diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 70fda09..646251c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -55,10 +55,11 @@ jobs: with: python-version: "3.12" - # --- Step 1: freeze the FastAPI backend into a single-file sidecar --- + # --- Step 1: freeze the FastAPI backend into a onedir sidecar folder --- # build_sidecar.* stages it as - # frontend/src-tauri/binaries/konduktor-sidecar-[.exe] - # which tauri.conf.json's externalBin bundles into the app. + # frontend/src-tauri/binaries/konduktor-sidecar/ + # which tauri.macos.conf.json (bundle.macOS.files, keeps its symlinks) / + # tauri.windows.conf.json (bundle.resources) put in the app as `sidecar/`. - name: Install backend deps working-directory: backend run: | diff --git a/BUILDING-WINDOWS.md b/BUILDING-WINDOWS.md index d3dfe8a..0224ce6 100644 --- a/BUILDING-WINDOWS.md +++ b/BUILDING-WINDOWS.md @@ -39,7 +39,7 @@ cd .. # 1) Freeze + stage the backend sidecar (from the activated backend venv) cd backend .\.venv\Scripts\Activate.ps1 # if not already active -.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar-.exe +.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar\ (a folder) cd .. # 2) Build the app @@ -56,7 +56,8 @@ frontend\src-tauri\target\release\bundle\msi\Konduktor_0.1.0_x64_en-US.msi frontend\src-tauri\target\release\bundle\nsis\Konduktor_0.1.0_x64-setup.exe ``` -Either one installs the app (bundling the sidecar `.exe` alongside it). +Either one installs the app, with the sidecar folder in its `sidecar\` resource +folder (`tauri.windows.conf.json`). ## Rebuilding after changes diff --git a/CLAUDE.md b/CLAUDE.md index c30fdf3..05af4e2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -568,7 +568,11 @@ Two independent apps that talk over HTTP: / `removed`), `audio` (Range), `art`, `upload` (into a folder CONFINED to the content folder — resolve then `is_relative_to`, so neither `..` nor a symlink escapes — never overwriting, `-2` suffixes, per-session - so a cancel deletes only its own), `fs/list|space`, `save`, `discard`, + so a cancel deletes only its own), `fs/list|space`, `folder/tracks|audio|leads` + (the content folder as a Files tree: tags via the shared `FolderScanner`, + file facts, `held` = file → the library's id; audio only for a file a + listing returned, confined; `leads` = the analysis lead per file, None + unless the platform analyses), `save`, `discard`, `history`, `export-sets`, and the stems routes below. Capabilities are the adapter's plus `tracks.audio_destination="library"`, `reference=False`, `paths.remappable=False`, `overwrite_risk="none"`. @@ -617,6 +621,21 @@ Two independent apps that talk over HTTP: Rekordbox's add analysis — waveform, grid AND key — is computed HERE (`core/add_analysis.prepare` with the lead the upload reports, sent as `NewTrack.analysis`). + **The content folder browsed like a drive** (decided 2026-10-10, + `folder.py`): `/api/fs/drives` lists the server FIRST (`kind: + "server"`, path `server:`) while a remote is open, and the ordinary + Files routes (`/api/fs/folders`, `/api/folder/*`) take `server:` + + the path ON THE SERVER — so the folder view, deck and add dialog need no + second set of routes, and a server path is never taken for the same path + here. `RemoteAdapter.folder_listing` remembers what was listed + (`ServerFiles`, a read-only source); `folder_audio` downloads into the + shared cache by the same facts as a library track's. Adding one is IN + PLACE (`on_library_host` → `importer.plan_on_host` + `run(reference=True)`): + nothing uploaded, nothing asked; files the library holds map to their + ids; where the server reports a lead the file is fetched and analysed + here, as an upload is. Server paths go back to the server in its own + spelling (`_server_paths`), never `str(Path(…))`, which rewrites them on + Windows. **Convert to Stems** (`stems/remote_convert.py`): the server plans (`/v1/stems/plan`, its `convert.plan`), this computer downloads, separates and encodes, uploads each verified file (`/v1/stems/stage`, @@ -791,9 +810,17 @@ Two independent apps that talk over HTTP: expandable Local Storage. A drive carrying a OneLibrary library opens as a device as before, and EVERY drive has a lazily-fetched **Files** tree; clicking a folder is the `folder` source kind — its audio in the ordinary - table, read-only via `readonly_cause: 'not_in_library'`, with files the - collection already holds checked off in the # column (`TrackTable`'s - `marked`). A browsed device is read-only (cause `browsing`); **"Open for + table, with files the collection already holds checked off in the # + column (`TrackTable`'s `marked`). **A held file's row IS the collection + track** (decided 2026-10-10: `main._folder_rows`; `FolderTracks.files` maps + its collection id back to the folder id that adding takes): it shows the + collection's key/rating/cues/plays, loads into the deck as origin + `collection` (`loadTrack`), edits inline and from the menu, and drops onto + a playlist directly. The table runs on the COLLECTION's capabilities; a + LOOSE row's edit — inline (`TableMeta.mayEdit`, asked before the editor + opens), rating, Edit Tags / Analyze / Auto Hotcues / Stems — asks to add + it first (`askToAdd`), and in the deck it stays read-only + (`not_in_library`). A browsed device is read-only (cause `browsing`); **"Open for editing…"** — the drive row's right-click menu, and a button while browsing a device whose caps say `browsing` — opens it as THE library via App's `openForEditing` (unsaved-edits confirm, source closed, library opened). @@ -848,8 +875,18 @@ Two independent apps that talk over HTTP: shell quits anyway after ~2 s without one, so a hung page cannot trap the user), quits (`quit_now`) when nothing is unsaved, else asks Save · Discard · Cancel; the sidecar is killed only at `RunEvent::Exit`, after the answer; - browser dev gets `beforeunload`), `SaveBar` (+ "Discard changes…" when - dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too), `Toolbar` (search/filters; columns are chosen by right-clicking the table header), + browser dev gets `beforeunload`), `StartupGate` (mounted in `main.tsx` + around everything but `AmbientBackdrop`: the shell opens the window AT ONCE + and starts the sidecar beside it, so nothing that calls the API mounts + until `backend_status` / `konduktor://backend` says ready, which is when + `setApiBase` gets the sidecar's address. Meanwhile `StartupScreen` shows + the icon with a generated waveform scrolling under a fixed playhead, a + "first launch takes longer" note after 6 s, Quit / Keep waiting after 90 s, + and if the sidecar exits its last 30 output lines with Copy details / Quit + / Try again (`backend_restart`). The shell has no timeout of its own. Before + ready it answers quit requests itself — nothing can be unsaved — and stops + at ready so it never races `QuitGuard`), `SaveBar` (+ "Discard changes…" when + dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too — and `AppSettings` ("Konduktor Settings…": app-level prefs, each with its default in `APP_SETTING_DEFAULTS` and read through `useAppSetting`; today `expandPlaylistFolders` and `exportRootFolder`, both default off — the latter read by the backend at `run_export` and passed down as `ExportPayload.root_folder`. The Sidebar holds folder open state as per-id overrides of that setting, reset on a new library or a change of the setting, and carried to the new ids when a rename/move changes a folder's path id)), `Toolbar` (search/filters; columns are chosen by right-clicking the table header), `TrackTable` (**the one track list** — All Tracks, playlists, exports and devices. TanStack Table + **virtualized** grid; per-row play button, configurable columns, header sorting, inline double-click editing, and @@ -1413,7 +1450,11 @@ serialization path.** It enforces: only the edited `` THROUGH the trip, one download per file, Analyze on the cached copy, export (and a re-export copying nothing), an upload stored in the mapping's stored form, takeover → read-only at once, - reopening names the holder and the edits left, leaving releases. + reopening names the holder and the edits left, leaving releases. And the + content folder as a drive: listed first, confined, held files ticked off, + auditioned with one download, an add IN PLACE (no upload, the held one not + added twice, both into the playlist, analysed here when the server reports + a lead). - `test_remote_stems.py` — Convert to Stems on a remote with the FAKE engine: the plan's transfer and two-machine space, Replace parks and swaps ON THE SERVER (saved file untouched until Save, which deletes the parked @@ -1442,6 +1483,13 @@ frontend at `http://localhost:5173`. `masterdb` and `tables` → `models` and moved `BLOB` out of `db6.database`; the Rekordbox adapter uses the new names. `db6` still works as a deprecated alias and is **removed in 0.6.0**. + **PyAV: open files for reading through `core/pyav.open_input`, never + `av.open` directly.** PyAV 18 refuses a file with non-UTF-8 tags unless + given `metadata_errors="ignore"`; PyAV 19 removed that keyword. CI installs + fresh (it got 19) while a dev venv keeps what it had (18), so code passing + the keyword passed every local test and shipped a release whose deck played + every stem track as the mix. `requirements.txt` caps `av<20`: check + `pyav.py` before raising it. 2. **The collection is real, irreplaceable data — protect it.** Every save writes a timestamped `.bak` first (into a `backups/` folder next to the collection). When testing writes, point `KONDUKTOR_NML` at a COPY. Warn the @@ -1451,6 +1499,21 @@ frontend at `http://localhost:5173`. render is the library's own pipeline (see "Write path"), which reproduces Traktor's byte-exact layout so a no-op save is byte-identical and only edited objects diff. `test_save_fidelity.py` enforces this. +4. **The desktop sidecar is a PyInstaller ONEDIR folder — never go back to + onefile.** A onefile binary unpacked ~390 native libraries into a NEW temp + folder on every launch, and macOS (XProtect / syspolicyd) checks each library + it has not seen before as it is dlopen()ed, keyed per FILE: the window + appeared only after ~10 s on every launch (measured 2026-10-12: 95 s to load + them all fresh, 1 s once seen). As a folder in the app they are checked + once; a launch is ~0.5 s. `build_sidecar.*` stages + `src-tauri/binaries/konduktor-sidecar/`; `lib.rs` spawns + `/sidecar/konduktor-sidecar[.exe]`. On macOS it is bundled by + `tauri.macos.conf.json`'s `bundle.macOS.files`, NOT `bundle.resources`: + the resource copier follows symlinks, turning PyInstaller's 37 library + aliases (`_internal/libavcodec… -> av/.dylibs/…`, `Python.framework`'s + `Versions/Current`) into second copies a library could be loaded twice + from. Windows has no such links and uses `resources` + (`tauri.windows.conf.json`). ## Data model notes @@ -1716,7 +1779,11 @@ that number and nothing else — everything derives from it: **volume-relative** `DIR`, never a host path — so a USB export is portable by construction, and the `.nml` cannot be written until the destination is known. Also settled: loose tracks land in an **"Other" playlist**, playlist folders - are preserved, and the export is a **standalone `collection.nml`** the user + are preserved — at the exported library's TOP LEVEL by default; the + `exportRootFolder` setting (`ExportPayload.root_folder`) nests the whole + tree, Other included, in one folder named after the export, in all four + writers (decided 2026-10-12: the export is a library of its own, so the + wrapper was one more click at the gig), and the export is a **standalone `collection.nml`** the user swaps into a Traktor install — so it needs the full skeleton, verified from the real file: ``, ``, ``, ``, `` wrapping a `$ROOT` FOLDER node with a diff --git a/README.md b/README.md index a15304b..4c4fe06 100644 --- a/README.md +++ b/README.md @@ -1,256 +1,141 @@ -# Konduktor +

+ Konduktor icon +

-**A fast, modern home for your Traktor collection.** +

Konduktor

-Konduktor is a lightweight desktop-style app for DJs who run **Native -Instruments Traktor** (Pro 4 / NML v20). It opens your existing -`collection.nml`, gives you a beautiful dark library to explore, and lets you -build playlists and prep tracks — without launching the whole heavyweight -Traktor app just to tidy up your tags or drop a few cue points. +

+ Prep your tracks and run your DJ libraries in one fast app.
+ Traktor, Rekordbox, or the USB stick in your pocket. +

-Your collection stays exactly where it is. Konduktor reads and writes the same -file Traktor uses, so everything you do shows up next time you open Traktor. +

+ Download for macOS & Windows +

+ +![Konduktor: the prep deck with a track loaded, above a playlist](docs/screenshots/library.png) + +Konduktor opens the library you already have, in the format it already uses. +You can tidy tags, build playlists, set grids and cues, and pack a USB stick +for the gig without launching your full DJ software. When you open your DJ +software again, everything you changed is there. --- -## Why you'll like it +## One app for every library -- **Instant, searchable library.** Your whole collection loads into a snappy, - virtualized grid. Search, filter by genre / key / BPM / rating, and sort by - any column — all instant, no waiting. -- **Make it yours.** Show only the columns you care about, drag them into the - order you like, and resize them to fit. Your layout is remembered. -- **Edit tags without the ceremony.** Double-click any field to fix a title or - genre on the spot, click the stars to rate a track, or right-click for a full - tag + cover-art editor. Great for quick one-off fixes. -- **Playlists, the easy way.** Create, rename, and delete playlists, then - drag-and-drop to reorder or add tracks. -- **A real prep deck.** Load any track into the deck at the top and: - - play it with a **frequency-colored waveform** (Traktor-style Spectrum look), - scrolling under a fixed playhead with zoom in/out - - scratch it by dragging the waveform - - see and adjust the **beatgrid** and BPM - - set, jump to, and delete **hotcues** (with a color-coded 8-slot bar) - - build **loops** in fixed beat sizes, tied into the hotcue system - - use keyboard shortcuts: **Space** to play/pause, **1–8** to fire hotcues, - **Shift+1–8** to clear them -- **Your data is safe.** Every save makes a timestamped backup first, and only - ever touches the parts you changed — the rest of the file stays byte-for-byte - identical. +Choosing a platform: Rekordbox, Traktor, OneLibrary or Remote + +- **Traktor** collections. +- **Rekordbox** libraries. +- **OneLibrary** USB sticks, the format CDJs read. Plug one in to browse it, + preview tracks off it, import them, or edit the stick directly. +- **Remote** libraries: keep your whole library and music on a home server and + open it from any laptop ([set up a server](docs/REMOTE-SERVER.md)). +- **Any folder or drive**: browse loose audio files, preview them, and add + them to your library. + +Your library is never converted into a Konduktor database. Saves write back to +the original file and change only what you edited. + +
+ +## A real prep deck + +![The prep deck in beatgrid editing mode](docs/screenshots/deck.png) + +- A scrolling waveform, coloured by frequency, with zoom, scratching and an + overview of the whole track. +- Eight hotcue pads with names, types and colours, plus beat loops, beat jump + and tap tempo. +- **Beatgrid editing**, including grids with tempo changes. Nudge, retempo, + halve or double without opening your DJ software. +- Keyboard shortcuts for the whole deck: Space to play, 1–8 for hotcues, + arrow keys to jump or move a loop. + +## Stems, built in + +![A stem file in the deck: drums, bass, synths and vocals each in their own lane](docs/screenshots/stems.png) + +**Play stem files as stems.** Load a stem file and the deck splits into +drums, bass, synths and vocals, each drawn in its own lane. Click a lane's +button to mute it, Alt/Option-click to solo it, or use Q W E R. + +**Convert to Stems.** In a Traktor collection, right-click any tracks and +choose Convert to Stems. They come back as standard Traktor stem files with their tags, cover art, cues and +beatgrid intact. + +- The separation runs on your own computer, so your music isn't sent to an + online service. +- Replace the originals, or save the stems to a folder and add them as new + tracks. +- Convert a whole playlist in one go. + +## Let it do the boring parts + +| Auto Hotcues | Analyze | +|:---:|:---:| +| ![Auto Hotcues: choose an event for each pad](docs/screenshots/auto-hotcues.png) | ![Analyze: BPM, grid and key](docs/screenshots/analyze.png) | +| Pick an event for each pad (first beat, build, drop, breakdown, outro). Konduktor finds them in the track and places the cues. Run it on one track or a whole playlist. | Detects tempo, beatgrid and musical key, for one track or hundreds. | + +## Export to USB for CDJs, or other platforms + +An export set for OneLibrary, Traktor and Rekordbox + +Make an **export** in the sidebar, drag playlists onto it, and press Export. +One stick can carry a Traktor collection, a OneLibrary library for current +CDJs and a Rekordbox Device Library for older players, all sharing **one copy +of the audio**. + +- Hotcues, memory cues, loops, grids, keys and cover art are converted for + each platform. +- Playlists stay linked: edit a playlist, re-export, and the stick catches up. +- Re-exports copy only what changed, so updating a stick is quick. +- Konduktor only ever clears a folder that it wrote itself. + +
+ +## Your library is safe + +- **Saves are surgical.** A Traktor save changes only the entries you edited. + The rest of the file stays byte-for-byte identical. +- **Backups and history.** Every Traktor save makes a backup first and is kept + in a version history that you can restore from in the app. +- **Nothing is written until you press Save.** Discard changes throws away + everything you did since your last save. +- Tag edits are also written into the audio files themselves, so other apps + see them too. + +## And also + +- A fast library with search, filters, sorting and columns you can rearrange, + even with thousands of tracks. +- Edit tags inline or in a full tag and cover-art editor. +- Drag and drop tracks onto playlists, exports or the deck, and drag playlists + to reorganise them. +- If you open a Traktor collection on a different computer or drive, + Konduktor finds the missing files for you. --- -## Getting started +## Get Konduktor -Konduktor runs as two small local servers (a Python backend and a web -frontend). Do the one-time setup, then start them — the same steps work on -macOS, Linux, and Windows. +Download the latest build from +[**Releases**](https://github.com/MrPatben8/konduktor/releases): +a `.dmg` for macOS (Apple Silicon) and a `-setup.exe` for Windows. -### 1. Install (once) +> **First launch:** builds aren't notarised yet, so your OS will warn you the +> first time. +> **macOS:** right-click the app, choose **Open**, then **Open** again. If it +> still refuses, run `xattr -cr /Applications/Konduktor.app` once. +> **Windows:** click **More info → Run anyway**. -**Backend** — needs Python 3.11+. Create a virtual environment and install the -dependencies: +> **Using Traktor?** Close it before saving in Konduktor. Traktor rewrites +> `collection.nml` when it quits, which would overwrite your changes. -```bash -cd backend -python3 -m venv .venv # Windows: python -m venv .venv -``` +Want to run it from source or build it yourself? See +[docs/BUILDING.md](docs/BUILDING.md). -Activate it, then install: +## License -```bash -source .venv/bin/activate # Windows (PowerShell): .\.venv\Scripts\Activate.ps1 -pip install -r requirements.txt -cd .. -``` - -**Frontend** — needs Node 18+ (same on every platform): - -```bash -cd frontend -npm install -cd .. -``` - -### 2. Run it (development) - -Konduktor runs as two local servers (backend on `:8000`, frontend on `:5173`). - -**macOS / Linux** — one command starts both: - -```bash -./dev.sh -``` - -**Windows** — start each server in its own terminal: - -```powershell -# Terminal 1 — backend -cd backend; .\.venv\Scripts\Activate.ps1; uvicorn konduktor.main:app --reload --port 8000 - -# Terminal 2 — frontend -cd frontend; npm run dev -``` - -Either way, open **http://localhost:5173** in your browser (`Ctrl-C` stops a -server). This is the fastest way to try Konduktor or hack on it — the frontend -hot-reloads as you edit. To package a real double-clickable app instead, see -[Build a standalone app](#build-a-standalone-app-production) below. - -### 3. Open your collection - -On launch, Konduktor offers to: - -- **Automatically** open the collection from your latest installed Traktor, -- reopen the **last collection** you used, or -- **browse** for a `collection.nml` yourself. - -That's it — you're in. - ---- - -## Build a standalone app (production) - -Prefer a real double-clickable app over running the dev servers? Konduktor -packages into a native desktop app (via **Tauri**) that bundles the Python -backend as a sidecar — no terminal, no servers to start by hand. - -### Extra prerequisites - -On top of the Python 3.11+ and Node 18+ from above: - -- **Rust** — install from (the app shell is Tauri/Rust). -- **PyInstaller** — into the backend venv: - `pip install -r backend/requirements-build.txt` -- **Windows only:** also the MSVC C++ build tools and the WebView2 runtime — see - [BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the one-time toolchain setup. - -The build is a two-step recipe on both platforms: **freeze the backend into a -sidecar binary**, then **build the app**. The only difference is which sidecar -script you run — `.sh` on macOS/Linux, `.ps1` on Windows. Each build runs on its -own OS (the app can't be cross-compiled). - -### macOS / Linux - -```bash -# 1) Freeze the backend into a sidecar binary (from the activated backend venv) -cd backend && source .venv/bin/activate && ./build_sidecar.sh && cd .. - -# 2) Build the app -cd frontend && npx tauri build -``` - -The installer lands at -`frontend/src-tauri/target/release/bundle/dmg/Konduktor__aarch64.dmg` -(with the `.app` beside it). - -### Windows - -```powershell -# 1) Freeze the backend into a sidecar binary (from the activated backend venv) -cd backend; .\.venv\Scripts\Activate.ps1; .\build_sidecar.ps1; cd .. - -# 2) Build the app -cd frontend; npx tauri build -``` - -The installers land in `frontend\src-tauri\target\release\bundle\` (an `.msi` and -an NSIS `-setup.exe`). See [BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the full -walkthrough and Windows-specific notes. - -> **First launch — getting past the OS security prompt.** Builds are -> **ad-hoc signed, not notarized** (no paid Apple/Windows developer cert yet), so -> the OS flags them the first time. This is expected — the app isn't damaged. -> -> - **macOS:** right-click the app → **Open** → **Open** (or System Settings → -> Privacy & Security → **Open Anyway** after the first blocked attempt). If it -> still refuses — common for a `.dmg` downloaded via a browser, which macOS -> quarantines — clear the quarantine flag once from Terminal: -> ```bash -> xattr -cr /Applications/Konduktor.app -> ``` -> - **Windows:** click **More info → Run anyway** past SmartScreen. -> -> The macOS `.dmg` is Apple-Silicon (`aarch64`) only. - -> **Faster local builds:** `npx tauri build --debug --bundles app` skips the -> optimizer and the installer, giving you a runnable app in seconds — handy while -> iterating. - -### Rebuilding after changes - -Changed **backend** Python? Re-run the sidecar script for your OS -(`./build_sidecar.sh` or `.\build_sidecar.ps1`), then `npx tauri build`. -Frontend-only change? Just `npx tauri build` — it rebuilds the web app for you. - ---- - -## Saving back to Traktor - -Playlist edits, tag changes, and prep tweaks all apply live in the app. When -you're happy, hit **Save to Traktor** to write them to `collection.nml`. - -> ⚠️ **Close Traktor before saving.** Traktor rewrites `collection.nml` when it -> quits, so if it's open it will overwrite your changes. Konduktor always writes -> a backup first (into a `backups/` folder next to your collection), but closing -> Traktor first is the safe habit. - -Want to experiment risk-free? Point Konduktor at a *copy* of your collection and -play around. - ---- - -## A remote library (Konduktor server on a NAS) - -Keep your whole library — the collection file and the music — on a server, and -open it from any computer with Konduktor. Prep tracks, edit playlists, and -export sticks for your gigs without the music ever living on your performance -laptop. - -The server is a small container (`server/`). It holds the library and saves it. -Playback, analysis and stem separation run on the computer you open it from, -on copies it downloads, so the server needs no GPU and does very little work. - -**On the server (e.g. TrueNAS SCALE):** - -1. Copy `server/compose.yaml` and `server/.env.example` (renamed to `.env`) - onto the NAS. Point the volumes at your datasets, and fill in `.env`: the - platform (`traktor` or `rekordbox`), the library file, the music folder, a - username and password, and — for a collection made on a Mac — the path - mapping (`/Users/you/Music => /music`). -2. Install it: on TrueNAS, **Apps → Discover Apps → ⋮ → Install via YAML** and - paste the compose file; anywhere else, `docker compose up -d`. A bad setting - stops the container with one clear line in its log. - -**In the app:** choose **Remote** on the platform screen → **Add a remote -library** → enter the server's address (and a fallback, such as its Tailscale -address, for when you're away from home), the username and the password. -Konduktor checks the server before it saves the remote, and keeps the -password in your keychain. - -Good to know: - -- **One computer at a time.** If another computer has the library open, - Konduktor says who has it and offers to take over. Edits that computer - hadn't saved stay with the library, and you're asked to save or discard - them. -- **Plain HTTP.** Reach the server over your home network or a VPN - (Tailscale / WireGuard). Don't expose its port to the internet. -- **Unsaved edits live on the server** until you save. Restarting the - container drops them. -- Downloaded tracks are cached on your computer (Settings → **Remote audio** - sets the size), so a track you've prepped and then export is fetched once. - ---- - -## Good to know - -- Konduktor is built on [`traktor-nml-utils`](https://github.com/MrPatben8/traktor-nml-utils) - and speaks Traktor's real file format — no import/export, no separate database. -- Run it in your browser from source, or package it into a native desktop app - (macOS `.dmg` / Windows `.msi`) that bundles the backend — see - [Build a standalone app](#build-a-standalone-app-production). A mobile version - is on the horizon. -- Under the hood: **FastAPI** (Python) backend + **React / TypeScript / Vite** - frontend. Curious about internals or contributing? See - [CLAUDE.md](CLAUDE.md) for the architecture and conventions. +[AGPL-3.0](LICENSE) diff --git a/backend/build_sidecar.ps1 b/backend/build_sidecar.ps1 index 4288a66..c5196ec 100644 --- a/backend/build_sidecar.ps1 +++ b/backend/build_sidecar.ps1 @@ -1,6 +1,7 @@ -# Build the frozen backend sidecar on Windows (PyInstaller) and stage it for -# Tauri as binaries\konduktor-sidecar-.exe. -# Output: backend\dist\konduktor-sidecar.exe + frontend\src-tauri\binaries\... +# Build the frozen backend sidecar on Windows (a PyInstaller onedir folder) and +# stage it for Tauri as frontend\src-tauri\binaries\konduktor-sidecar\, which +# tauri.conf.json bundles as a resource folder (`sidecar\` in the app). +# Output: backend\dist\konduktor-sidecar\ + frontend\src-tauri\binaries\konduktor-sidecar\ # # Run from a PowerShell prompt with the backend venv's Python on PATH, e.g.: # cd backend @@ -16,12 +17,13 @@ $Py = Join-Path $Root ".venv\Scripts\python.exe" if (-not (Test-Path $Py)) { $Py = "python" } & $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec -Write-Host "Built: $Root\dist\konduktor-sidecar.exe" +if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed ($LASTEXITCODE)" } +Write-Host "Built: $Root\dist\konduktor-sidecar\" -# Stage for Tauri: name with the host target triple + .exe so the shell plugin -# resolves it. (rustc must be on PATH.) -$Triple = (& rustc -vV | Select-String '^host: ').ToString().Replace('host: ', '').Trim() +# Stage for Tauri, replacing the whole folder so no file from an older build survives. $Dest = Join-Path $Root "..\frontend\src-tauri\binaries" New-Item -ItemType Directory -Force -Path $Dest | Out-Null -Copy-Item "$Root\dist\konduktor-sidecar.exe" (Join-Path $Dest "konduktor-sidecar-$Triple.exe") -Force -Write-Host "Staged: $Dest\konduktor-sidecar-$Triple.exe" +$Staged = Join-Path $Dest "konduktor-sidecar" +if (Test-Path $Staged) { Remove-Item -Recurse -Force $Staged } +Copy-Item -Recurse "$Root\dist\konduktor-sidecar" $Staged +Write-Host "Staged: $Staged\" diff --git a/backend/build_sidecar.sh b/backend/build_sidecar.sh index ac8c7b8..4ad1d7c 100755 --- a/backend/build_sidecar.sh +++ b/backend/build_sidecar.sh @@ -1,7 +1,8 @@ #!/usr/bin/env bash -# Build the frozen backend sidecar (single-file binary) with PyInstaller and -# stage it for Tauri as binaries/konduktor-sidecar-. -# Output: backend/dist/konduktor-sidecar + frontend/src-tauri/binaries/… +# Build the frozen backend sidecar (a onedir folder) with PyInstaller and stage +# it for Tauri as frontend/src-tauri/binaries/konduktor-sidecar/, which +# tauri.conf.json bundles as a resource folder (`sidecar/` in the app). +# Output: backend/dist/konduktor-sidecar/ + frontend/src-tauri/binaries/konduktor-sidecar/ # # One-time: pip install -r requirements-build.txt (into the backend venv). set -euo pipefail @@ -9,25 +10,20 @@ ROOT="$(cd "$(dirname "$0")" && pwd)" cd "$ROOT" PY="${PY:-.venv/bin/python}" "$PY" -m PyInstaller --noconfirm --clean konduktor-sidecar.spec -echo "Built: $ROOT/dist/konduktor-sidecar" +echo "Built: $ROOT/dist/konduktor-sidecar/" -# NOTE: do NOT re-codesign this binary. PyInstaller already ad-hoc signs the -# one-file bootloader AND its packed libraries (Python.framework, etc.) with a -# matching identity. Re-signing only the outer bootloader (e.g. `codesign -s -`) -# desyncs the Team IDs, so at runtime dlopen of the extracted Python framework -# fails with "different Team IDs" and the sidecar dies on launch (which makes -# the Tauri app panic: "backend sidecar did not report a port"). The app bundle -# is ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`, -# which seals this binary without re-signing it. +# NOTE: do NOT re-codesign anything in this folder. PyInstaller already ad-hoc +# signs the executable AND its collected libraries (Python, the .so/.dylib +# files) with a matching identity. Re-signing only some of them desyncs the +# Team IDs, so dlopen fails with "different Team IDs" and the sidecar dies on +# launch (the app then shows "Konduktor couldn't start"). The app bundle is +# ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`, +# which seals this folder as a resource without re-signing it. -# Stage for Tauri: the sidecar must be named with the host target triple so the -# shell plugin can resolve it in both dev and bundle. (rustc must be on PATH.) -if command -v rustc >/dev/null 2>&1; then - TRIPLE="$(rustc -vV | sed -n 's/host: //p')" - DEST="$ROOT/../frontend/src-tauri/binaries" - mkdir -p "$DEST" - cp "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar-$TRIPLE" - echo "Staged: $DEST/konduktor-sidecar-$TRIPLE" -else - echo "warning: rustc not found — skipped staging the Tauri sidecar binary" >&2 -fi +# Stage for Tauri. Replace the whole folder so no file from an older build +# survives; `cp -R` keeps PyInstaller's symlinks as symlinks. +DEST="$ROOT/../frontend/src-tauri/binaries" +mkdir -p "$DEST" +rm -rf "$DEST/konduktor-sidecar" +cp -R "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar" +echo "Staged: $DEST/konduktor-sidecar/" diff --git a/backend/konduktor-sidecar.spec b/backend/konduktor-sidecar.spec index fb2f436..3ab53f6 100644 --- a/backend/konduktor-sidecar.spec +++ b/backend/konduktor-sidecar.spec @@ -1,6 +1,14 @@ # PyInstaller spec for the Konduktor backend sidecar (Step 1 of the standalone -# build). Produces a single-file binary that serves the FastAPI API on a free -# loopback port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh) +# build). Produces a ONEDIR build — dist/konduktor-sidecar/ holding the +# executable plus `_internal/` — that serves the FastAPI API on a free loopback +# port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh) +# +# Onedir, NOT onefile: a onefile binary unpacks ~300 MB (1,000+ files, ~390 +# native libraries) into a NEW temp folder on every launch, and macOS checks +# every library it has not seen before (XProtect / syspolicyd) as it is +# dlopen()ed, keyed per file — so every launch paid ~10 s before the window +# appeared (measured 2026-10-12: the same libraries took 95 s fresh, 1 s once +# seen). Installed as a folder inside the app, they are checked once. # # The tricky bits this handles: # - uvicorn imports its loop/protocol backends dynamically → collect_submodules @@ -82,9 +90,8 @@ pyz = PYZ(a.pure) exe = EXE( pyz, a.scripts, - a.binaries, - a.datas, [], + exclude_binaries=True, name="konduktor-sidecar", debug=False, bootloader_ignore_signals=False, @@ -97,3 +104,12 @@ exe = EXE( codesign_identity=None, entitlements_file=None, ) + +coll = COLLECT( + exe, + a.binaries, + a.datas, + strip=False, + upx=False, + name="konduktor-sidecar", +) diff --git a/backend/konduktor/adapters/onelibrary/export.py b/backend/konduktor/adapters/onelibrary/export.py index c7ec9ea..b9af620 100644 --- a/backend/konduktor/adapters/onelibrary/export.py +++ b/backend/konduktor/adapters/onelibrary/export.py @@ -381,7 +381,8 @@ class OneLibraryExporter: # ---- playlists ----------------------------------------------------------- def _write_playlists(self, con, payload: ExportPayload, by_source: dict) -> None: - """One folder named after the export, with the tree preserved under it. + """The tree preserved — at the top level (parent NULL), or with + `payload.root_folder` under one folder named after the export. `playlist` is a flat table with `playlist_id_parent`, so folders and playlists are the same row kind told apart by `attribute` (1 = folder). @@ -397,8 +398,8 @@ class OneLibraryExporter: ) return next_id[0] - root = add(payload.name, None, folder=True) - folders: dict[tuple[str, ...], int] = {(): root} + root = add(payload.name, None, folder=True) if payload.root_folder else None + folders: dict[tuple[str, ...], int | None] = {(): root} for playlist in payload.playlists: parent = root diff --git a/backend/konduktor/adapters/rekordbox/device_export.py b/backend/konduktor/adapters/rekordbox/device_export.py index f697080..7c967d2 100644 --- a/backend/konduktor/adapters/rekordbox/device_export.py +++ b/backend/konduktor/adapters/rekordbox/device_export.py @@ -198,8 +198,9 @@ class RekordboxDeviceExporter: @staticmethod def _playlists(payload: ExportPayload, by_source: dict) -> tuple[list[bytes], list[bytes]]: - """The tree under one folder named after the export, as the other - targets build it. `sort_order` is a node's position among its siblings.""" + """The tree as the other targets build it — at the top level (parent + 0), or with `payload.root_folder` under one folder named after the + export. `sort_order` is a node's position among its siblings.""" tree: list[bytes] = [] entries: list[bytes] = [] next_id = [0] @@ -220,7 +221,7 @@ class RekordboxDeviceExporter: index += 1 entries.append(pdb.playlist_entry_row(index, track_id, playlist_id)) - root = add(payload.name, 0, folder=True) + root = add(payload.name, 0, folder=True) if payload.root_folder else 0 folders: dict[tuple[str, ...], int] = {(): root} for playlist in payload.playlists: parent = root diff --git a/backend/konduktor/adapters/rekordbox/export.py b/backend/konduktor/adapters/rekordbox/export.py index 670a294..57e9e1d 100644 --- a/backend/konduktor/adapters/rekordbox/export.py +++ b/backend/konduktor/adapters/rekordbox/export.py @@ -383,9 +383,12 @@ class RekordboxExporter: # ---- playlists --------------------------------------------------------------- def _write_playlists(self, db, payload: ExportPayload, rows: dict) -> None: - """The tree, under one folder named after the export.""" - root = db.create_playlist_folder(payload.name) - db.flush() + """The tree — at the top level, or with `payload.root_folder` under one + folder named after the export (None = the top level).""" + root = None + if payload.root_folder: + root = db.create_playlist_folder(payload.name) + db.flush() folders: dict[tuple[str, ...], object] = {(): root} for playlist in payload.playlists: diff --git a/backend/konduktor/adapters/remote/adapter.py b/backend/konduktor/adapters/remote/adapter.py index 949557f..fb85628 100644 --- a/backend/konduktor/adapters/remote/adapter.py +++ b/backend/konduktor/adapters/remote/adapter.py @@ -30,6 +30,7 @@ from ... import remote_protocol as rp from ...core.adapter import ( AudioFacts, FileTagResult, + NotFound, SaveOutcome, Unavailable, Unsupported, @@ -39,6 +40,7 @@ from ...core.query import TrackIndex from .cache import RemoteAudioCache, StaleFacts from .cache import shared as shared_cache from .client import RemoteClient, SessionLost +from .folder import ServerFile, ServerFiles from .session import RemoteSession _NOT_HERE = "A remote library's paths are the server's configuration" @@ -60,6 +62,13 @@ class RemoteAdapter: self._facts: dict[str, AudioFacts] = {} #: Server path of an upload → (the local file it came from, its analysis lead). self._uploads: dict[str, tuple[Path, float | None]] = {} + #: Content-folder files a listing returned, by their server path. + self._listed: dict[str, ServerFile] = {} + #: `str(Path(p))` → `p` for every server path this side has turned into + #: a `Path` (an upload's target, a listed file): on Windows that + #: conversion rewrites the separators, and the server must get its own + #: spelling back. + self._server_paths: dict[str, str] = {} self._dirty = bool(hello.get("dirty")) self._load() @@ -260,6 +269,7 @@ class RemoteAdapter: self.session.lost(ex.holder) raise self._uploads[landed["path"]] = (Path(source), landed.get("analysis_lead")) + self._server_paths[str(Path(landed["path"]))] = landed["path"] return Path(landed["path"]) def free_space(self, path: str) -> int: @@ -268,8 +278,13 @@ class RemoteAdapter: def delete_upload(self, path) -> None: """Undo `upload_audio` (a cancelled or failed import).""" - self._uploads.pop(str(path), None) - self.client.delete_upload(str(path)) + key = self._server_key(path) + self._uploads.pop(key, None) + self.client.delete_upload(key) + + def _server_key(self, path) -> str: + text = str(path) + return self._server_paths.get(text, text) def add_tracks(self, items, *, checkpoint=None): """Add uploaded files. Where the platform analyses what it adds (the @@ -279,10 +294,20 @@ class RemoteAdapter: wire = [] total = len(items) - for n, item in enumerate(items, start=1): - key = str(item.audio_path) + keys = [self._server_key(item.audio_path) for item in items] + # Files already in the content folder (added in place): the server says + # whether the platform analyses, and only then is the file fetched. + in_place = [k for k, item in zip(keys, items) + if item.analysis is None and k not in self._uploads and k in self._listed] + leads = self.client.folder_leads(in_place) if in_place else {} + for n, (item, key) in enumerate(zip(items, keys), start=1): source, lead = self._uploads.get(key, (None, None)) analysis = item.analysis + if analysis is None and source is None and leads.get(key) is not None: + lead = leads[key] + if checkpoint is not None: + checkpoint(f"Downloading {item.track.title or Path(key).name} ({n}/{total})", step=n, of=total) + source = self.folder_audio(key) if analysis is None and lead is not None and source is not None: if checkpoint is not None: checkpoint(f"Analysing {item.track.title or source.name} ({n}/{total})", step=n, of=total) @@ -302,8 +327,8 @@ class RemoteAdapter: self.session.lost(ex.holder) raise self._apply(envelope) - for item in items: - self._uploads.pop(str(item.audio_path), None) + for key in keys: + self._uploads.pop(key, None) return envelope["result"] def apply_stem_swaps(self, swaps, *, add_to_playlist=None): @@ -393,6 +418,46 @@ class RemoteAdapter: facts = self.audio_facts([track_id]).get(track_id) return self.cache.get(facts) if facts else None + # ---- the content folder, browsed -------------------------------------------------- + def folder_listing(self, path: str | None) -> ServerFiles: + """The audio directly inside a content folder (None: the folder itself), + as the server lists it — and remembered, so a file can then be played + or added by its path.""" + listing = ServerFiles.from_wire(self, self.client.folder_tracks(path)) + with self._lock: + self._listed = {k: f for k, f in self._listed.items() if f.folder != listing.path} + self._listed.update(listing.files) + self._server_paths.update({str(Path(k)): k for k in listing.files}) + return listing + + def listed_files(self, paths) -> ServerFiles | None: + """The listed files among `paths` as one source (they may come from + several folders); None when none of them was listed.""" + with self._lock: + found = [self._listed[p] for p in paths if p in self._listed] + return ServerFiles(self, found[0].folder, found) if found else None + + def folder_audio(self, path: str, *, progress=None) -> Path: + """A local copy of a listed file, downloaded into the shared cache — + keyed by the same facts as a library track's, so a file that is both + downloads once.""" + for attempt in range(2): + with self._lock: + found = self._listed.get(path) + if found is None: + raise NotFound("File not found — browse to its folder first") + cached = self.cache.get(found.facts) + if cached is not None: + return cached + try: + return self.cache.fetch( + found.facts, lambda partial: self.client.folder_download(path, partial, progress=progress)) + except StaleFacts: + if attempt: + raise + self.folder_listing(found.folder) # changed on the server: re-read it + raise NotFound(path) + # ---- paths: the server's business ------------------------------------------------ def set_path_mapping(self, mapping): raise Unsupported(_NOT_HERE) diff --git a/backend/konduktor/adapters/remote/client.py b/backend/konduktor/adapters/remote/client.py index 2291bad..9e45487 100644 --- a/backend/konduktor/adapters/remote/client.py +++ b/backend/konduktor/adapters/remote/client.py @@ -246,6 +246,29 @@ class RemoteClient: def fs_list(self, path: str | None) -> dict: return self.request("GET", "/v1/fs/list", params={"path": path} if path else None).json() + def folder_tracks(self, path: str | None) -> dict: + return self.request("GET", "/v1/folder/tracks", params={"path": path} if path else None, + timeout=None).json() + + def folder_leads(self, paths: list[str]) -> dict[str, float | None]: + return self.request("POST", "/v1/folder/leads", json={"paths": paths}).json()["leads"] + + def folder_download(self, path: str, target: Path, *, progress=None) -> dict: + """Stream a listed content-folder file into `target` (as `download`).""" + with self.stream("GET", "/v1/folder/audio", params={"path": path}, timeout=None) as response: + if response.status_code >= 400: + response.read() + self.check(response) + with open(target, "wb") as out: + for chunk in response.iter_bytes(1 << 20): + out.write(chunk) + if progress is not None: + progress(len(chunk)) + return { + "size": int(response.headers.get("X-Konduktor-Size") or 0), + "mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0), + } + def fs_space(self, path: str | None) -> int: return int(self.request("GET", "/v1/fs/space", params={"path": path} if path else None).json()["free"]) diff --git a/backend/konduktor/adapters/remote/folder.py b/backend/konduktor/adapters/remote/folder.py new file mode 100644 index 0000000..16273b7 --- /dev/null +++ b/backend/konduktor/adapters/remote/folder.py @@ -0,0 +1,102 @@ +"""The server's content folder, browsed from this computer like a drive. + +The sidebar's Files trees read folders on THIS computer (`core/folder.py`). On a +remote library the music lives in the server's content folder, which this +computer cannot see — so the server lists it (`/v1/folder/tracks`: tags, file +facts, and which files the library already holds) and this module holds the +answer as a read-only SOURCE, the shape the table, the deck and the importer +already read. + +Adding one of these files never uploads anything: it is already where the +library can reach it, so it is added IN PLACE (`on_library_host`), and the +importer skips both the copy and the copy-or-reference question. + +Ids are the file's path ON THE SERVER — a string, never a `Path` on this side +until the importer needs one, because a server path is not a path here (on a +Windows laptop `Path("/music/x.mp3")` is `\\music\\x.mp3`). +""" +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +from ...core.adapter import AudioFacts +from ...core.model import PlaylistNode, Track, TrackCues + + +@dataclass +class ServerFile: + folder: str + track: Track + facts: AudioFacts + #: The library's id for this file, when it already points at it. + held: str | None = None + + +class ServerFiles: + """Files in the content folder, as the read half of a source.""" + + #: The importer's cue that these are already on the machine holding the + #: library: added where they are, neither copied nor uploaded. + on_library_host = True + + def __init__(self, adapter, path: str, files: list[ServerFile]): + self.adapter = adapter + self.path = path + self._files = {f.track.id: f for f in files} + + @classmethod + def from_wire(cls, adapter, body: dict) -> "ServerFiles": + folder = body["path"] + facts = body.get("files") or {} + held = body.get("held") or {} + files = [] + for raw in body.get("tracks") or []: + track = Track.model_validate(raw) + fact = facts.get(track.id) + if fact is None: + continue + files.append(ServerFile( + folder=folder, track=track, + facts=AudioFacts(key=track.id, size=int(fact["size"]), mtime_ns=int(fact["mtime_ns"])), + held=held.get(track.id), + )) + return cls(adapter, folder, files) + + @property + def files(self) -> dict[str, ServerFile]: + return self._files + + @property + def tracks(self) -> list[Track]: + return [f.track for f in self._files.values()] + + def track(self, track_id: str) -> Track | None: + found = self._files.get(track_id) + return found.track if found else None + + def held(self, track_id: str) -> str | None: + found = self._files.get(track_id) + return found.held if found else None + + def size(self, track_id: str) -> int: + found = self._files.get(track_id) + return found.facts.size if found else 0 + + def track_cues(self, track_id: str) -> TrackCues | None: + return TrackCues(cues=[], grid_markers=[]) if track_id in self._files else None + + def audio_facts(self, track_ids) -> dict[str, AudioFacts]: + return {t: self._files[t].facts for t in track_ids if t in self._files} + + def audio_path(self, track_id: str, *, progress=None) -> Path | None: + """A local copy (downloaded into the shared cache, like a library track).""" + if track_id not in self._files: + return None + return self.adapter.folder_audio(track_id, progress=progress) + + def playlist_tree(self) -> list[PlaylistNode]: + return [] + + def playlist_tracks(self, node_id: str) -> list[Track] | None: + return None diff --git a/backend/konduktor/adapters/traktor/export.py b/backend/konduktor/adapters/traktor/export.py index c7feadd..66b2739 100644 --- a/backend/konduktor/adapters/traktor/export.py +++ b/backend/konduktor/adapters/traktor/export.py @@ -106,14 +106,10 @@ class TraktorExporter: return WrittenLibrary(library=library) def _write_playlists(self, adapter, payload: ExportPayload, moved: dict) -> None: - """Recreate the tree under one folder named after the export. - - Nested under the export's own name for the same reason import nests a - drive's playlists under the drive's name: a collection swapped onto - another machine should say where its playlists came from. - """ - root = adapter.create_folder(payload.name) - folders: dict[tuple[str, ...], str] = {(): root} + """Recreate the tree — at the top level, or with `payload.root_folder` + under one folder named after the export (None = the top level).""" + root = adapter.create_folder(payload.name) if payload.root_folder else None + folders: dict[tuple[str, ...], str | None] = {(): root} for playlist in payload.playlists: parent = self._folder_for(adapter, folders, tuple(playlist.folders), root) @@ -128,7 +124,7 @@ class TraktorExporter: adapter.set_playlist_entries(node_id, loose) @staticmethod - def _folder_for(adapter, folders: dict, path: tuple[str, ...], root: str) -> str: + def _folder_for(adapter, folders: dict, path: tuple[str, ...], root: str | None) -> str | None: """Create (once) the folder chain a playlist sits under, and return it.""" for depth in range(1, len(path) + 1): branch = path[:depth] diff --git a/backend/konduktor/core/export.py b/backend/konduktor/core/export.py index 749ad9c..d2c50f7 100644 --- a/backend/konduktor/core/export.py +++ b/backend/konduktor/core/export.py @@ -94,8 +94,14 @@ class ExportPayload: tracks: list[ExportTrack] = field(default_factory=list) playlists: list[ExportPlaylist] = field(default_factory=list) - #: The export's name, used for the folder its playlists are nested under. + #: The export's name, used for the folder its playlists are nested under + #: when `root_folder` is set. name: str = "Export" + #: Nest the whole playlist tree (and "Other") in one folder named `name`. + #: Off — the default, a Konduktor setting — the playlists sit at the + #: library's top level: an export is a library of its own, so a folder + #: saying where it came from is one more click at the gig. + root_folder: bool = False #: Called by a writer before each slow step (e.g. decoding a track for its #: waveform) with a message for the status bar, and — for a per-track loop — #: `step` of `of`, which drives the progress bar. RAISES when the user has diff --git a/backend/konduktor/core/pyav.py b/backend/konduktor/core/pyav.py new file mode 100644 index 0000000..b76dc7a --- /dev/null +++ b/backend/konduktor/core/pyav.py @@ -0,0 +1,33 @@ +"""Opening a file for reading with PyAV, on every PyAV version the app ships. + +A file whose tags are not valid UTF-8 must still open: it is still audio. +PyAV 18 decodes tags strictly by default and raises UnicodeDecodeError at open +unless given `metadata_errors="ignore"`; PyAV 19 REMOVED that keyword (passing +it is a TypeError) and opens such a file as it is, the bad bytes as surrogates. +Measured on both with a generated M4A and MP3 whose title is invalid UTF-8. + +The keyword once went straight into `av.open`, which worked on the dev venv's +18.1 while CI's fresh install took 19.0.1: every stem file then failed to open +in the released app, and the deck played stem tracks as the mix. Every read +goes through `open_input`, so the difference lives in one place. +""" +from __future__ import annotations + +from functools import cache +from pathlib import Path + + +@cache +def _takes_metadata_errors() -> bool: + import av + + return int(av.__version__.split(".")[0]) < 19 + + +def open_input(path: Path | str): + """`av.open(path)` for reading, tolerant of tags that are not UTF-8.""" + import av + + if _takes_metadata_errors(): + return av.open(str(path), metadata_errors="ignore") + return av.open(str(path)) diff --git a/backend/konduktor/core/stem_file.py b/backend/konduktor/core/stem_file.py index a044c4c..b17cc1e 100644 --- a/backend/konduktor/core/stem_file.py +++ b/backend/konduktor/core/stem_file.py @@ -45,7 +45,7 @@ from typing import Callable import numpy as np -from . import mp4_edit, tag_copy +from . import mp4_edit, pyav, tag_copy SR = 44100 FRAME = 1024 # AAC-LC frame size, for both encoders @@ -132,7 +132,7 @@ def decode(path: Path | str) -> Source: """Decode the first audio stream to stereo float32 at 44.1 kHz.""" import av - with av.open(str(path), metadata_errors="ignore") as container: + with pyav.open_input(path) as container: stream = container.streams.audio[0] codec = stream.codec_context.name bit_rate = stream.bit_rate or container.bit_rate or None @@ -381,7 +381,7 @@ def _audio_stream_count(path: Path) -> int: av = None if av is not None: try: - with av.open(str(path), metadata_errors="ignore") as c: + with pyav.open_input(path) as c: return len(c.streams.audio) except av.FFmpegError as ex: raise ValueError(str(ex)) @@ -453,7 +453,7 @@ def extract_stream(path: Path | str, stream: int, fp) -> None: """ import av - with av.open(str(path), metadata_errors="ignore") as inp: + with pyav.open_input(path) as inp: if not 0 <= stream < len(inp.streams.audio): raise StemFileError(f"The file has no audio stream {stream}") ist = inp.streams.audio[stream] diff --git a/backend/konduktor/core/waveform.py b/backend/konduktor/core/waveform.py index b38b04d..9c00067 100644 --- a/backend/konduktor/core/waveform.py +++ b/backend/konduktor/core/waveform.py @@ -94,7 +94,9 @@ def _decode_pyav(path: Path) -> np.ndarray: """ import av - with av.open(str(path)) as container: + from . import pyav + + with pyav.open_input(path) as container: stream = container.streams.audio[0] resampler = av.AudioResampler(format="flt", layout="mono", rate=SR) chunks = [] diff --git a/backend/konduktor/exporter.py b/backend/konduktor/exporter.py index 424b371..9cebdec 100644 --- a/backend/konduktor/exporter.py +++ b/backend/konduktor/exporter.py @@ -433,9 +433,13 @@ def _folder_paths(adapter) -> dict[str, list[str]]: # ---- running ----------------------------------------------------------------- -def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict: +def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *, + root_folder: bool = False) -> dict: """Copy what changed, then write every target's library over the audio. + `root_folder` nests the playlists in a folder named after the export (the + "Put exported playlists in a folder" setting); otherwise they sit at the top. + Rolls back EVERYTHING this run wrote on cancel or on any failure — including the libraries of targets that had already been written when a later one failed. What it KEPT from the previous export stays, and the @@ -545,6 +549,7 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict: payload = ExportPayload( name=export_set.name, + root_folder=root_folder, tracks=payload_tracks, playlists=built.playlists, checkpoint=checkpoint, diff --git a/backend/konduktor/importer.py b/backend/konduktor/importer.py index e0e0e58..69decb5 100644 --- a/backend/konduktor/importer.py +++ b/backend/konduktor/importer.py @@ -191,6 +191,30 @@ def plan(source, dest, destination: Path | None, *, track_ids=None, playlist_ids return plan +def plan_on_host(source, track_ids) -> ImportPlan: + """A plan for files that are already on the machine holding the library — a + remote library's content folder, browsed from this computer + (`source.on_library_host`). Nothing is checked on THIS disk, where those + paths mean nothing: the source says each file's size and which ones the + library already holds. Added in place (`run(reference=True)`), so there is + no destination and nothing to copy. + """ + plan = ImportPlan(destination=None) + for track_id in dict.fromkeys(track_ids): + track = source.track(track_id) + if track is None: + continue + name = track_id.replace("\\", "/").rsplit("/", 1)[-1] + plan.tracks.append(PlannedTrack( + track_id=track_id, + title=track.title or name, + source_path=Path(track_id), + size=source.size(track_id), + existing_id=source.held(track_id), + )) + return plan + + def _playlist_name(source, node_id: str) -> str | None: for nid, name in _all_playlists(source): if nid == node_id: @@ -321,7 +345,7 @@ def run( # a folder on the server, instead of copied here. Nothing can be left in # place — the server cannot see this computer's files. uploads = not places and uploads_audio(dest) - if uploads and reference: + if uploads and reference and not getattr(source, "on_library_host", False): raise ValueError("A remote library cannot reference files on this computer") if not reference and not places and not uploads: assert destination is not None diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index fd40059..199b0ec 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -765,7 +765,10 @@ def run_export(set_id: str) -> JobStatus: built = exporter.plan(adapter, found) if built.blocked: raise HTTPException(409, built.blocked) - job = JOBS.submit("export", lambda handle: exporter.run(adapter, found, built, handle)) + # A Konduktor setting, read when the export starts. + root_folder = bool(prefs.load_prefs().get("exportRootFolder", False)) + job = JOBS.submit("export", lambda handle: exporter.run( + adapter, found, built, handle, root_folder=root_folder)) return JobStatus(**job.as_dict()) @@ -2183,6 +2186,50 @@ def source_track_stems(track_id: str) -> dict: FOLDERS = FolderScanner() +# A remote library's content folder rides the same routes. Its paths carry this +# prefix, so a path on the server can never be taken for the same path on this +# computer — and the UI's folder view, deck and add dialog need no second set of +# routes. The prefix alone is the content folder itself. +SERVER_FOLDER = "server:" + + +def _on_server(path: str) -> str | None: + """The server path behind a prefixed one ('' = the content folder), else None.""" + return path[len(SERVER_FOLDER):] if path.startswith(SERVER_FOLDER) else None + + +def _server_track(track: Track) -> Track: + return track.model_copy(update={"id": SERVER_FOLDER + track.id}) + + +def _folder_rows(dest, tracks: list[Track], held_of) -> tuple[list[Track], dict[str, str]]: + """A folder's files as table rows. Where the library holds a file, the row + IS the library's track — its key, rating, comments, cues and plays, and + its id, so it plays, edits and drags as the collection track it is + (decided 2026-10-10) — else the file's own tags. Also returns library id → + the file's folder id, for the rows that are library tracks: adding still + speaks in folder ids.""" + rows: list[Track] = [] + files: dict[str, str] = {} + for track in tracks: + known = held_of(track) + held = dest.track(known) if known else None + if held is None or held.id in files: + rows.append(track) + continue + rows.append(held) + files[held.id] = track.id + return rows, files + + +def _server_file(track_id: str) -> tuple[object, str]: + """The remote adapter and the server path of a listed content-folder file.""" + adapter = _require_remote() + raw = _on_server(track_id) or "" + if adapter.listed_files([raw]) is None: + raise HTTPException(404, "Track not found — browse to its folder first") + return adapter, raw + def _drive_of(path: Path, drives: list[dict]) -> dict | None: """The drive `path` lives on: the longest drive root that contains it.""" @@ -2209,6 +2256,10 @@ def fs_drives() -> list[Drive]: found = places.drives() libraries = sources() out = [Drive(**d) for d in found] + if STATE.remote is not None and STATE.remote_config is not None: + # The server holding the library, first: its content folder is where + # this library's music is, and this computer cannot see it otherwise. + out.insert(0, Drive(name=STATE.remote_config.name, path=SERVER_FOLDER, kind="server")) externals = [d for d in found if d["path"] != "/"] for lib in libraries: home = _drive_of(Path(lib.path), externals) @@ -2223,6 +2274,11 @@ def fs_drives() -> list[Drive]: @app.get("/api/fs/folders", response_model=list[FsEntry]) def fs_folders(path: str) -> list[FsEntry]: """The visible folders directly inside `path` — one level of a Files tree.""" + raw = _on_server(path) + if raw is not None: + listing = _require_remote().client.fs_list(raw or None) + return [FsEntry(name=e["name"], path=SERVER_FOLDER + e["path"]) + for e in listing["entries"] if e["is_dir"]] base = Path(path).expanduser() if not base.is_dir(): raise HTTPException(404, f"Not a folder: {base}") @@ -2236,16 +2292,27 @@ def _formats() -> list[str]: @app.get("/api/folder/tracks", response_model=FolderTracks) def folder_tracks(path: str) -> FolderTracks: """The audio files directly inside a folder, and which are already held.""" + raw = _on_server(path) + if raw is not None: + adapter = _require_remote() + listing = adapter.folder_listing(raw or None) + rows, files = _folder_rows(adapter, [_server_track(t) for t in listing.tracks], + lambda t: listing.held(t.id[len(SERVER_FOLDER):])) + return FolderTracks(path=SERVER_FOLDER + listing.path, tracks=rows, + in_collection=list(files), files=files, removable=False) base = Path(path).expanduser() if not base.is_dir(): raise HTTPException(404, f"Not a folder: {base}") source = FOLDERS.scan(base, _formats()) - held = importer._existing_files(require_adapter()) + dest = require_adapter() + held = importer._existing_files(dest) + rows, files = _folder_rows(dest, source.tracks, lambda t: held.get(importer._key(Path(t.id)))) drive = _drive_of(base, places.drives()) return FolderTracks( path=str(base), - tracks=source.tracks, - in_collection=[t.id for t in source.tracks if importer._key(Path(t.id)) in held], + tracks=rows, + in_collection=list(files), + files=files, removable=drive is None or drive["kind"] == "external", ) @@ -2263,11 +2330,17 @@ def _folder_track(track_id: str) -> FolderSource: def folder_capabilities(path: str) -> Capabilities: from .core.folder import capabilities_for + raw = _on_server(path) + if raw is not None: + return capabilities_for(Path(raw) if raw else Path(STATE.remote_config.name if STATE.remote_config else "Server")) return capabilities_for(Path(path)) @app.get("/api/folder/tracks/cues", response_model=TrackCues) def folder_track_cues(track_id: str) -> TrackCues: + if _on_server(track_id) is not None: + _server_file(track_id) + return TrackCues(cues=[], grid_markers=[]) cues = _folder_track(track_id).track_cues(track_id) assert cues is not None return cues @@ -2275,7 +2348,11 @@ def folder_track_cues(track_id: str) -> TrackCues: @app.get("/api/folder/tracks/audio") def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse: - path = _folder_track(track_id).audio_path(track_id) + if _on_server(track_id) is not None: + adapter, raw = _server_file(track_id) + path = adapter.folder_audio(raw) # this computer's copy, as for a library track + else: + path = _folder_track(track_id).audio_path(track_id) if path is None or not path.is_file(): raise HTTPException(404, "Audio file not found") if stem is not None: @@ -2286,6 +2363,9 @@ def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse: @app.get("/api/folder/tracks/stems") def folder_track_stems(track_id: str) -> dict: + if _on_server(track_id) is not None: + adapter, raw = _server_file(track_id) + return _stem_layout_of(adapter.folder_audio(raw)) return _stem_layout_of(_folder_track(track_id).audio_path(track_id)) @@ -2295,6 +2375,34 @@ def _require_addable(dest) -> None: raise HTTPException(422, "Tracks cannot be added to this library") +def _check_add_targets(dest, body: FolderAddRequest) -> None: + if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None: + raise HTTPException(404, f"Playlist not found: {body.playlist_id}") + if body.export_id is not None: + if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None: + raise HTTPException(404, f"Export not found: {body.export_id}") + + +def _is_server_add(body: FolderAddRequest) -> bool: + on_server = [_on_server(t) is not None for t in body.track_ids] + if any(on_server) and not all(on_server): + raise HTTPException(400, "Files on the server and on this computer are added separately") + return bool(on_server) and all(on_server) + + +def _server_add_plan(body: FolderAddRequest): + """Files in the remote library's content folder: already where the library + can reach them, so they are added IN PLACE — nothing uploaded, nothing asked.""" + dest = _require_remote() + _require_addable(dest) + paths = [_on_server(t) for t in body.track_ids] + source = dest.listed_files(paths) + if source is None: + raise HTTPException(400, "No tracks to add") + _check_add_targets(dest, body) + return source, dest, importer.plan_on_host(source, paths) + + def _folder_add_plan(body: FolderAddRequest): dest = require_adapter() _require_addable(dest) @@ -2315,11 +2423,7 @@ def _folder_add_plan(body: FolderAddRequest): if not body.destination: raise HTTPException(400, "Copying needs a destination folder") destination = Path(body.destination).expanduser() - if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None: - raise HTTPException(404, f"Playlist not found: {body.playlist_id}") - if body.export_id is not None: - if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None: - raise HTTPException(404, f"Export not found: {body.export_id}") + _check_add_targets(dest, body) return source, dest, destination, importer.plan( source, dest, destination, track_ids=[t.id for t in tracks] ) @@ -2327,6 +2431,11 @@ def _folder_add_plan(body: FolderAddRequest): @app.post("/api/folder/add/preview") def folder_add_preview(body: FolderAddRequest) -> dict: + if _is_server_add(body): + _source, _dest, plan = _server_add_plan(body) + out = plan.as_dict() + out.update(total_bytes=0, free_bytes=None, enough_space=None, removable=False) + return out _source, dest, destination, plan = _folder_add_plan(body) out = plan.as_dict(free_bytes=importer.free_bytes(destination, dest) if destination else None) if importer.places_audio(dest): @@ -2343,10 +2452,16 @@ def folder_add_preview(body: FolderAddRequest) -> dict: def folder_add(body: FolderAddRequest) -> JobStatus: """Add browsed files to the collection. A job, like import: copying can be long.""" _require_no_pending_stems("Adding files") - source, dest, destination, plan = _folder_add_plan(body) + in_place = _is_server_add(body) + if in_place: + source, dest, plan = _server_add_plan(body) + destination = None + else: + source, dest, destination, plan = _folder_add_plan(body) if not plan.importable and not plan.existing: raise HTTPException(400, "Nothing to add (none of those files exist)") - if body.mode == "copy" or importer.places_audio(dest): + # Nothing is copied in place, so there is no space to check. + if not in_place and (body.mode == "copy" or importer.places_audio(dest)): free = importer.free_bytes(destination, dest) needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes if free is not None and free < needed + importer.SPACE_HEADROOM: @@ -2362,7 +2477,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus: def work(handle): result = importer.run( source, dest, plan, handle, - reference=body.mode == "reference", + reference=in_place or body.mode == "reference", into_playlist=body.playlist_id, ) # Export sets are Konduktor's own data, not the library's, so they are diff --git a/backend/konduktor/remote_protocol.py b/backend/konduktor/remote_protocol.py index 0198931..4319e1e 100644 --- a/backend/konduktor/remote_protocol.py +++ b/backend/konduktor/remote_protocol.py @@ -35,7 +35,8 @@ from .core.model import AutoHotcue, Track, TrackCues #: at least its own: minors only add. Bump the minor for an added route or #: method, the major for anything an older client would misread. #: 1.1 — `move_playlist` (sidebar drag and drop). -API_VERSION: tuple[int, int] = (1, 1) +#: 1.2 — `/v1/folder/*`: the content folder browsed as a Files tree. +API_VERSION: tuple[int, int] = (1, 2) #: How long a session survives without a heartbeat, and how often the holder #: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index aa3e1c0..d051a21 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -521,11 +521,15 @@ class Drive(BaseModel): candidate `/api/sources` reports, attached to the drive it lives on so the sidebar can show one row per drive rather than a device list and a drive list that disagree about what is plugged in. + + `server` is a remote library's content folder (path `server:`), listed + first while a remote library is open — the one place its music can be + browsed by folder from this computer. """ name: str path: str - kind: Literal["local", "external"] + kind: Literal["local", "external", "server"] library: SourceCandidate | None = None @@ -533,9 +537,13 @@ class FolderTracks(BaseModel): """The audio files directly inside one folder, projected as tracks.""" path: str + # A file the collection holds is listed AS the collection's track (its id, + # key, rating, cues…); any other file as its own tags, id = its path. tracks: list[Track] - # Ids (= absolute paths) of the files the collection already points at. + # Collection ids of the rows that are collection tracks. in_collection: list[str] + # Those rows' collection id → the file's folder id, which adding takes. + files: dict[str, str] = {} # On an external drive: a track referenced in place goes missing when the # drive is unplugged, which the add dialog has to say. removable: bool diff --git a/backend/konduktor/server/app.py b/backend/konduktor/server/app.py index f2f6741..ca0d239 100644 --- a/backend/konduktor/server/app.py +++ b/backend/konduktor/server/app.py @@ -44,6 +44,7 @@ from ..core.adapter import ( NotFound, Unsupported, ) +from ..core.folder import FolderScanner from ..core.places import is_os_housekeeping from .config import ConfigError, ServerConfig from .session import InUse, Lost, SessionLock @@ -65,6 +66,10 @@ class Server: self.lock = lock or SessionLock() self.rev = 0 self._rev_lock = threading.Lock() + #: The content folder's audio as browsed from a client's Files tree — + #: tags read once per folder state, and the gatekeeper for streaming + #: one of those files (only a file a listing found is served). + self.folders = FolderScanner() # ---- opening --------------------------------------------------------------- def open(self) -> None: @@ -388,6 +393,73 @@ def create_app(server: Server) -> FastAPI: "entries": entries, } + @app.get("/v1/folder/tracks") + def folder_tracks(path: str | None = None) -> dict: + """The audio directly inside a content folder, projected as tracks — the + client's Files tree for the server, like `/api/folder/tracks` for a + drive of its own. Tags only (no decoding). `held` maps each file the + library already points at to the library's id for it, so the client + can tick it off and add it to a playlist without adding it twice.""" + from .. import importer + + folder = server.confine(path) + if not folder.is_dir(): + raise HTTPException(404, f"Not a folder: {folder}") + adapter = server.adapter + source = server.folders.scan(folder, adapter.capabilities().tracks.audio_formats) + library = importer._existing_files(adapter) + files, held = {}, {} + for track in source.tracks: + try: + st = Path(track.id).stat() + except OSError: + continue + files[track.id] = {"size": st.st_size, "mtime_ns": st.st_mtime_ns} + known = library.get(importer._key(Path(track.id))) + if known is not None: + held[track.id] = known + return { + "path": str(folder), + "tracks": [t.model_dump(mode="json") for t in source.tracks if t.id in files], + "files": files, + "held": held, + } + + def listed_file(path: str) -> Path: + # Confined (a symlink in a listing cannot lead out of the content + # folder), and only a file a listing found: this is not a way to read + # any path on the server. + server.confine(path) + source = server.folders.source_for_file(path) + if source is None: + raise HTTPException(404, "File not found — list its folder first") + target = Path(path) + if not target.is_file(): + raise HTTPException(404, "The audio file is missing") + return target + + @app.get("/v1/folder/audio") + def folder_audio(path: str): + target = listed_file(path) + st = target.stat() + media = mimetypes.guess_type(str(target))[0] or "application/octet-stream" + return FileResponse(target, media_type=media, headers={ + "X-Konduktor-Size": str(st.st_size), + "X-Konduktor-Mtime-Ns": str(st.st_mtime_ns), + }) + + @app.post("/v1/folder/leads") + def folder_leads(body: dict = Body(...)) -> dict: + """The analysis lead of each listed file, as an upload reports it: what + a client adding these files IN PLACE measures with. None for every file + when the platform does not analyse what it adds.""" + lead = getattr(server.adapter, "analysis_lead", None) + out = {} + for path in body.get("paths") or []: + target = listed_file(str(path)) + out[str(path)] = lead(target) if lead else None + return {"leads": out} + @app.get("/v1/fs/space") def fs_space(path: str | None = None) -> dict: folder = server.confine(path) diff --git a/backend/requirements-build.txt b/backend/requirements-build.txt index fcfdead..52ca39f 100644 --- a/backend/requirements-build.txt +++ b/backend/requirements-build.txt @@ -1,4 +1,4 @@ # Build-only dependencies (not needed to run the backend in dev). -# Freezes the backend into a standalone sidecar binary for the desktop build. +# Freezes the backend into a standalone sidecar folder (onedir) for the desktop build. # See konduktor-sidecar.spec and build_sidecar.sh. pyinstaller>=6.16 # 6.16+ supports Python 3.14 diff --git a/backend/requirements.txt b/backend/requirements.txt index 43f8fc3..f691eb3 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -4,7 +4,7 @@ fastapi>=0.115 uvicorn[standard]>=0.34 pydantic>=2.11 mutagen>=1.47 # embedded audio-file tag read/write (ID3/MP4/FLAC/AIFF) -av>=18.1 # PyAV: FFmpeg's decoders in the wheel — waveforms for export, AAC on every OS +av>=18.1,<20 # PyAV: FFmpeg's decoders in the wheel — waveforms for export, AAC on every OS. Before allowing a new major, check core/pyav.py (19 broke av.open) Pillow>=11 # cover art -> the 80/240 px JPEGs a Pioneer export carries python-multipart>=0.0.9 # multipart form parsing for cover-art upload # Version-history backups: a self-contained git impl (no system git needed; diff --git a/backend/test_device_export.py b/backend/test_device_export.py index e133d5a..5778e51 100644 --- a/backend/test_device_export.py +++ b/backend/test_device_export.py @@ -177,9 +177,9 @@ check("bpm x100, rating, file type, bitmask as rekordbox writes them", check("the file path is drive-relative", lib.tracks[0]["file_path"] == "/Contents/House/One.wav", lib.tracks[0]["file_path"]) check("no computer's masterDbId is claimed", all(t["u3"] == 0 and t["u4"] == 0 for t in lib.tracks)) tree = {p["name"]: p for p in lib.playlists} -check("the tree: a folder named after the export > House > Peak, plus Other for loose tracks", - tree["GIG"]["folder"] and tree["House"]["parent"] == tree["GIG"]["id"] - and tree["Peak"]["parent"] == tree["House"]["id"] and tree["Other"]["parent"] == tree["GIG"]["id"]) +check("the tree: House > Peak, plus Other for loose tracks, at the top level (parent 0)", + "GIG" not in tree and tree["House"]["folder"] and tree["House"]["parent"] == 0 + and tree["Peak"]["parent"] == tree["House"]["id"] and tree["Other"]["parent"] == 0) peak = [e for e in lib.entries if e[2] == tree["Peak"]["id"]] check("playlist entries in order, 1-based", peak == [(1, 1, tree["Peak"]["id"]), (2, 2, tree["Peak"]["id"])], peak) check("every track has an analysis path, and the files exist", @@ -188,6 +188,13 @@ check("artwork rows name the a.jpg files, which exist", all((root / p.lstrip("/")).is_file() for p in lib.artwork.values()) and len(lib.artwork) == 3) check("every file written is reported, so a re-export can clear it", all(p.exists() for p in written.all_paths)) +import dataclasses # noqa: E402 +rooted_tree = {p["name"]: p for p in P.read( + dev.write(dataclasses.replace(payload, root_folder=True), root).library.read_bytes()).playlists} +check("with the root-folder setting: a folder named after the export holds House and Other", + rooted_tree["GIG"]["folder"] and rooted_tree["GIG"]["parent"] == 0 + and rooted_tree["House"]["parent"] == rooted_tree["GIG"]["id"] + and rooted_tree["Other"]["parent"] == rooted_tree["GIG"]["id"]) print("== alongside OneLibrary: one set of analysis files and artwork ==") both = Path(tempfile.mkdtemp()) @@ -195,7 +202,6 @@ for t in tracks: dst = both / t.destination.relative_to(root) dst.parent.mkdir(parents=True, exist_ok=True) dst.write_bytes(t.destination.read_bytes()) -import dataclasses # noqa: E402 moved = [dataclasses.replace(t, destination=both / t.destination.relative_to(root)) for t in tracks] both_payload = ExportPayload(name="GIG", tracks=moved, playlists=payload.playlists) ol_written = core_export.for_platform("onelibrary").write(both_payload, both) diff --git a/backend/test_export.py b/backend/test_export.py index de32d60..25b4e6d 100644 --- a/backend/test_export.py +++ b/backend/test_export.py @@ -137,19 +137,20 @@ def walk(nodes, path=()): walk(back.playlist_tree()) -check("one folder named after the export", ("GIG",) in tree and tree[("GIG",)].kind == "folder") -check("nested folders are preserved", ("GIG", "House") in tree) -check("and nest further", ("GIG", "House", "Slow") in tree) +# By default the tree sits at the top level: an export is a library of its own. +check("no folder named after the export by default", ("GIG",) not in tree) +check("nested folders are preserved", ("House",) in tree and tree[("House",)].kind == "folder") +check("and nest further", ("House", "Slow") in tree) check("playlists land in their folder", - ("GIG", "House", "Peak Time") in tree and ("GIG", "House", "Slow", "Warmup") in tree) + ("House", "Peak Time") in tree and ("House", "Slow", "Warmup") in tree) check("with the right counts", - tree[("GIG", "House", "Peak Time")].count == 2 - and tree[("GIG", "House", "Slow", "Warmup")].count == 1) + tree[("House", "Peak Time")].count == 2 + and tree[("House", "Slow", "Warmup")].count == 1) # A track added individually would otherwise be reachable only by search. -check("loose tracks get an 'Other' playlist", ("GIG", "Other") in tree) +check("loose tracks get an 'Other' playlist, at the top level", ("Other",) in tree) check("holding exactly the ones no playlist claimed", - tree[("GIG", "Other")].count == 1, tree[("GIG", "Other")].count) -other_ids = back.playlist_entries(tree[("GIG", "Other")].id) + tree[("Other",)].count == 1, tree[("Other",)].count) +other_ids = back.playlist_entries(tree[("Other",)].id) check("and it is the right track", back.track(other_ids[0]).title == plain.title) @@ -182,7 +183,19 @@ again = exporter.write(payload, dest).library check("the entry count did not double", f'' in again.read_text(encoding="utf-8")) check("and the tree did not duplicate", - len(TraktorDriver().open(again).playlist_tree()) == 1) + len(TraktorDriver().open(again).playlist_tree()) == len(back.playlist_tree())) + +print("== with the root-folder setting: everything under one folder named after the export ==") +payload.root_folder = True +rooted = TraktorDriver().open(exporter.write(payload, dest).library) +tree.clear() +walk(rooted.playlist_tree()) +check("one top-level node: a folder named after the export", + [n.name for n in rooted.playlist_tree()] == ["GIG"] and tree[("GIG",)].kind == "folder") +check("the tree nests inside it", + ("GIG", "House", "Peak Time") in tree and ("GIG", "House", "Slow", "Warmup") in tree) +check("and so does 'Other'", ("GIG", "Other") in tree and tree[("GIG", "Other")].count == 1) +payload.root_folder = False # ============================================================================== # Running an export: the copy, the safety rules, and the rollback. @@ -207,7 +220,7 @@ for i, track in enumerate(src.tracks[:4]): seed_items.append(ExportTrack(track=track, destination=audio, cues=src.track_cues(track.id))) exporter_obj = core_export.for_platform("traktor") exporter_obj.write( - _Payload(name="Source", tracks=seed_items, + _Payload(name="Source", tracks=seed_items, root_folder=True, playlists=[ExportPlaylist(name="Peak Time", track_ids=[src.tracks[0].id, src.tracks[1].id])]), lib_root, diff --git a/backend/test_export_pioneer.py b/backend/test_export_pioneer.py index 36a93d0..af8649a 100644 --- a/backend/test_export_pioneer.py +++ b/backend/test_export_pioneer.py @@ -173,9 +173,23 @@ for platform, reopen in ( tree.clear() walk(back.playlist_tree()) - check("a folder named after the export", ("GIG",) in tree) - check("nested folders are preserved", ("GIG", "House") in tree) + check("no folder named after the export by default", ("GIG",) not in tree) + check("nested folders are preserved, at the top level", ("House",) in tree) check("with the playlist inside", + ("House", "Peak Time") in tree + and tree[("House", "Peak Time")].count == len(chosen)) + + print(f"-- {platform}: with the root-folder setting") + rooted_root = Path(tempfile.mkdtemp()) / "GIG" + rooted_payload = build(rooted_root) + rooted_payload.root_folder = True + exporter.write(rooted_payload, rooted_root) + rooted = reopen(rooted_root) + tree.clear() + walk(rooted.playlist_tree()) + check("one top-level node: a folder named after the export", + [n.name for n in rooted.playlist_tree()] == ["GIG"]) + check("the tree nests inside it", ("GIG", "House", "Peak Time") in tree and tree[("GIG", "House", "Peak Time")].count == len(chosen)) diff --git a/backend/test_folders.py b/backend/test_folders.py index 1047c8a..4672e3f 100644 --- a/backend/test_folders.py +++ b/backend/test_folders.py @@ -154,7 +154,11 @@ with TestClient(main.app, raise_server_exceptions=False) as c: 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"] == [str(one)], str(body["in_collection"])) + 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 diff --git a/backend/test_remote_adapter.py b/backend/test_remote_adapter.py index 67cd0cf..f7ad125 100644 --- a/backend/test_remote_adapter.py +++ b/backend/test_remote_adapter.py @@ -293,6 +293,91 @@ with tempfile.TemporaryDirectory() as d: check("…and to the mirror here", any((tr.filepath or "").endswith("Brand New.mp3") for tr in main.require_adapter().tracks)) + print("== the content folder, browsed like a drive ==") + loose = make_mp3(content / "Crate" / "Loose One.mp3", seconds=3, seed=11) + drives = c.get("/api/fs/drives").json() + check("the server is listed first among the drives, under the remote's name", + drives and drives[0] == {"name": "NAS", "path": "server:", "kind": "server", "library": None}, + drives[:1]) + tops = c.get("/api/fs/folders", params={"path": "server:"}).json() + check("its Files tree starts at the content folder", + {e["name"] for e in tops} >= {"Crate", "Mapped"} + and all(e["path"].startswith("server:") for e in tops), tops) + r = c.get("/api/folder/tracks", params={"path": f"server:{content}/Mapped"}) + listed = r.json() + check("a folder's files the library holds are listed AS its tracks, ticked off", + r.status_code == 200 and sorted(tr["id"] for tr in listed["tracks"]) == sorted(ids) + and sorted(listed["in_collection"]) == sorted(ids) and not listed["removable"] + and all(v.startswith("server:") for v in listed["files"].values()), r.text[:300]) + check("…with the collection's data, not the file's tags", + next(tr for tr in listed["tracks"] if tr["id"] == target)["genre"] == "Remote Edit") + r = c.get("/api/folder/tracks", params={"path": "server:/etc"}) + check("…and nothing outside the content folder is listed", r.status_code == 400, r.text[:200]) + crate = c.get("/api/folder/tracks", params={"path": f"server:{content}/Crate"}).json() + loose_id = f"server:{loose}" + check("a file the library does not hold is listed unticked", + [tr["id"] for tr in crate["tracks"]] == [loose_id] and crate["in_collection"] == []) + caps = c.get("/api/folder/capabilities", params={"path": f"server:{content}/Crate"}).json() + check("…read-only, like any browsed folder", not caps["writable"] + and caps["readonly_cause"] == "not_in_library") + folder_downloads = [] + real_folder_download = adapter.client.folder_download + adapter.client.folder_download = lambda *a, **k: (folder_downloads.append(a[0]), + real_folder_download(*a, **k))[1] + r = c.get("/api/folder/tracks/audio", params={"track_id": loose_id}) + check("the deck can audition it", r.status_code == 200 and r.content == loose.read_bytes()) + c.get("/api/folder/tracks/audio", params={"track_id": loose_id}) + check("…downloaded once", folder_downloads == [str(loose)], folder_downloads) + r = c.get("/api/folder/tracks/audio", params={"track_id": f"server:{content}/Crate/nope.mp3"}) + check("a file no listing returned is not served", r.status_code == 404) + srv_unlisted = httpx.get(f"http://127.0.0.1:{port}/v1/folder/audio", + params={"path": str(work)}, auth=("dj", "secret")) + check("…nor, asked of the server directly, anything outside the content folder", + srv_unlisted.status_code == 400, srv_unlisted.text[:200]) + + pl = c.post("/api/playlists", json={"name": "From the server"}).json()["id"] + held_track = listed["in_collection"][0] + held_id = listed["files"][held_track] # adding speaks in folder ids + add = {"track_ids": [loose_id, held_id], "mode": "reference", "playlist_id": pl} + r = c.post("/api/folder/add/preview", json=add) + pv = r.json() + check("(preview) one new, one already held, nothing to copy", + r.status_code == 200 and pv["importable"] == 1 and len(pv["existing"]) == 1 + and pv["total_bytes"] == 0 and pv["enough_space"] is None, r.text[:300]) + mixed = c.post("/api/folder/add/preview", json={**add, "track_ids": [loose_id, str(incoming)]}) + check("files here and on the server are not mixed in one add", mixed.status_code == 400) + # Pretend the platform analyses what it adds (as Rekordbox does): the file + # is then fetched and analysed HERE, and the server receives the result. + received = [] + real_add = server_adapter.add_tracks + server_adapter.add_tracks = lambda items, **k: (received.extend(items), real_add(items, **k))[1] + server_adapter.analysis_lead = lambda path: 0.0 + before = sorted(p.name for p in content.rglob("*") if p.is_file()) + job = c.post("/api/folder/add", json=add).json() + for _ in range(400): + j = c.get(f"/api/jobs/{job['id']}").json() + if j["state"] != "running": + break + time.sleep(0.05) + del server_adapter.analysis_lead + server_adapter.add_tracks = real_add + added = [tr for tr in server_adapter.tracks if server_adapter.audio_path(tr.id) == loose] + check("the file is added to the library WHERE IT IS", j["state"] == "done" and len(added) == 1, + j.get("error")) + check("…nothing uploaded or copied", sorted(p.name for p in content.rglob("*") if p.is_file()) == before) + check("…analysed here on the cached copy, the result sent along", + len(received) == 1 and received[0].analysis is not None and folder_downloads == [str(loose)], + f"{len(received)} {folder_downloads}") + entries = server_adapter.playlist_entries(pl) or [] + check("…both land in the playlist, the held one not added twice", + added and entries == [added[0].id, held_track] + and len(server_adapter.tracks) == len(main.require_adapter().tracks), entries) + crate = c.get("/api/folder/tracks", params={"path": f"server:{content}/Crate"}).json() + check("…and the folder now shows it ticked off, as the collection track", + crate["in_collection"] == [added[0].id] and crate["files"] == {added[0].id: loose_id} + if added else False, crate) + check("the save is versioned on the server", not server_adapter.dirty) + print("== another computer takes over ==") other = RemoteClient(remote_config.Remote(id="o", name="NAS", host=f"127.0.0.1:{port}", username="dj"), "secret") other.acquire("other-client", "Studio iMac", takeover=True) diff --git a/backend/test_stem_playback.py b/backend/test_stem_playback.py index 3fdf825..758ea7d 100644 --- a/backend/test_stem_playback.py +++ b/backend/test_stem_playback.py @@ -73,6 +73,27 @@ check("a stem file lists its four stems with names and colours, in stream order" check("a plain MP3 has none", sf.stem_layout(plain) is None) check("a missing file has none (no exception)", sf.stem_layout(ROOT / "nope.stem.m4a") is None) +print("== a stem file whose tags are not UTF-8 ==") +# PyAV 18 will not open such a file unless told to ignore the bad bytes, and +# PyAV 19 rejects the keyword that tells it (core/pyav.py). A release built on +# 19 while dev ran 18 played every stem track as the mix: the route 500'd. +from mutagen.mp4 import MP4 # noqa: E402 + +bad = ROOT / "BadTag.stem.m4a" +shutil.copy2(stem, bad) +m = MP4(bad) +m["\xa9nam"] = ["XéX"] +m.save() +raw = bad.read_bytes() +assert raw.count("XéX".encode()) == 1 +bad.write_bytes(raw.replace("XéX".encode(), b"X\xe9\xe9X")) # same length: no box sizes change +check(f"it still lists its stems (PyAV {av.__version__})", sf.stem_layout(bad) == layout, str(sf.stem_layout(bad))) +with open(ROOT / "bad-stem-1.m4a", "wb") as fp: + sf.extract_stream(bad, 1, fp) +check("…a stem still extracts, bit-identical to the stream in place", + np.array_equal(decode(ROOT / "bad-stem-1.m4a"), decode(stem, 1))) +check("…and it still decodes for conversion", sf.decode(bad).pcm.shape[1] > 0) + print("== a temp collection pointing at them ==") work = ROOT / "collection.nml" shutil.copy2(REAL, work) diff --git a/backend/test_timebase.py b/backend/test_timebase.py index b24b197..725a488 100644 --- a/backend/test_timebase.py +++ b/backend/test_timebase.py @@ -33,7 +33,7 @@ import numpy as np # noqa: E402 from konduktor.adapters.traktor import timebase # noqa: E402 from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402 from konduktor.adapters.traktor.export import SKELETON # noqa: E402 -from konduktor.core import mp3_gapless # noqa: E402 +from konduktor.core import mp3_gapless, pyav # noqa: E402 from konduktor.core.adapter import NewTrack # noqa: E402 from konduktor.core.model import Track # noqa: E402 @@ -197,7 +197,7 @@ else: pad8 = re.search(r']*START="([^"]*)"[^>]*HOTCUE="7"', e) if not pad8 or not (KIT / name).is_file(): continue - with av.open(str(KIT / name), metadata_errors="ignore") as c: + with pyav.open_input(KIT / name) as c: st = c.streams.audio[0] sr = st.rate y = np.concatenate([f.to_ndarray()[0] for f in c.decode(st)]).astype(np.float64) @@ -258,7 +258,7 @@ else: name = c.Content.FileNameL if c.Content else "" if not name.startswith("K4-") or c.Kind != 9 or not (KIT / name).is_file(): continue # pad H: the ones placed by hand - with av.open(str(KIT / name), metadata_errors="ignore") as con: + with pyav.open_input(KIT / name) as con: st = con.streams.audio[0] sr = st.rate y = np.concatenate([f.to_ndarray()[0] for f in con.decode(st)]).astype(np.float64) diff --git a/docs/BUILDING.md b/docs/BUILDING.md new file mode 100644 index 0000000..112328f --- /dev/null +++ b/docs/BUILDING.md @@ -0,0 +1,149 @@ +# Building Konduktor + +Most people should just [download a release](https://github.com/MrPatben8/konduktor/releases). This page is for running Konduktor from source or packaging the desktop app yourself. + +## Run from source (development) + +Konduktor runs as two small local servers (a Python backend and a web +frontend). Do the one-time setup, then start them — the same steps work on +macOS, Linux, and Windows. + +### 1. Install (once) + +**Backend** — needs Python 3.11+. Create a virtual environment and install the +dependencies: + +```bash +cd backend +python3 -m venv .venv # Windows: python -m venv .venv +``` + +Activate it, then install: + +```bash +source .venv/bin/activate # Windows (PowerShell): .\.venv\Scripts\Activate.ps1 +pip install -r requirements.txt +cd .. +``` + +**Frontend** — needs Node 18+ (same on every platform): + +```bash +cd frontend +npm install +cd .. +``` + +### 2. Run it (development) + +Konduktor runs as two local servers (backend on `:8000`, frontend on `:5173`). + +**macOS / Linux** — one command starts both: + +```bash +./dev.sh +``` + +**Windows** — start each server in its own terminal: + +```powershell +# Terminal 1 — backend +cd backend; .\.venv\Scripts\Activate.ps1; uvicorn konduktor.main:app --reload --port 8000 + +# Terminal 2 — frontend +cd frontend; npm run dev +``` + +Either way, open **http://localhost:5173** in your browser (`Ctrl-C` stops a +server). This is the fastest way to try Konduktor or hack on it — the frontend +hot-reloads as you edit. To package a real double-clickable app instead, see +[Build a standalone app](#build-a-standalone-app-production) below. + +### 3. Open a library + +On launch, pick your platform (Traktor, Rekordbox, OneLibrary or Remote), then +let Konduktor find the library **automatically**, reopen the **last one** you +used, or **browse** for it yourself. + +Testing writes? `./dev-sandbox.sh` starts both servers against a throwaway copy +of your Traktor collection, with prefs and version history in a temp folder. + +--- + +## Build a standalone app (production) + +Prefer a real double-clickable app over running the dev servers? Konduktor +packages into a native desktop app (via **Tauri**) that bundles the Python +backend as a sidecar — no terminal, no servers to start by hand. + +### Extra prerequisites + +On top of the Python 3.11+ and Node 18+ from above: + +- **Rust** — install from (the app shell is Tauri/Rust). +- **PyInstaller** — into the backend venv: + `pip install -r backend/requirements-build.txt` +- **Windows only:** also the MSVC C++ build tools and the WebView2 runtime — see + [BUILDING-WINDOWS.md](../BUILDING-WINDOWS.md) for the one-time toolchain setup. + +The build is a two-step recipe on both platforms: **freeze the backend into a +sidecar folder**, then **build the app**. The only difference is which sidecar +script you run — `.sh` on macOS/Linux, `.ps1` on Windows. Each build runs on its +own OS (the app can't be cross-compiled). + +### macOS / Linux + +```bash +# 1) Freeze the backend into a sidecar folder (from the activated backend venv) +cd backend && source .venv/bin/activate && ./build_sidecar.sh && cd .. + +# 2) Build the app +cd frontend && npx tauri build +``` + +The installer lands at +`frontend/src-tauri/target/release/bundle/dmg/Konduktor__aarch64.dmg` +(with the `.app` beside it). + +### Windows + +```powershell +# 1) Freeze the backend into a sidecar folder (from the activated backend venv) +cd backend; .\.venv\Scripts\Activate.ps1; .\build_sidecar.ps1; cd .. + +# 2) Build the app +cd frontend; npx tauri build +``` + +The installers land in `frontend\src-tauri\target\release\bundle\` (an `.msi` and +an NSIS `-setup.exe`). See [BUILDING-WINDOWS.md](../BUILDING-WINDOWS.md) for the full +walkthrough and Windows-specific notes. + +> **First launch — getting past the OS security prompt.** Builds are +> **ad-hoc signed, not notarized** (no paid Apple/Windows developer cert yet), so +> the OS flags them the first time. This is expected — the app isn't damaged. +> +> - **macOS:** right-click the app → **Open** → **Open** (or System Settings → +> Privacy & Security → **Open Anyway** after the first blocked attempt). If it +> still refuses — common for a `.dmg` downloaded via a browser, which macOS +> quarantines — clear the quarantine flag once from Terminal: +> ```bash +> xattr -cr /Applications/Konduktor.app +> ``` +> - **Windows:** click **More info → Run anyway** past SmartScreen. +> +> The macOS `.dmg` is Apple-Silicon (`aarch64`) only. + +> **Faster local builds:** `npx tauri build --debug --bundles app` skips the +> optimizer and the installer, giving you a runnable app in seconds — handy while +> iterating. + +### Rebuilding after changes + +Changed **backend** Python? Re-run the sidecar script for your OS +(`./build_sidecar.sh` or `.\build_sidecar.ps1`), then `npx tauri build`. +Frontend-only change? Just `npx tauri build` — it rebuilds the web app for you. + +--- + +Curious about the internals or want to contribute? [CLAUDE.md](../CLAUDE.md) describes the architecture and conventions. diff --git a/docs/REMOTE-SERVER.md b/docs/REMOTE-SERVER.md new file mode 100644 index 0000000..3ee1177 --- /dev/null +++ b/docs/REMOTE-SERVER.md @@ -0,0 +1,40 @@ +# Remote libraries: a Konduktor server on your NAS + +Keep your whole library — the collection file and the music — on a server, and +open it from any computer with Konduktor. Prep tracks, edit playlists, and +export sticks for your gigs without the music ever living on your performance +laptop. + +The server is a small container (`server/`). It holds the library and saves it. +Playback, analysis and stem separation run on the computer you open it from, +on copies it downloads, so the server needs no GPU and does very little work. + +**On the server (e.g. TrueNAS SCALE):** + +1. Copy `server/compose.yaml` and `server/.env.example` (renamed to `.env`) + onto the NAS. Point the volumes at your datasets, and fill in `.env`: the + platform (`traktor` or `rekordbox`), the library file, the music folder, a + username and password, and — for a collection made on a Mac — the path + mapping (`/Users/you/Music => /music`). +2. Install it: on TrueNAS, **Apps → Discover Apps → ⋮ → Install via YAML** and + paste the compose file; anywhere else, `docker compose up -d`. A bad setting + stops the container with one clear line in its log. + +**In the app:** choose **Remote** on the platform screen → **Add a remote +library** → enter the server's address (and a fallback, such as its Tailscale +address, for when you're away from home), the username and the password. +Konduktor checks the server before it saves the remote, and keeps the +password in your keychain. + +Good to know: + +- **One computer at a time.** If another computer has the library open, + Konduktor says who has it and offers to take over. Edits that computer + hadn't saved stay with the library, and you're asked to save or discard + them. +- **Plain HTTP.** Reach the server over your home network or a VPN + (Tailscale / WireGuard). Don't expose its port to the internet. +- **Unsaved edits live on the server** until you save. Restarting the + container drops them. +- Downloaded tracks are cached on your computer (Settings → **Remote audio** + sets the size), so a track you've prepped and then export is fetched once. diff --git a/docs/screenshots/analyze.png b/docs/screenshots/analyze.png new file mode 100644 index 0000000..1c29379 Binary files /dev/null and b/docs/screenshots/analyze.png differ diff --git a/docs/screenshots/auto-hotcues.png b/docs/screenshots/auto-hotcues.png new file mode 100644 index 0000000..e79ab7b Binary files /dev/null and b/docs/screenshots/auto-hotcues.png differ diff --git a/docs/screenshots/deck.png b/docs/screenshots/deck.png new file mode 100644 index 0000000..5b05ebb Binary files /dev/null and b/docs/screenshots/deck.png differ diff --git a/docs/screenshots/export.png b/docs/screenshots/export.png new file mode 100644 index 0000000..0f64d54 Binary files /dev/null and b/docs/screenshots/export.png differ diff --git a/docs/screenshots/library.png b/docs/screenshots/library.png new file mode 100644 index 0000000..00eaefd Binary files /dev/null and b/docs/screenshots/library.png differ diff --git a/docs/screenshots/platforms.png b/docs/screenshots/platforms.png new file mode 100644 index 0000000..a6ba769 Binary files /dev/null and b/docs/screenshots/platforms.png differ diff --git a/docs/screenshots/stems.png b/docs/screenshots/stems.png new file mode 100644 index 0000000..f5ea95e Binary files /dev/null and b/docs/screenshots/stems.png differ diff --git a/frontend/index.html b/frontend/index.html index 528a475..21fe310 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -5,6 +5,11 @@ Konduktor + +
diff --git a/frontend/package.json b/frontend/package.json index 1edc00e..c57baa3 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "frontend", "private": true, - "version": "0.2.4", + "version": "0.2.5", "type": "module", "scripts": { "dev": "vite", diff --git a/frontend/src-tauri/.gitignore b/frontend/src-tauri/.gitignore index 62374f3..45dbf4e 100644 --- a/frontend/src-tauri/.gitignore +++ b/frontend/src-tauri/.gitignore @@ -3,6 +3,6 @@ /target/ /gen/schemas -# Frozen backend sidecar — a build artifact (23MB); rebuild with +# Frozen backend sidecar (a onedir folder) — a build artifact; rebuild with # backend/build_sidecar.sh. The Rust/config that reference it ARE tracked. /binaries/ diff --git a/frontend/src-tauri/entitlements.plist b/frontend/src-tauri/entitlements.plist index 7cfb3e4..cc61cdd 100644 --- a/frontend/src-tauri/entitlements.plist +++ b/frontend/src-tauri/entitlements.plist @@ -3,12 +3,13 @@ com.apple.security.cs.disable-library-validation diff --git a/frontend/src-tauri/src/lib.rs b/frontend/src-tauri/src/lib.rs index 81d29a6..08ae495 100644 --- a/frontend/src-tauri/src/lib.rs +++ b/frontend/src-tauri/src/lib.rs @@ -1,22 +1,38 @@ // Konduktor desktop shell (Tauri v2). // -// The backend is the frozen Python sidecar (see backend/sidecar.py): on launch -// we spawn it, read the `KONDUKTOR_PORT=` line it prints on stdout, wait for -// it to actually accept connections, then create the app window with an -// initialization script that hands the frontend its API base -// (`window.__KONDUKTOR_API__`). The sidecar is killed when the app exits. +// The backend is the frozen Python sidecar (see backend/sidecar.py), a +// PyInstaller ONEDIR folder bundled as the `sidecar/` resource — not an +// `externalBin`, which must be one file. A one-file build unpacked ~390 native +// libraries into a new temp folder on every launch, and macOS scans each +// library it has not seen before as it loads, so the window took ~10 s to +// appear; installed as a folder they are scanned once. +// +// The window opens AT ONCE and shows the startup screen (StartupScreen.tsx) +// while the backend starts: a first launch after an install or update still +// waits for that one-time scan, and a window that appears seconds late looks +// like an app that failed to open. Meanwhile we spawn the sidecar, read the +// `KONDUKTOR_PORT=` line it prints on stdout and wait for the socket to +// accept connections. The page asks `backend_status` and listens for +// `konduktor://backend` (starting / ready + url / stopped + the output's last +// lines); `backend_restart` is its Try again. There is no timeout here — a +// fresh install can take a minute — so the page decides when to ask the user. +// The sidecar is killed when the app exits. // // Quitting ASKS FIRST. Closing the window or Cmd/Ctrl+Q is prevented and -// becomes a `konduktor://quit-requested` event; the frontend (QuitGuard.tsx) -// acknowledges it, checks for unsaved changes and either quits (`quit_now`) or -// asks Save / Discard / Cancel. The sidecar must outlive that question — a -// Save or Discard runs in it — so it is killed only once the app really exits. -// If the webview does not acknowledge within ~2 s (hung, or not loaded yet), -// the app quits anyway: a broken page must never make the app unquittable. -use std::sync::atomic::{AtomicBool, Ordering}; +// becomes a `konduktor://quit-requested` event; the frontend (QuitGuard.tsx, +// or the startup screen before the app has loaded) acknowledges it, checks for +// unsaved changes and either quits (`quit_now`) or asks Save / Discard / +// Cancel. The sidecar must outlive that question — a Save or Discard runs in +// it — so it is killed only once the app really exits. If the webview does not +// acknowledge within ~2 s (hung, or not loaded yet), the app quits anyway: a +// broken page must never make the app unquittable. +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Mutex; use std::time::Duration; +use serde::Serialize; +use tauri::window::Color; use tauri::{AppHandle, Emitter, Manager, RunEvent, WebviewUrl, WebviewWindowBuilder, WindowEvent}; use tauri_plugin_shell::process::{CommandChild, CommandEvent}; use tauri_plugin_shell::ShellExt; @@ -24,6 +40,26 @@ use tauri_plugin_shell::ShellExt; /// Holds the running sidecar child so we can terminate it on exit. struct Sidecar(Mutex>); +/// How many of the sidecar's last output lines a "couldn't start" report keeps. +const LOG_LINES: usize = 30; + +/// What the startup screen shows. Serialised as `{"state": "starting"}`, +/// `{"state": "ready", "url": …}` or `{"state": "stopped", "code", "signal", "log"}`. +#[derive(Clone, Serialize)] +#[serde(tag = "state", rename_all = "snake_case")] +enum BackendStatus { + Starting, + Ready { url: String }, + Stopped { code: Option, signal: Option, log: Vec }, +} + +/// The backend's current status, plus a generation counter: each spawn bumps +/// it, so events from a sidecar that was replaced (Try again) are ignored. +struct Backend { + status: Mutex, + generation: AtomicU64, +} + /// Quit handshake state: `allowed` once the frontend (or the timeout) has said /// quit; `acked` once the frontend has seen the current request. struct Quit { @@ -59,6 +95,125 @@ fn request_quit(app: &AppHandle) { }); } +/// Record a new status for generation `gen` (ignored if a newer sidecar has +/// been spawned since) and tell the page. +fn set_status(app: &AppHandle, gen: u64, status: BackendStatus) { + let backend = app.state::(); + if backend.generation.load(Ordering::SeqCst) != gen { + return; + } + *backend.status.lock().unwrap() = status.clone(); + let _ = app.emit("konduktor://backend", status); +} + +fn push_lines(log: &mut VecDeque, bytes: &[u8]) { + for line in String::from_utf8_lossy(bytes).lines() { + if log.len() == LOG_LINES { + log.pop_front(); + } + log.push_back(line.to_string()); + } +} + +/// Spawn the sidecar and follow it until it is serving (ready) or exits (stopped). +fn start_backend(app: &AppHandle) { + kill_sidecar(app); + let gen = app.state::().generation.fetch_add(1, Ordering::SeqCst) + 1; + set_status(app, gen, BackendStatus::Starting); + + // The frozen backend lives in the bundled `sidecar/` folder (staged into + // src-tauri/binaries/ by backend/build_sidecar.*). + let exe = if cfg!(windows) { "konduktor-sidecar.exe" } else { "konduktor-sidecar" }; + let spawned = app + .path() + .resource_dir() + .map_err(|e| e.to_string()) + .and_then(|dir| { + let program = dir.join("sidecar").join(exe); + app.shell() + .command(&program) + .spawn() + .map_err(|e| format!("{}: {e}", program.display())) + }); + let (mut rx, child) = match spawned { + Ok(pair) => pair, + Err(e) => { + let log = vec![format!("Could not start the library service: {e}")]; + set_status(app, gen, BackendStatus::Stopped { code: None, signal: None, log }); + return; + } + }; + app.state::().0.lock().unwrap().replace(child); + + let handle = app.clone(); + tauri::async_runtime::spawn(async move { + let mut log = VecDeque::with_capacity(LOG_LINES); + let mut announced = false; + // Keep draining to the end, so the sidecar's pipes never fill and block it. + while let Some(event) = rx.recv().await { + match event { + CommandEvent::Stdout(bytes) => { + if !announced { + let text = String::from_utf8_lossy(&bytes); + let port = text.lines().find_map(|line| { + line.trim().strip_prefix("KONDUKTOR_PORT=")?.trim().parse::().ok() + }); + if let Some(port) = port { + announced = true; + wait_until_serving(handle.clone(), gen, port); + } + } + push_lines(&mut log, &bytes); + } + CommandEvent::Stderr(bytes) => push_lines(&mut log, &bytes), + CommandEvent::Error(e) => push_lines(&mut log, e.as_bytes()), + CommandEvent::Terminated(payload) => { + let status = BackendStatus::Stopped { + code: payload.code, + signal: payload.signal, + log: log.iter().cloned().collect(), + }; + set_status(&handle, gen, status); + } + _ => {} + } + } + }); +} + +/// The port line is printed before uvicorn binds: report ready once the socket +/// actually accepts connections (or give up quietly if this sidecar is gone). +fn wait_until_serving(app: AppHandle, gen: u64, port: u16) { + tauri::async_runtime::spawn(async move { + loop { + let backend = app.state::(); + let current = backend.generation.load(Ordering::SeqCst) == gen + && matches!(*backend.status.lock().unwrap(), BackendStatus::Starting); + if !current { + return; + } + if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() { + let url = format!("http://127.0.0.1:{port}"); + set_status(&app, gen, BackendStatus::Ready { url }); + return; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + }); +} + +/// Where the backend is: the startup screen asks once on load, then listens. +#[tauri::command] +fn backend_status(app: AppHandle) -> BackendStatus { + app.state::().status.lock().unwrap().clone() +} + +/// The startup screen's Try again. +#[tauri::command] +fn backend_restart(app: AppHandle) { + start_backend(&app); +} + /// The frontend has seen the quit request (it may now take as long as it likes). #[tauri::command] fn quit_ack(app: AppHandle) { @@ -82,8 +237,15 @@ pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_shell::init()) .manage(Sidecar(Mutex::new(None))) + .manage(Backend { status: Mutex::new(BackendStatus::Starting), generation: AtomicU64::new(0) }) .manage(Quit { allowed: AtomicBool::new(false), acked: AtomicBool::new(false) }) - .invoke_handler(tauri::generate_handler![quit_ack, quit_cancel, quit_now]) + .invoke_handler(tauri::generate_handler![ + backend_status, + backend_restart, + quit_ack, + quit_cancel, + quit_now + ]) .on_window_event(|window, event| { if let WindowEvent::CloseRequested { api, .. } = event { let app = window.app_handle(); @@ -102,71 +264,22 @@ pub fn run() { )?; } - let handle = app.handle().clone(); + start_backend(app.handle()); - // Spawn the frozen backend. In dev/bundle the shell plugin resolves - // the sidecar from `binaries/konduktor-sidecar-`. - let (mut rx, child) = app - .shell() - .sidecar("konduktor-sidecar") - .expect("sidecar binary not found (build it into src-tauri/binaries/)") - .spawn() - .expect("failed to spawn backend sidecar"); - app.state::().0.lock().unwrap().replace(child); - - tauri::async_runtime::block_on(async move { - // Read stdout until the backend announces its port (bounded so a - // misbehaving sidecar can't hang the launch forever). - let find_port = async { - while let Some(event) = rx.recv().await { - if let CommandEvent::Stdout(bytes) = event { - let text = String::from_utf8_lossy(&bytes); - for line in text.lines() { - if let Some(p) = line.trim().strip_prefix("KONDUKTOR_PORT=") { - if let Ok(n) = p.trim().parse::() { - return Some(n); - } - } - } - } - } - None - }; - let port = tokio::time::timeout(Duration::from_secs(20), find_port) - .await - .ok() - .flatten() - .expect("backend sidecar did not report a port"); - - // Keep draining events so the sidecar's stdout/stderr pipes never - // fill and block it; the task ends when the child exits. - tauri::async_runtime::spawn(async move { while rx.recv().await.is_some() {} }); - - // Wait for the socket to actually accept connections (the port - // line is printed before uvicorn binds). - for _ in 0..200 { - if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() { - break; - } - std::thread::sleep(Duration::from_millis(50)); - } - - let inject = - format!("window.__KONDUKTOR_API__ = 'http://127.0.0.1:{port}';"); - WebviewWindowBuilder::new(&handle, "main", WebviewUrl::App("index.html".into())) - .title("Konduktor") - .inner_size(1400.0, 900.0) - .min_inner_size(900.0, 600.0) - // On Windows the webview would otherwise be served from - // https://tauri.localhost, and fetching the sidecar over - // http://127.0.0.1 would be blocked as mixed content. Force - // the http custom-protocol scheme so both are http. (No-op on - // macOS, which uses the tauri:// scheme.) - .use_https_scheme(false) - .initialization_script(&inject) - .build() - .expect("failed to create the main window"); - }); + WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into())) + .title("Konduktor") + .inner_size(1400.0, 900.0) + .min_inner_size(900.0, 600.0) + // The page's own base colour (ink-950), so the first frame — + // before any CSS has loaded — is dark rather than white. + .background_color(Color(5, 6, 10, 255)) + // On Windows the webview would otherwise be served from + // https://tauri.localhost, and fetching the sidecar over + // http://127.0.0.1 would be blocked as mixed content. Force + // the http custom-protocol scheme so both are http. (No-op on + // macOS, which uses the tauri:// scheme.) + .use_https_scheme(false) + .build()?; Ok(()) }) diff --git a/frontend/src-tauri/tauri.conf.json b/frontend/src-tauri/tauri.conf.json index cb8b1e0..ed34927 100644 --- a/frontend/src-tauri/tauri.conf.json +++ b/frontend/src-tauri/tauri.conf.json @@ -19,7 +19,6 @@ "bundle": { "active": true, "targets": "all", - "externalBin": ["binaries/konduktor-sidecar"], "icon": [ "icons/32x32.png", "icons/128x128.png", diff --git a/frontend/src-tauri/tauri.macos.conf.json b/frontend/src-tauri/tauri.macos.conf.json new file mode 100644 index 0000000..33d942e --- /dev/null +++ b/frontend/src-tauri/tauri.macos.conf.json @@ -0,0 +1,8 @@ +{ + "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", + "bundle": { + "macOS": { + "files": { "Resources/sidecar": "binaries/konduktor-sidecar" } + } + } +} diff --git a/frontend/src-tauri/tauri.windows.conf.json b/frontend/src-tauri/tauri.windows.conf.json new file mode 100644 index 0000000..d79ff33 --- /dev/null +++ b/frontend/src-tauri/tauri.windows.conf.json @@ -0,0 +1,6 @@ +{ + "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", + "bundle": { + "resources": { "binaries/konduktor-sidecar/": "sidecar/" } + } +} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index ce3f938..c630aec 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -8,6 +8,7 @@ import { addTracksToPlaylist } from './lib/addTracks' import { useDropTarget } from './lib/drag' import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api' import { confirmDiscardUnsaved } from './lib/unsaved' +import { askConfirm } from './lib/confirm' import { COLUMN_MENU, DEFAULT_COLUMN_ORDER, @@ -80,6 +81,9 @@ export default function App() { const [prepOrigin, setPrepOrigin] = useState('collection') // The view's origin, read by the load callbacks below (defined before it). const viewOriginRef = useRef('collection') + // The browsed folder's rows that ARE collection tracks: collection id → the + // file's folder id. A ref, for the callbacks below that outlive a render. + const folderFilesRef = useRef>({}) // Browsed files being added to the collection (and maybe a playlist/export). const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null } | null>(null) const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays @@ -108,7 +112,9 @@ export default function App() { const loadTrack = useCallback((t: Track, origin: TrackOrigin = viewOriginRef.current) => { setPrepTrack(t) - setPrepOrigin(origin) + // A folder row the collection holds IS the collection track, so the deck + // loads it as one: its cues and grid, and editable (decided 2026-10-10). + setPrepOrigin(origin === 'folder' && folderFilesRef.current[t.id] ? 'collection' : origin) }, []) const playTrack = useCallback( (t: Track) => { @@ -307,6 +313,11 @@ export default function App() { () => new Set(folderView.data?.in_collection ?? []), [folderView.data], ) + const folderFiles = useMemo(() => folderView.data?.files ?? {}, [folderView.data]) + folderFilesRef.current = viewingFolder ? folderFiles : {} + // Adding speaks in FOLDER ids; a row the collection holds carries its + // collection id, and maps back (the add dialog then reports it as held). + const toFolderIds = (ids: string[]) => ids.map((id) => folderFiles[id] ?? id) viewOriginRef.current = viewingDevice ? 'device' : viewingFolder ? 'folder' : 'collection' // Tracks in view belong to ANOTHER library (a device) or to none (a folder), // so no collection command may be offered on them: their ids mean nothing to @@ -368,10 +379,16 @@ export default function App() { // asked (decided 2026-10-06). const addForeign = useCallback( (origin: TrackOrigin, ids: string[], target: AddTarget) => { - if (origin === 'folder') setAdding({ ids, target }) - else if (origin === 'device') setImportDrop({ ids, target }) + if (origin === 'folder') { + const files = folderFilesRef.current + // Rows that are all collection tracks already: nothing to add first. + if (ids.every((id) => files[id])) { + if (target.kind === 'playlist') void addToPlaylist(target.id, ids) + else void addToExport(target.id, ids) + } else setAdding({ ids: ids.map((id) => files[id] ?? id), target }) + } else if (origin === 'device') setImportDrop({ ids, target }) }, - [], + [addToPlaylist, addToExport], ) const [deckDropRef, deckOver] = useDropTarget({ hint: (p) => (p.kind === 'tracks' ? true : null), @@ -407,7 +424,10 @@ export default function App() { : origin === 'folder' ? (folderCaps.data ?? readOnlyCaps('not_in_library')) : capabilities.data! - const viewCaps = capsFor(viewOriginRef.current) + // A folder's table runs on the COLLECTION's: the rows it holds are collection + // tracks and edit as such, and a loose row asks to be added first + // (`folderMayEdit`) rather than rendering inert. + const viewCaps = viewingFolder ? capabilities.data! : capsFor(viewOriginRef.current) // The deck follows its TRACK's library, not the view's. const deckCaps = capsFor(prepOrigin) @@ -443,9 +463,12 @@ export default function App() { // PrepStrip keys its audio on the id, so a new object for the same id // reloads nothing. useEffect(() => { - if (!prepTrack || viewOriginRef.current !== prepOrigin) return + if (!prepTrack) return const fresh = tracks.find((t) => t.id === prepTrack.id) - if (fresh && JSON.stringify(fresh) !== JSON.stringify(prepTrack)) setPrepTrack(fresh) + if (!fresh) return + const origin = + viewOriginRef.current === 'folder' && folderFilesRef.current[fresh.id] ? 'collection' : viewOriginRef.current + if (origin === prepOrigin && JSON.stringify(fresh) !== JSON.stringify(prepTrack)) setPrepTrack(fresh) // Only a refetch of the list matters; prepTrack is read, not tracked. // eslint-disable-next-line react-hooks/exhaustive-deps }, [tracks]) @@ -636,7 +659,7 @@ export default function App() { } // ---- Convert to Stems ------------------------------------------------------ - const canStems = canEdit && !viewForeign && !!capabilities.data?.tracks.stem_convertible + const canStems = canEdit && !viewingDevice && !!capabilities.data?.tracks.stem_convertible const finishStemBatch = (state: string, r: StemBatchResult | null, error: string | null) => { qc.invalidateQueries({ queryKey: ['state'] }) if (state === 'failed' || !r) { @@ -788,7 +811,7 @@ export default function App() { // the rest with a reason. const canAnalyzeGrid = !!capabilities.data?.grid.editable const canAnalyzeKey = !!capabilities.data?.tracks.key_writable - const canAnalyze = canEdit && !viewForeign && (canAnalyzeGrid || canAnalyzeKey) + const canAnalyze = canEdit && !viewingDevice && (canAnalyzeGrid || canAnalyzeKey) const startCueBatch = (ids: string[]) => { const byId = new Map(tracks.map((t) => [t.id, t])) @@ -801,7 +824,7 @@ export default function App() { setBatchCancelling(false) setBatchJob({ id: job.id, kind: 'cues' }) } - const canAutoCue = canEdit && !viewForeign && (capabilities.data?.cues.hotcue_slots ?? 0) > 0 + const canAutoCue = canEdit && !viewingDevice && (capabilities.data?.cues.hotcue_slots ?? 0) > 0 // ---- Remove ▸ ----------------------------------------------------------- @@ -934,12 +957,48 @@ export default function App() { }), }) - const canClearGrids = canEdit && !viewForeign && !!capabilities.data?.grid.editable + const canClearGrids = canEdit && !viewingDevice && !!capabilities.data?.grid.editable const canClearCues = canAutoCue - const canRemoveTracks = canEdit && !viewForeign && !!capabilities.data?.tracks.removable + const canRemoveTracks = canEdit && !viewingDevice && !!capabilities.data?.tracks.removable // The COLLECTION's capabilities, deliberately: adding happens while a folder // or device is on screen, whose own capabilities are read-only. const canAddTracks = canEdit && !!capabilities.data?.tracks.addable + + // In a folder, only the rows the collection holds can be edited. Anything + // that would edit a loose file says so and offers to add it, rather than + // being absent or silently inert (decided 2026-10-10). + const askToAdd = async (ids: string[]) => { + const loose = ids.filter((id) => !folderFiles[id]) + if (!loose.length) return + const first = tracks.find((t) => t.id === loose[0]) + const what = + loose.length === 1 + ? `“${first?.title || 'This file'}” is not in your collection` + : `${loose.length} of these files are not in your collection` + if (!canAddTracks) { + notify('error', `${what}, and tracks cannot be added to this library.`) + return + } + const add = await askConfirm({ + title: 'Add to your collection first', + body: `${what} yet. Add ${loose.length === 1 ? 'it' : 'them'} to edit tags, cues or the beatgrid.`, + confirmLabel: 'Add to Collection…', + tone: 'primary', + }) + if (add) setAdding({ ids: loose, target: null }) + } + const folderEditField = (track: Track, field: keyof Track, value: string | number) => { + if (folderFiles[track.id]) editField(track, field, value) + else void askToAdd([track.id]) + } + const folderMayEdit = (track: Track) => { + if (folderFiles[track.id]) return true + void askToAdd([track.id]) + return false + } + // The open menu's loose files: every editing item then asks to add them. + const menuLoose = menu && viewingFolder ? menu.ids.filter((id) => !folderFiles[id]) : [] + const gated = (fn: () => void) => (menuLoose.length ? () => void askToAdd(menuLoose) : fn) const exportRootId = source.kind === 'export' ? source.id : source.kind === 'export-other' ? source.exportId : null const removeItems = (ids: string[]): MenuItem[] => [ @@ -1023,8 +1082,8 @@ export default function App() { : []), // Offering "Edit Tags…" on a read-only library would open a dialog // whose every save is refused, so it is not offered at all. - ...(canEdit && !viewForeign && menu.ids.length === 1 - ? [{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }] + ...(canEdit && !viewingDevice && menu.ids.length === 1 + ? [{ label: 'Edit Tags…', onClick: gated(() => setEditing(menu.track)) }] : []), ...(canAnalyze ? [ @@ -1032,7 +1091,7 @@ export default function App() { label: 'Analyze…', hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, disabled: !!batchJob, - onClick: () => setAnalyzing(menu.ids), + onClick: gated(() => setAnalyzing(menu.ids)), }, ] : []), @@ -1044,20 +1103,20 @@ export default function App() { label: 'Auto Hotcues…', hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, disabled: !!batchJob, - onClick: () => startCueBatch(menu.ids), + onClick: gated(() => startCueBatch(menu.ids)), }, ] : []), // Shown disabled WITH a reason where the platform cannot play stem // files as stems, rather than hidden: a missing item reads as a bug. - ...(canEdit && !viewForeign + ...(canEdit && !viewingDevice ? [ canStems ? { label: 'Convert to Stems…', hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, disabled: !!batchJob, - onClick: () => setStemDialog(menu.ids), + onClick: gated(() => setStemDialog(menu.ids)), } : { label: 'Convert to Stems…', @@ -1070,12 +1129,14 @@ export default function App() { // A device's track ids belong to the stick, not the collection, so // there is nothing they could be added to. A folder's files CAN be // added — through the add dialog, which puts them in the - // collection first. + // collection first; rows it already holds are collection tracks. ...(viewingFolder - ? canAddTracks + ? !menuLoose.length + ? [{ label: 'Add to', submenu: addToItems(menu.ids) }] + : canAddTracks ? [ - { label: 'Add to Collection…', onClick: () => setAdding({ ids: menu.ids, target: null }) }, - { label: 'Add to', submenu: folderAddToItems(menu.ids) }, + { label: 'Add to Collection…', onClick: () => setAdding({ ids: menuLoose, target: null }) }, + { label: 'Add to', submenu: folderAddToItems(toFolderIds(menu.ids)) }, ] : [{ label: 'Add to Collection…', @@ -1092,7 +1153,7 @@ export default function App() { ? [{ label: 'Set Position…', onClick: () => setPositioning(menu.ids) }] : []), ...(() => { - const items = removeItems(menu.ids) + const items = menuLoose.length ? [] : removeItems(menu.ids) return items.length ? [{ label: 'Remove', submenu: items }] : [] })(), ]} @@ -1315,9 +1376,11 @@ export default function App() { {' · this folder only'} - - Not in collection - + {tracks.length > heldInFolder.size && ( + + Not in collection + + )} {tracks.length > 0 && canAddTracks && ( + +
+
+

Sidebar

+ +
+
+

Exports

+ +
+ {error &&
{error}
} +
+
+ +
+ + , + document.body, + ) +} diff --git a/frontend/src/components/DevicesSection.tsx b/frontend/src/components/DevicesSection.tsx index b79afaa..0557fe6 100644 --- a/frontend/src/components/DevicesSection.tsx +++ b/frontend/src/components/DevicesSection.tsx @@ -1,13 +1,14 @@ import { useEffect, useState, type ReactNode } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { api, type Drive, type PlaylistNode } from '../api' +import { api, isServerPath, type Drive, type PlaylistNode } from '../api' import type { Source } from './Sidebar' import { Icon } from '../lib/icons' import { ContextMenu, type MenuItem } from './ContextMenu' /** * Every drive, in the sidebar: plugged-in ones under Devices, and the computer's - * own under an expandable Local Storage. + * own under an expandable Local Storage. While a remote library is open, the + * server holding it comes first: its content folder, browsed like any drive. * * A drive carrying a OneLibrary library opens as a device, the way rekordbox and * Traktor show a stick: its playlists appear under it and the ordinary track @@ -86,13 +87,15 @@ export function DevicesSection({ source, onSelect, onError, onImport, onOpenLibr }) const list = drives.data ?? [] + const server = list.filter((d) => d.kind === 'server') const external = list.filter((d) => d.kind === 'external') const local = list.filter((d) => d.kind === 'local') // A drive can be physically unplugged while it is open. Nothing crashes — the // routes just start failing — but leaving it selected would show a library // that is not there, so fall back to the collection. The same goes for a - // folder on it being browsed. + // folder on it being browsed — and for a folder on the server, the remote + // library being closed. const stillPresent = !openPath || list.some((d) => d.library?.path === openPath) useEffect(() => { if (!drives.isSuccess || !openPath || stillPresent || eject.isPending) return @@ -102,7 +105,11 @@ export function DevicesSection({ source, onSelect, onError, onImport, onOpenLibr const folderGone = source.kind === 'folder' && drives.isSuccess && - !list.some((d) => d.path === '/' || isInside(source.path, d.path)) + !list.some((d) => + isServerPath(source.path) + ? d.kind === 'server' + : d.path === '/' || isInside(source.path, d.path), + ) useEffect(() => { if (folderGone) onSelect({ kind: 'all' }) // eslint-disable-next-line react-hooks/exhaustive-deps @@ -137,7 +144,7 @@ export function DevicesSection({ source, onSelect, onError, onImport, onOpenLibr
} + icon={} label={d.name} title={d.path} expanded={expandedHere} @@ -212,6 +219,7 @@ export function DevicesSection({ source, onSelect, onError, onImport, onOpenLibr
+ {server.map((d) => driveRow(d, 0))} {external.map((d) => driveRow(d, 0))} {local.length > 0 && ( diff --git a/frontend/src/components/SettingsMenu.tsx b/frontend/src/components/SettingsMenu.tsx index 34b857a..e9d8929 100644 --- a/frontend/src/components/SettingsMenu.tsx +++ b/frontend/src/components/SettingsMenu.tsx @@ -1,6 +1,7 @@ import { useEffect, useRef, useState } from 'react' import { useQuery } from '@tanstack/react-query' import { api } from '../api' +import { AppSettings } from './AppSettings' import { useCaps } from '../lib/capabilities' import { RemoteCacheSettings } from './RemoteCacheSettings' import { ShortcutsDialog } from './ShortcutsDialog' @@ -12,14 +13,15 @@ interface Props { up?: boolean } -/** Overflow menu for low-frequency, collection-level settings. Currently holds - * path remapping, Stems and the shortcut list; the natural home for future advanced - * settings. The shortcuts dialog is owned here, since nothing else opens it. */ +/** Overflow menu for low-frequency settings: the app's own (Konduktor + * settings), path remapping, Stems and the shortcut list. The dialogs are owned + * here, since nothing else opens them. */ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) { const [open, setOpen] = useState(false) const [showShortcuts, setShowShortcuts] = useState(false) const [showStems, setShowStems] = useState(false) const [showCache, setShowCache] = useState(false) + const [showApp, setShowApp] = useState(false) const ref = useRef(null) // Path remapping is a library on THIS computer's business; a remote's // mapping is its server's configuration. @@ -66,6 +68,16 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) { up ? 'bottom-full mb-1' : 'mt-1' }`} > + {remappable && (
) } diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index 53295c8..0287718 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -6,6 +6,7 @@ import { useCaps } from '../lib/capabilities' import { SaveBar } from './SaveBar' import { confirmDiscardUnsaved } from '../lib/unsaved' import { SettingsMenu } from './SettingsMenu' +import { useAppSetting } from './AppSettings' import { DevicesSection } from './DevicesSection' import { ExportsSection } from './ExportsSection' import { ConfirmDialog, type ConfirmRequest } from './ConfirmDialog' @@ -14,7 +15,7 @@ import { Icon, type IconName } from '../lib/icons' import { PlatformIcon } from '../lib/platformIcons' import { addTracksToPlaylist } from '../lib/addTracks' import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload } from '../lib/drag' -import { nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree' +import { findNode, idsAfter, nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree' /** * Which view the main table is showing. @@ -99,8 +100,11 @@ type Draft = { kind: 'playlist' | 'folder'; parentId: string | null } /** Actions a row can ask of the sidebar. They live there, not in the row, so * the right-click menu and the hover buttons run the very same code. */ interface RowActions { + /** Whether a folder is open, and opening / closing it. */ + isOpen: (node: PlaylistNode) => boolean + setOpen: (node: PlaylistNode, open: boolean) => void onContextMenu: (e: React.MouseEvent, node: PlaylistNode) => void - onRename: (node: PlaylistNode, name: string) => void + onRename: (node: PlaylistNode, name: string, parentId: string | null) => void onDelete: (node: PlaylistNode) => void onAddToExport: (node: PlaylistNode, setId: string) => void /** The row's export button: the export list as a menu under it. */ @@ -202,7 +206,7 @@ function NodeRow({ exportSets: { id: string; name: string }[] actions: RowActions }) { - const [open, setOpen] = useState(true) + const open = actions.isOpen(node) const renaming = renamingId === node.id const [renameDraft, setRenameDraft] = useState(node.name) const isFolder = node.kind === 'folder' @@ -278,9 +282,11 @@ function NodeRow({ // Holding a drag over a collapsed folder opens it, so a playlist nested in // it can be reached without letting go. const opening = over?.zone === 'into' || over?.zone === 'peek' + const openLater = useRef(() => actions.setOpen(node, true)) + openLater.current = () => actions.setOpen(node, true) useEffect(() => { if (!opening || expanded) return - const t = setTimeout(() => setOpen(true), 600) + const t = setTimeout(() => openLater.current(), 600) return () => clearTimeout(t) }, [opening, expanded]) const ringed = over?.zone === 'tracks' || over?.zone === 'into' @@ -314,7 +320,7 @@ function NodeRow({ )} + + + + ) +} + +function StoppedCard({ status }: { status: Extract }) { + const [busy, setBusy] = useState(false) + const [copied, setCopied] = useState(false) + const logRef = useRef(null) + const summary = + status.code !== null + ? `The library service exited with code ${status.code}.` + : status.signal !== null + ? `The library service was stopped by signal ${status.signal}.` + : null + const lines = status.log.length ? status.log : ['It wrote nothing before stopping.'] + const details = [`Konduktor v${__APP_VERSION__}`, ...(summary ? [summary] : []), ...lines].join('\n') + + // Show the end of the output: that is where the error is. + useEffect(() => { + const el = logRef.current + if (el) el.scrollTop = el.scrollHeight + }, [status]) + + const copy = async () => { + try { + await navigator.clipboard.writeText(details) + setCopied(true) + window.setTimeout(() => setCopied(false), 2000) + } catch { + // No clipboard access: select the text so Cmd/Ctrl+C works. + const el = logRef.current + if (!el) return + const range = document.createRange() + range.selectNodeContents(el) + window.getSelection()?.removeAllRanges() + window.getSelection()?.addRange(range) + } + } + + const retry = async () => { + setBusy(true) + try { + await shell('backend_restart') + } finally { + setBusy(false) + } + } + + return ( +
+
+ + + +
+

+ Konduktor couldn't start +

+

+ Its library service stopped before it was ready. Nothing in your libraries was changed. Try again, and + if it keeps happening, send the details below with your report. +

+
+
+
+        {summary && 
{summary}
} + {lines.map((line, i) => ( +
+ {line || ' '} +
+ ))} +
+
+ +
+ + +
+
+ ) +} + +// ---- The mark: the app icon, with a track scrolling under a fixed playhead ---- + +const BEAT = 60 / 128 +/** CSS px per second of audio, at the mark's 104 px. */ +const SPEED = 46 +/** 2 px bars with a 1 px gap: the main waveform's rhythm. */ +const BAR = 2 +const SLOT = 3 +/** The icon's own four bands, back to front. */ +const BANDS = ['#ff6a3d', '#8f6bff', '#3f9dff', '#7fe6ff'] + +const jitter = (i: number) => { + const x = Math.sin(i * 12.9898) * 43758.5453 + return x - Math.floor(x) +} + +/** Band levels (0..1) of a generated house track at time t: a kick on every + * beat, offbeat bass and hats, a clap on 2 and 4, a fill every 16 beats. */ +function levels(t: number) { + const n = Math.floor(t / BEAT) + const pos = t - n * BEAT + const in16 = n % 16 + const fill = in16 >= 14 + const sixteenth = BEAT / 4 + const p16 = t % sixteenth + const kick = fill ? 0 : Math.exp(-pos / 0.11) + const bass = pos > BEAT / 2 ? 0.5 * Math.exp(-(pos - BEAT / 2) / 0.16) : 0 + const roll = fill ? 0.35 + (0.5 * ((in16 - 14) * 4 + Math.floor(pos / sixteenth))) / 8 : 0 + const clap = (n % 2 === 1 ? 0.8 : 0) * Math.exp(-pos / 0.07) + roll * Math.exp(-p16 / 0.05) + const pad = 0.22 + 0.08 * Math.sin(t * 0.9) + const hat = 0.85 * Math.exp(-Math.abs(pos - BEAT / 2) / 0.025) + 0.3 * Math.exp(-p16 / 0.02) + return { low: Math.max(kick, bass), mid: Math.max(clap, pad, kick * 0.5), high: Math.max(hat, clap * 0.6) } +} + +function drawWave(ctx: CanvasRenderingContext2D, w: number, h: number, scroll: number) { + ctx.clearRect(0, 0, w, h) + const mid = h / 2 + const half = h * 0.34 + const centre = w / 2 + const first = Math.floor(scroll / SLOT) - 1 + const last = first + Math.ceil(w / SLOT) + 2 + for (let i = first; i <= last; i++) { + const x = i * SLOT - scroll + const t = (i * SLOT) / SPEED + // The peak over the slot, so a kick never falls between two samples. + const a = levels(t) + const b = levels(t + SLOT / SPEED / 2) + const low = Math.max(a.low, b.low) + const md = Math.max(a.mid, b.mid) + const hi = Math.max(a.high, b.high) + const j = 0.9 + 0.2 * jitter(i) + const h0 = half * Math.min(1, (0.16 + 0.84 * Math.max(low, md * 0.8, hi * 0.55)) * j) + const h1 = Math.min(h0 * 0.86, half * (0.1 + 0.6 * md) * j) + const h2 = Math.min(h1 * 0.84, half * (0.07 + 0.5 * hi) * j) + const h3 = Math.min(h2 * 0.78, half * (0.04 + 0.32 * hi) * j) + // Played audio, left of the playhead, sits dimmer, as on a deck. + ctx.globalAlpha = x + BAR / 2 < centre ? 0.6 : 1 + ;[h0, h1, h2, h3].forEach((bh, k) => { + ctx.fillStyle = BANDS[k] + ctx.fillRect(x, mid - bh, BAR, bh * 2) + }) + } + ctx.globalAlpha = 1 + // Bars enter and leave softly at the icon's edges. + ctx.globalCompositeOperation = 'destination-in' + const g = ctx.createLinearGradient(0, 0, w, 0) + g.addColorStop(0, 'rgba(0,0,0,0)') + g.addColorStop(0.14, '#000') + g.addColorStop(0.86, '#000') + g.addColorStop(1, 'rgba(0,0,0,0)') + ctx.fillStyle = g + ctx.fillRect(0, 0, w, h) + ctx.globalCompositeOperation = 'source-over' +} + +function StartupMark() { + const canvas = useRef(null) + useEffect(() => { + const el = canvas.current + const ctx = el?.getContext('2d') + if (!el || !ctx) return + const w = el.offsetWidth + const h = el.offsetHeight + const dpr = window.devicePixelRatio || 1 + el.width = Math.round(w * dpr) + el.height = Math.round(h * dpr) + ctx.setTransform(dpr, 0, 0, dpr, 0, 0) + // Reduced motion: one still frame. + if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) { + drawWave(ctx, w, h, 0) + return + } + let raf = 0 + let start: number | null = null + const frame = (now: number) => { + start ??= now + drawWave(ctx, w, h, ((now - start) / 1000) * SPEED) + raf = requestAnimationFrame(frame) + } + raf = requestAnimationFrame(frame) + return () => cancelAnimationFrame(raf) + }, []) + + return ( +
+ + + + + + + + + + + + + + + + + + + + + {/* Clipped to the icon's rounded square: rx 22 inside a 2-unit inset. */} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ ) +} diff --git a/frontend/src/components/TrackTable.tsx b/frontend/src/components/TrackTable.tsx index bc4dd08..35e7454 100644 --- a/frontend/src/components/TrackTable.tsx +++ b/frontend/src/components/TrackTable.tsx @@ -82,6 +82,8 @@ interface Props { onHeaderContextMenu?: (x: number, y: number) => void onPlay?: (track: Track) => void onEditField?: (track: Track, field: keyof Track, value: string | number) => void + /** Per-row gate on opening an inline editor (`TableMeta.mayEdit`). */ + mayEdit?: (track: Track) => boolean activeTrackId?: string | null /** Whether the deck is playing `activeTrackId` (vs. loaded but paused). */ activePlaying?: boolean @@ -287,6 +289,7 @@ export function TrackTable({ onHeaderContextMenu, onPlay, onEditField, + mayEdit, activeTrackId, activePlaying = false, }: Props) { @@ -299,7 +302,7 @@ export function TrackTable({ data, columns: TRACK_COLUMNS, state: { sorting, columnVisibility, columnOrder, columnSizing }, - meta: { onEditField, editableFields }, + meta: { onEditField, editableFields, mayEdit }, onSortingChange: (updater) => onSortingChange(typeof updater === 'function' ? updater(sorting) : updater), onColumnSizingChange: (updater) => diff --git a/frontend/src/lib/playlistTree.ts b/frontend/src/lib/playlistTree.ts index f4cf5ac..d554aba 100644 --- a/frontend/src/lib/playlistTree.ts +++ b/frontend/src/lib/playlistTree.ts @@ -20,3 +20,26 @@ export function nodeIdsUnder(node: PlaylistNode): Set { walk(node) return ids } + +/** The node with this id, anywhere in the tree. */ +export function findNode(nodes: PlaylistNode[], id: string): PlaylistNode | undefined { + for (const n of nodes) { + if (n.id === id) return n + const found = findNode(n.children, id) + if (found) return found + } + return undefined +} + +/** Old id → new id for a node and everything nested in it, after a rename or + * move that may have changed them (a platform addressing folders by path). + * Neither changes a subtree's shape, so the two are matched by position. */ +export function idsAfter(before: PlaylistNode, after: PlaylistNode): Map { + const map = new Map() + const walk = (a: PlaylistNode, b: PlaylistNode) => { + map.set(a.id, b.id) + a.children.forEach((c, i) => b.children[i] && walk(c, b.children[i])) + } + walk(before, after) + return map +} diff --git a/frontend/src/lib/trackColumns.tsx b/frontend/src/lib/trackColumns.tsx index 671073e..96eb904 100644 --- a/frontend/src/lib/trackColumns.tsx +++ b/frontend/src/lib/trackColumns.tsx @@ -29,6 +29,10 @@ declare module '@tanstack/react-table' { * platforms genuinely differ in WHICH fields they accept. Undefined means * "not gated" — every field with a handler stays editable. */ editableFields?: ReadonlySet + /** Asked before an inline editor opens on a row; false keeps it closed. + * A view mixing editable rows with others (a folder: collection tracks + * beside loose files) answers per row — and says why itself. */ + mayEdit?: (track: Track) => boolean } } @@ -42,6 +46,7 @@ function InlineEdit({ onCommit, className = 'w-full min-w-0 truncate text-muted', readOnly = false, + onBegin, }: { value: string | null display?: ReactNode @@ -49,6 +54,8 @@ function InlineEdit({ className?: string /** Render the value without offering an editor. */ readOnly?: boolean + /** Asked on double-click; false keeps the editor closed. */ + onBegin?: () => boolean }) { const [editing, setEditing] = useState(false) const [val, setVal] = useState('') @@ -91,6 +98,7 @@ function InlineEdit({
{ e.stopPropagation() + if (onBegin && !onBegin()) return setVal(value ?? '') setEditing(true) }} @@ -102,6 +110,11 @@ function InlineEdit({ ) } +/** Whether this row's editor may open (`TableMeta.mayEdit`). */ +function mayBegin(c: CellContext): boolean { + return c.table.options.meta?.mayEdit?.(c.row.original) ?? true +} + /** Whether this table may edit `field`, per the platform's capabilities. */ function canEdit(c: CellContext, field: string): boolean { const meta = c.table.options.meta @@ -116,6 +129,7 @@ function editable(field: keyof Track, className?: string) { value={c.getValue() as string | null} className={className} readOnly={!canEdit(c, field)} + onBegin={() => mayBegin(c)} onCommit={(v) => c.table.options.meta?.onEditField?.(c.row.original, field, v)} /> ) @@ -137,12 +151,14 @@ export const TRACK_COLUMNS: ColumnDef[] = [ display={title || Untitled} className="w-full min-w-0 truncate font-medium text-text group-data-[active]:text-accent" readOnly={!canEdit(c, 'title')} + onBegin={() => mayBegin(c)} onCommit={(v) => edit?.(r, 'title', v)} /> mayBegin(c)} onCommit={(v) => edit?.(r, 'artist', v)} />
@@ -310,6 +326,7 @@ export const TRACK_COLUMNS: ColumnDef[] = [ value={c.getValue() as string | null} display={{formatDate(c.getValue() as string | null)}} readOnly={!canEdit(c, 'release_date')} + onBegin={() => mayBegin(c)} onCommit={(v) => c.table.options.meta?.onEditField?.(c.row.original, 'release_date', v)} /> ), diff --git a/frontend/src/lib/trackQueries.ts b/frontend/src/lib/trackQueries.ts index 161856a..10af416 100644 --- a/frontend/src/lib/trackQueries.ts +++ b/frontend/src/lib/trackQueries.ts @@ -11,6 +11,8 @@ const TRACK_LIST_KEYS = [ ['export-tracks'], ['export-playlist-tracks'], ['export-loose'], + // A folder lists the files the collection holds AS collection tracks. + ['folder-tracks'], ] as const /** Refetch every collection track list, plus the unsaved-edits state. */ diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 0e961fe..c3f8a45 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -11,6 +11,7 @@ import { ConfirmHost } from './lib/confirm.tsx' import { DragLayer } from './lib/drag.tsx' import { QuitGuard } from './components/QuitGuard.tsx' import { preventHistoryNavigation } from './lib/noNavigation.ts' +import { StartupGate } from './components/StartupScreen.tsx' preventHistoryNavigation() @@ -28,15 +29,18 @@ createRoot(document.getElementById('root')!).render( {/* Behind everything, the picker screen included: every surface is glass over it. */} - - {/* Mounted beside App so the update dialog shows even on the picker screen. */} - - {/* askConfirm()'s dialogs — the app's replacement for window.confirm. */} - - {/* Save · Discard · Cancel when quitting with unsaved changes. */} - - {/* The ghost under the cursor while dragging tracks or playlists. */} - + {/* The desktop app's startup screen: nothing below mounts until the backend answers. */} + + + {/* Mounted beside App so the update dialog shows even on the picker screen. */} + + {/* askConfirm()'s dialogs — the app's replacement for window.confirm. */} + + {/* Save · Discard · Cancel when quitting with unsaved changes. */} + + {/* The ghost under the cursor while dragging tracks or playlists. */} + + , )