mirror of
https://github.com/got-feedBack/feedBack.git
synced 2026-08-11 03:09:57 +00:00
feat(folder_library): Folder Library core plugin (#610)
Adds the bundled Folder Library plugin (browse the DLC library by its on-disk folder tree, in-app folder CRUD, drag-and-drop + dialog song moves, sort/filter, live search), wired into the classic v2 toolbar and the v3 Songs page. Includes the screen.js IIFE dedup (unified surface factory) and review fixes: path-traversal guard on /song/move, folder-delete data-loss fix, plural /api/plugins/<id> namespace, loose-folder song recognition, error-text escaping, v3 setLibView null-guard, and tests. Co-authored-by: Kyle <kyle.j.t@live.co.uk> Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Kyle
Claude Opus 4.8
parent
d1f7f12293
commit
3b2d83d406
@@ -0,0 +1,345 @@
|
||||
# Folder Library — AI Agent Guide
|
||||
|
||||
A FeedBack (fee[dB]ack) plugin that adds a **Folders** nav screen showing your `.sloppak` / `.feedpak` DLC songs grouped by the folder tree on disk. Create, rename, and delete folders (including **nested subfolders**) directly in the UI, move songs by drag-and-drop, and browse with sort and metadata filters.
|
||||
|
||||
> The host app is **FeedBack** (formerly "Slopsmith"). The frontend talks to the host through `window.feedBack`; `window.slopsmith` is a back-compat alias the host still exposes (`window.slopsmith = window.feedBack` in `static/app.js`). New code should prefer `window.feedBack`.
|
||||
|
||||
> ⚠️ **Status — bundled core plugin.** This plugin began as a standalone plugin and is now a bundled core plugin. `screen.js` has been unified into a **single surface factory** driving two entry points: the v3 library Folder view (host chrome — host search `#v3-search`/`#lib-filter`, host filter params, renders into `#lib-folder-tree`) and the classic v2 standalone Folders nav-tab (its own `#fb-search` + toolbar, renders into `#fb-tree`). **Folder search works on both surfaces** — typing in the relevant search box re-renders the tree. **Loose-folder songs** (directories with audio + an arrangement XML) are recognised as songs via the host `loosefolder.is_loose_song` predicate, so they appear in the tree alongside `.sloppak`/`.feedpak` bundles. Folder management, nested subfolders, collapsible folders + expand/collapse-all, drag-and-drop, move-song, sort, filters, and the hover metadata badges are wired on both surfaces; verify against a running build before relying on any of it.
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
plugin.json Plugin manifest — id, name, nav entry, file declarations ("bundled": true core plugin)
|
||||
routes.py FastAPI backend — recursive DLC scan, folder tree + filters, folder/song mutations, two-level cache
|
||||
screen.html Plugin screen content — injected by the host into the plugin div automatically
|
||||
screen.js Frontend logic — recursive folder tree, search, sort, filters, drag-and-drop, modals
|
||||
README.md User-facing docs
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
This plugin follows the standard FeedBack plugin pattern (see the repo-root `CLAUDE.md` for the full plugin system reference).
|
||||
|
||||
- **Backend** (`routes.py`) — registers routes under `GET/POST /api/plugins/folder_library/`. Uses `context["get_dlc_dir"]()`, `context["extract_meta"]()`, and `context["log"]`. Scans `<dlc>/sloppak/` if it exists, otherwise `<dlc>/`. Recursively walks the tree and handles create/rename/delete folder and move-song operations on slash-separated folder paths.
|
||||
- **Frontend** (`screen.js`) — plain vanilla JS in an IIFE. Fetches the tree from the backend on screen load, recursively renders collapsible folder sections (any depth) and song rows or cards (grid view). Uses `window.feedBack.on('screen:changed', ...)` (via the `window.slopsmith` alias) to trigger load when the user navigates here. Calls `window.playSong(filename)` on song click with the full relative path from the DLC root.
|
||||
- **No dependencies** — no npm, no build step. Tailwind utility classes available globally from the host; the plugin uses only core-guaranteed utilities and inline styles, so it ships **no** `styles` manifest key.
|
||||
|
||||
## Critical Layout Lessons (Hard-Won)
|
||||
|
||||
These are non-obvious behaviours of the FeedBack desktop app (Electron) that took significant debugging to discover. They still apply unchanged.
|
||||
|
||||
### 1. Do NOT put an outer wrapper div in screen.html
|
||||
The host automatically creates `<div id="plugin-folder_library" class="screen">` and injects `screen.html` content inside it. If you add your own outer div with `class="screen"`, you get a nested screen element which gets `display:none` applied, hiding all content.
|
||||
|
||||
**Wrong:**
|
||||
```html
|
||||
<div id="plugin-folder_library" class="screen">
|
||||
<div>toolbar</div>
|
||||
<div>content</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
```html
|
||||
<!-- no outer wrapper — the host provides it -->
|
||||
<div>toolbar</div>
|
||||
<div>content</div>
|
||||
```
|
||||
|
||||
### 2. The .screen CSS class sets display:none by default
|
||||
`.screen { display: none }` and `.screen.active { display: block }`. There is no height set. The screen div gets its height purely from its content. Do not try to set height via CSS classes — use inline styles or JS if needed.
|
||||
|
||||
### 3. The host navbar is position:fixed with z-index:50
|
||||
The navbar sits at `top:0, z-index:50`. Plugin toolbars must use `position:fixed; top:64px; z-index:40` to sit below the navbar. Use a solid `background-color` (not Tailwind bg classes — those may not apply correctly) to prevent content showing through.
|
||||
|
||||
### 4. Content must have padding-top to clear the fixed toolbar
|
||||
Since the toolbar is `position:fixed`, it floats above the content. The content container needs enough `padding-top` (~120px) to ensure the first item isn't hidden behind the toolbar — the host navbar (64px) plus the plugin toolbar height (~56px). Adding more toolbar buttons increases this height, so if content is clipped, increase the padding further.
|
||||
|
||||
### 5. Electron blocks window.prompt() and window.confirm()
|
||||
The desktop app is built on Electron, which throws `Error: prompt() is not supported`. Use a custom inline modal instead. See `_showModal()` in `screen.js` — it returns a Promise and supports both text input and confirm modes.
|
||||
|
||||
### 6. The nav plugin dropdown has z-index:50 and blocks clicks
|
||||
When navigating to a plugin screen via the Plugins dropdown, the dropdown stays open and sits on top of the screen. Call `_closeDropdown()` on screen load to dismiss it. The dropdown element id is `plugin-dropdown`.
|
||||
|
||||
### 7. playSong() expects a relative path from the DLC root
|
||||
`window.playSong()` expects the path relative to the DLC root with forward slashes, e.g. `sloppak/CH/Artist - Title.sloppak`. Not just the filename. The backend builds this in `_meta()` via `"/".join(p.relative_to(dlc).parts)` and returns it as each song's `filename`.
|
||||
|
||||
### 8. FastAPI POST routes need `from fastapi import Request`
|
||||
Routes that receive a JSON body must import `Request` from fastapi explicitly and use `async def route(request: Request)` with `body = await request.json()`. Missing this import crashes the server on plugin load.
|
||||
|
||||
### 9. Plugin id must be consistent everywhere
|
||||
The plugin id (`folder_library`) must match in:
|
||||
- `plugin.json` → `"id"` and `"nav.screen"`
|
||||
- `screen.js` → `PLUGIN_ID` constant and `API` constant (`/api/plugins/folder_library`)
|
||||
- `routes.py` → `APIRouter(prefix="/api/plugins/folder_library")`
|
||||
|
||||
A mismatch in any of these causes silent failures (blank screen, 404 API calls).
|
||||
|
||||
### 10. Use inline styles for grid layout, not Tailwind
|
||||
Tailwind's `grid` and `grid-cols-*` classes may not apply reliably inside the plugin div. Use `element.style.cssText` with explicit `display:grid; grid-template-columns:...` for the grid container.
|
||||
|
||||
## Key Conventions
|
||||
|
||||
- **IIFE + `'use strict'`** — all frontend code wrapped in `(function(){ 'use strict'; ... })();`
|
||||
- **localStorage prefixes** — plugin keys are prefixed `fo:` (e.g. `fo:view`, `fo:sort`, `fo:filters`); host-library-synced filter state uses `fo:lib:`. Open-folder state is tracked by **folder path** (so nested folders each remember their own state).
|
||||
- **Safe storage access** — all `localStorage` reads/writes wrapped in try/catch
|
||||
- **Logging** — backend uses `context["log"]`, never `print()`
|
||||
- **Sibling imports** — use `context["load_sibling"]("name")` not bare `import name` (none needed today; keep this in mind if you add helper modules)
|
||||
|
||||
## Song Formats
|
||||
|
||||
The plugin treats both `.sloppak` and `.feedpak` as songs (`_is_song()` in `routes.py`). `feedpak` is the published name for the same on-disk format the codebase still calls `sloppak` internally — see the repo-root `CLAUDE.md`. Both file form (`.sloppak`/`.feedpak` zip) and directory form (`*.sloppak/` folder) are recognized.
|
||||
|
||||
## Backend Routes
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| GET | `/api/plugins/folder_library/tree` | Returns the folder tree. Accepts optional filter query params (below) applied server-side. |
|
||||
| POST | `/api/plugins/folder_library/folder/create` | Body: `{name, parent?}` — creates a subfolder; `parent` (slash path) nests it inside an existing folder, omit/empty for top level |
|
||||
| POST | `/api/plugins/folder_library/folder/rename` | Body: `{old, new}` — `old` is a slash path, `new` is a bare name; renames within the same parent |
|
||||
| POST | `/api/plugins/folder_library/folder/delete` | Body: `{name}` (slash path) — moves all songs at any depth to the scan root, then removes the folder |
|
||||
| POST | `/api/plugins/folder_library/song/move` | Body: `{filename, folder}` — moves a song to `folder` (slash path; empty = scan root / "Unsorted") |
|
||||
|
||||
### `/tree` filter query params
|
||||
|
||||
All optional, applied server-side over the cached full tree by `_apply_tree_filters()`. Comma-separated, case-insensitive:
|
||||
|
||||
- `arrangements_has`, `arrangements_lacks` — include/exclude by arrangement name
|
||||
- `stems_has`, `stems_lacks` — include/exclude by stem name
|
||||
- `has_lyrics` — `""` (any), `"1"`, or `"0"`
|
||||
- `tunings` — comma-separated tuning names to include
|
||||
|
||||
The frontend forwards the host library's active filter params here (via `window.feedBackLibFilterParams()` when present, with `window.slopsmithLibFilterParams()` as a legacy fallback) so the Folders view can stay in sync with the main library filters, falling back to its own filter panel state otherwise.
|
||||
|
||||
### Path safety
|
||||
|
||||
`_safe_name()` rejects empty names, leading/trailing whitespace, the characters `\ / : * ? " < > |`, and `.`/`..`. `_safe_path()` applies `_safe_name()` to every slash-separated segment, so traversal (`..`) and absolute paths are rejected before any filesystem op. Always validate user-supplied folder paths through these before touching disk.
|
||||
|
||||
## Tree Shape
|
||||
|
||||
`/tree` returns:
|
||||
|
||||
```json
|
||||
{
|
||||
"folders": [
|
||||
{
|
||||
"name": "CH",
|
||||
"path": "CH",
|
||||
"songs": [ /* song objects */ ],
|
||||
"children": [
|
||||
{ "name": "Live", "path": "CH/Live", "songs": [], "children": [] }
|
||||
]
|
||||
}
|
||||
],
|
||||
"root_songs": [ /* songs sitting directly in the scan root — shown as "Unsorted" */ ]
|
||||
}
|
||||
```
|
||||
|
||||
Folder nodes are **recursive**: each has `name`, `path` (slash-separated, relative to the scan root), `songs`, and `children`. The frontend renders any depth — `_findFolderByPath()`, `_countDeep()`, and `_countFoldersDeep()` walk the `children` arrays.
|
||||
|
||||
## Song Metadata Format
|
||||
|
||||
Each song object (built by `_meta()`):
|
||||
|
||||
```json
|
||||
{
|
||||
"filename": "sloppak/CH/Artist - Title.sloppak",
|
||||
"title": "Title",
|
||||
"artist": "Artist",
|
||||
"album": "Album Name",
|
||||
"duration": 213.5,
|
||||
"year": 1993,
|
||||
"tuning": "E Standard",
|
||||
"added": 1748132400.0,
|
||||
"arrangements": ["Lead", "Rhythm", "Bass"],
|
||||
"stems": ["Drums", "Bass", "Vocals"],
|
||||
"lyrics": true
|
||||
}
|
||||
```
|
||||
|
||||
- `filename` is the full relative path from the DLC root — pass it directly to `window.playSong()`.
|
||||
- `added` is a Unix timestamp (float, seconds) from `stat().st_mtime` — convert with `new Date(added * 1000)`. Always recomputed fresh (it changes when a file moves), even on a metadata-cache hit.
|
||||
- `arrangements` / `stems` are flat lists of **strings**, even though `extract_meta()` returns them as objects.
|
||||
|
||||
### extract_meta returns arrangements/stems as objects, not strings
|
||||
|
||||
`context["extract_meta"]()` returns arrangements as a list of objects `{index, name, notes}`, not plain strings; stems similarly. `_meta()` normalizes to `.name`:
|
||||
|
||||
```python
|
||||
raw_arr = raw.get("arrangements") or []
|
||||
m["arrangements"] = [
|
||||
a["name"] if isinstance(a, dict) else str(a)
|
||||
for a in raw_arr
|
||||
if (isinstance(a, dict) and "name" in a) or isinstance(a, str)
|
||||
]
|
||||
```
|
||||
|
||||
`lyrics` is coerced to a bool from several possible keys (`lyrics`, `hasLyrics`, `has_lyrics`, …). If you add new metadata fields from `extract_meta`, check the raw shape before assuming it's a plain value.
|
||||
|
||||
## Two-Level Cache
|
||||
|
||||
`routes.py` keeps two caches inside `setup()`:
|
||||
|
||||
- **`_meta_cache`** — expensive `extract_meta()` results keyed by absolute POSIX path. **Never cleared.** When files move (rename/delete/move), the keys are rewritten in-place so the warm data survives the operation.
|
||||
- **`_cache`** — the assembled tree structure (`folders` / `root_songs`). Cleared by `_invalidate()` on **every** mutation so the next `/tree` rebuilds it — but the rebuild is fast because `_meta_cache` is still warm.
|
||||
|
||||
`filename` and `added` are deliberately **not** stored in `_meta_cache` (they depend on the file's current location) — they're recomputed on every `_meta()` call and merged onto the cached copy. When you add a mutation route, mirror the existing key-rewrite logic (see `rename_folder`, `delete_folder`, `move_song`) so the metadata cache stays valid.
|
||||
|
||||
## Folder Scan Logic
|
||||
|
||||
`routes.py` scans recursively starting at `<dlc>/sloppak/` (or `<dlc>/` if no `sloppak` subdir exists):
|
||||
- Files/dirs matching `.sloppak` or `.feedpak` → song entries (root-level ones go to `root_songs`, shown as "Unsorted")
|
||||
- Subdirectories → recursive folder nodes with their own `songs` + `children`
|
||||
- Dot-prefixed entries are skipped; empty folders are still included (shown with a 0 count)
|
||||
|
||||
To add more grouping options (by artist, album, etc.), build an alternative projection over the scanned songs rather than the on-disk tree.
|
||||
|
||||
## Library provider (future, not implemented)
|
||||
|
||||
This plugin surfaces folders as a dedicated **view** over the existing library;
|
||||
it does not (yet) register itself as a selectable library **source/provider**.
|
||||
If you want a "Folders" entry to appear in the host's main library-source
|
||||
picker (mapping top-level folder → "artist", subfolder → "album"), implement a
|
||||
provider exposing the source-aware contract (`query_page`, `query_artists`,
|
||||
`query_stats`, `tuning_names`) and register it in `setup()` via
|
||||
`context["register_library_provider"](...)`, unregistering on teardown. (An
|
||||
earlier inert `FolderLibraryProvider` scaffold was removed — it was never wired
|
||||
and only duplicated the scan logic; re-add it only alongside real registration
|
||||
and tests.)
|
||||
|
||||
## View Modes (List / Grid)
|
||||
|
||||
The toolbar has a list/grid toggle. Current view is stored in `localStorage` under `fo:view` (`'list'` or `'grid'`).
|
||||
|
||||
- **List view** — `_songRow()`, rendered inside a `ml-5 space-y-0` div
|
||||
- **Grid view** — `_songCard()`, rendered inside a CSS grid div (`auto-fill, minmax(150px,1fr)`)
|
||||
- Both the folder and unsorted section renderers branch on `_view` to pick the right renderer and container
|
||||
- Album art is fetched via `/api/song/<encoded-path>/art` where each path segment is individually `encodeURIComponent`-encoded. On error the `<img>` is hidden and a placeholder SVG is shown
|
||||
- The collapse/expand toggle restores `display:grid` (not just `display:''`) when reopening a folder in grid mode — always check this when changing toggle logic
|
||||
|
||||
### Lazy folder rendering
|
||||
|
||||
Folders do **not** render their song list on initial load. The folder renderer sets a `_listPopulated` flag and only populates the list the first time a folder is opened, keeping the initial render fast with large libraries. When search is active all folders are forced open and populated immediately (search overrides lazy loading).
|
||||
|
||||
## Sort System
|
||||
|
||||
The toolbar has a sort select (`#fb-sort`) and a direction toggle (`#fb-sort-dir`). State is stored under `fo:sort` and `fo:sortDir`.
|
||||
|
||||
- `_sort` — `'default' | 'title' | 'artist' | 'duration' | 'year' | 'tuning' | 'added'`
|
||||
- `_sortDir` — `'asc' | 'desc'`
|
||||
- `_sortSongs(songs)` returns a sorted copy; direction is applied by reversing after sort. Returns the array unchanged when `_sort === 'default'`.
|
||||
- The sort direction button is dimmed (`opacity: 0.35`) and non-interactive when sort is `'default'`.
|
||||
|
||||
## Filter System
|
||||
|
||||
Client-side filters are stored under `fo:filters` as a JSON object. (The server `/tree` endpoint can also filter — see Backend Routes — used to sync with the host library.)
|
||||
|
||||
### Filter state shape
|
||||
|
||||
```js
|
||||
_filters = {
|
||||
arrangements: { Lead: 'on', Bass: 'exclude', Rhythm: 'off' },
|
||||
stems: { Drums: 'off' },
|
||||
lyrics: 'off', // 'off' | 'on' | 'exclude'
|
||||
tunings: ['E Standard', 'Eb Standard'],
|
||||
}
|
||||
```
|
||||
|
||||
Each arrangement/stem value is `'off' | 'on' | 'exclude'`.
|
||||
|
||||
### Include vs exclude logic
|
||||
|
||||
`_matchFilters(song)` uses **OR logic for includes, AND logic for excludes**:
|
||||
|
||||
- **Include (`'on'`)** — song passes if it has *at least one* selected arrangement/stem. More includes widens the result set.
|
||||
- **Exclude (`'exclude'`)** — each excluded tag independently removes songs that have it. More excludes narrows the result set.
|
||||
|
||||
This matches standard multi-select filter UX (Spotify/library style).
|
||||
|
||||
### Data-driven filter panel
|
||||
|
||||
All filter sections are built from the actual library data — nothing is hardcoded:
|
||||
|
||||
- `_getArrangements()` — unique arrangement names sorted by frequency (most common first), then alphabetically
|
||||
- `_getStems()` — same pattern for stem names
|
||||
- `_getAvailableFilters()` — returns `{ arrangements, stems, lyrics, tuning }` booleans gating the lyrics/tuning sections
|
||||
|
||||
Non-standard arrangement names (e.g. `"Bonus"`) appear as pills automatically — no constants to update. The stems section only appears if at least one song has stems data.
|
||||
|
||||
### Split pill UI
|
||||
|
||||
`_makeSplitPill(label, state, onChange)` renders a two-zone pill:
|
||||
- Left zone (label) — toggles `'off' ↔ 'on'` (include, blue)
|
||||
- Right zone (`✕`) — toggles `'off' ↔ 'exclude'` (exclude, red)
|
||||
|
||||
The filter badge (`#fb-filter-badge`) shows the active filter count via `_activeFilterCount()`.
|
||||
|
||||
## Hover Badges
|
||||
|
||||
Each song row/card has two hidden hover-reveal layers, built once and toggled via CSS `max-height` + `opacity` transitions.
|
||||
|
||||
### `_badge(text, active, type)`
|
||||
|
||||
Renders a single metadata badge. Type controls the inactive colour:
|
||||
|
||||
| type | inactive border | inactive text |
|
||||
|---|---|---|
|
||||
| `'arrangement'` | amber `#92400e` | amber `#fcd34d` |
|
||||
| `'stem'` | violet `#5b21b6` | violet `#c4b5fd` |
|
||||
| `'lyrics'` | rose `#9f1239` | rose `#fda4af` |
|
||||
| `'tuning'` | teal `#0f766e` | teal `#5eead4` |
|
||||
|
||||
Active state is always blue (`#1d4ed8` fill, `#3b82f6` border, white text) regardless of type.
|
||||
|
||||
### `_buildSongBadges(song)`
|
||||
|
||||
Builds the badge row (arrangements, stems, lyrics, tuning), deduplicating within each category. Clicking a badge toggles that filter on/off and re-renders. Returns `null` if the song has no filterable metadata.
|
||||
|
||||
### `_buildSongDateInfo(song)`
|
||||
|
||||
Builds a separate plain-text hover line showing `year · date added` (e.g. `1993 · 24 May 2026`), `#cbd5e1` text. Always shown on hover regardless of filter state.
|
||||
|
||||
### Reveal / hide
|
||||
|
||||
```js
|
||||
_revealBadges(el) // max-height:120px, opacity:1, margin-top:4px
|
||||
_hideBadges(el) // max-height:0, opacity:0, margin-top:0
|
||||
```
|
||||
|
||||
Both badge layers (badges + date-info) are wired to the same `mouseenter`/`mouseleave` events on the row or card element.
|
||||
|
||||
## Drag-and-Drop
|
||||
|
||||
Drag-and-drop uses **pointer events** (mousedown/mousemove/mouseup), not the HTML5 DnD API. HTML5 DnD blocks wheel events and gives unreliable edge positions inside Electron — pointer events give full control.
|
||||
|
||||
- `_makeDraggable(el, song, folderName)` — attaches a `mousedown` listener. A drag goes "live" only after the pointer moves more than `_DRAG_THRESH` (5 px), preventing accidental drags on clicks.
|
||||
- Once live, a ghost `div` follows the cursor. Auto-scroll activates when the pointer is within `_DRAG_ZONE` (150 px) of the viewport top/bottom.
|
||||
- `_makeDropTarget(el, targetFolder)` — sets `data-dropFolder` so an element can receive drops. Both folder headers and song-list containers are drop targets — including **nested** folders (drop onto a subfolder header moves the song there).
|
||||
- `_dragFindTarget(x, y)` — uses `document.elementsFromPoint` to find the topmost element with `data-dropFolder` under the cursor.
|
||||
- **Esc to cancel** — `_onDragKeyDown` calls `_endPointerDrag()` on `Escape`, removing the ghost and clearing state without dropping.
|
||||
- On a successful drop, `_executeDrop()` does an **optimistic UI update** (moves the song in the in-memory tree and re-renders) then calls `/song/move`. On API failure it reloads the full tree.
|
||||
- A one-time `click` capture listener after mouseup suppresses the post-drag click so it doesn't trigger playback.
|
||||
|
||||
## Modal Behaviour
|
||||
|
||||
`_showModal(msg, withInput, defaultVal)` is the custom modal used for all prompts and confirms (Electron blocks `window.prompt()` / `window.confirm()`). It returns a Promise.
|
||||
|
||||
- `_confirm(msg)` — resolves `true` on OK, `null` on cancel
|
||||
- `_prompt(msg, default)` — resolves the trimmed input string on OK, `null` on cancel
|
||||
- **Esc cancels** — resolves with `null`, same as Cancel (applies to rename, delete, create folder/subfolder, move song)
|
||||
- **Enter confirms** — submits, equivalent to OK
|
||||
|
||||
## Roadmap
|
||||
|
||||
Implemented since the original release: **nested subfolders** (recursive tree + create-inside-folder), drag-and-drop, sort, advanced filtering, server-side tree filtering synced to the host library, and the warm metadata cache.
|
||||
|
||||
Not yet implemented, in rough priority order:
|
||||
|
||||
- **Auto-play on hover** — with an on/off toggle saved to localStorage.
|
||||
- **Bulk move** — multi-select songs and move them all at once.
|
||||
- **Thumbnail performance** — faster loading and smoother scrolling with large libraries.
|
||||
- **Adjustable thumbnail/row sizes** — user-resizable song cards and list rows.
|
||||
- **Custom themes** — switchable colour schemes.
|
||||
- **Favoriting songs** — likely a new backend route plus a `fo:favorites` localStorage key.
|
||||
- **Editing song metadata** — edit title, artist, album etc. in-plugin; needs new backend write routes.
|
||||
- **Folders as a library source** — register a library provider so a "Folders" entry appears in the host's main library-source picker (see "Library provider (future)" above).
|
||||
@@ -0,0 +1,100 @@
|
||||
# Folder Library — FeedBack Plugin
|
||||
|
||||

|
||||

|
||||
|
||||
A FeedBack (fee[dB]ack) plugin that organizes your `.sloppak` / `.feedpak` DLC songs into a folder tree, grouped by the folders on disk. Browse your whole library visually with album art, nest folders as deep as you like, switch between list and grid layouts, and manage folders without ever leaving the app.
|
||||
|
||||
---
|
||||
|
||||
## Screenshots
|
||||
|
||||

|
||||
*Grid view — album art cards with title and artist*
|
||||
|
||||

|
||||
*Live search filters instantly across all folders*
|
||||
|
||||

|
||||
*List view — compact rows with album art thumbnails and duration*
|
||||
|
||||

|
||||
*Create and manage folders directly in the UI*
|
||||
|
||||
---
|
||||
|
||||
> **Status — migrating to core.** Folder Library is being reworked from a standalone plugin into a bundled core plugin, and several previously-shipped features are not currently wired up in core (see the Roadmap). The list below reflects what works today; if something here is wrong, it's because this rework is still in progress.
|
||||
|
||||
## Features
|
||||
|
||||
- **List & Grid views** — toggle between a compact list with thumbnails or a full album art card grid
|
||||
- **Album art** — pulls art automatically for every song in both views
|
||||
- **One-click playback** — click any song to start playing immediately
|
||||
- **Sort options** — sort songs by title, artist, duration, year, tuning, or recently added with an asc/desc toggle
|
||||
- **Advanced filters** — filter by arrangements, stems, lyrics, and tuning with include and exclude support
|
||||
- **Folder management** — create, rename, and delete folders without leaving the plugin
|
||||
- **Nested subfolders** — organize as deep as you want; create a subfolder inside any folder, expand/collapse a whole branch in one click
|
||||
- **Collapsible folders** — expand/collapse individual folders, plus Expand All / Collapse All
|
||||
- **Move songs** — reassign any song to a different folder on the fly; press `Esc` to cancel
|
||||
- **Drag-and-drop** — drag songs between folders (including into nested folders) with smooth auto-scroll; press `Esc` to cancel
|
||||
- **Fast with big libraries** — folder song lists render lazily and metadata is cached so reopening folders is instant
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
Folder Library ships bundled with FeedBack as a core plugin (`"bundled": true`), so there's nothing to install — the **Folders** screen appears in the navbar under **Plugins** automatically.
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
| Action | How |
|
||||
|--------|-----|
|
||||
| Switch to grid view | Click the grid icon in the toolbar |
|
||||
| Switch to list view | Click the list icon in the toolbar |
|
||||
| Play a song | Click any song row or card |
|
||||
| Sort songs | Use the sort dropdown in the toolbar |
|
||||
| Toggle sort direction | Click the arrow button next to the sort dropdown |
|
||||
| Open filters | Click the filter icon in the toolbar |
|
||||
| Filter by arrangement/stem | Open filters → click a pill to include; click `✕` to exclude |
|
||||
| Clear all filters | Open filters → click "Clear all" |
|
||||
| Create a folder | Click the folder+ icon in the toolbar |
|
||||
| Create a subfolder | Hover a folder header → click the new-subfolder icon |
|
||||
| Rename a folder | Hover the folder header → click the pencil icon |
|
||||
| Delete a folder | Hover the folder header → click the trash icon (songs move up to Unsorted) |
|
||||
| Move a song | Hover the song row → click the folder icon |
|
||||
| Drag a song to a folder | Click and hold a song → drag to a folder header or body (nested folders work too) |
|
||||
| Cancel a drag | Press `Esc` while holding a song |
|
||||
| Cancel a move dialog | Press `Esc` in the move prompt |
|
||||
| Expand / collapse a folder | Click the folder header |
|
||||
| Expand / collapse all subfolders | Use the expand/collapse-children buttons on a folder with subfolders |
|
||||
|
||||
---
|
||||
|
||||
## Changelog
|
||||
|
||||
Folder Library started life as a standalone plugin with its own version line, but it's now a **bundled core plugin** that ships with FeedBack. Its changes are tracked alongside the app in the repo-root [CHANGELOG.md](../../CHANGELOG.md), and it versions with the app rather than on its own. The **Features** section above reflects what's in the current build.
|
||||
|
||||
---
|
||||
|
||||
## Roadmap
|
||||
|
||||
- [ ] Auto play song on hover (with an on/off toggle)
|
||||
- [ ] Bulk move — select multiple songs and move them at once
|
||||
- [ ] Thumbnail performance — faster loading and smoother scrolling with large song libraries
|
||||
- [ ] Adjustable thumbnail and row sizes — resize song cards and list rows to suit your preference
|
||||
- [ ] Custom themes — switch between colour schemes to match your style
|
||||
- [ ] Favoriting songs
|
||||
- [ ] Editing song metadata
|
||||
|
||||
---
|
||||
|
||||
## Contributing
|
||||
|
||||
Pull requests are welcome. For major changes please open an issue first to discuss what you'd like to change.
|
||||
|
||||
1. Fork the repo
|
||||
2. Create a feature branch (`git checkout -b feature/your-feature`)
|
||||
3. Commit your changes
|
||||
4. Push to the branch and open a pull request
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"id": "folder_library",
|
||||
"name": "Folder Library",
|
||||
"version": "1.8.0",
|
||||
"bundled": true,
|
||||
"nav": { "label": "Folders", "screen": "plugin-folder_library" },
|
||||
"screen": "screen.html",
|
||||
"script": "screen.js",
|
||||
"routes": "routes.py"
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
"""
|
||||
Folder Library plugin — routes.py
|
||||
|
||||
Surfaces the DLC folder structure as a navigable tree and provides in-app
|
||||
folder management (create / rename / delete) and song moves. Every filesystem
|
||||
mutation is confined to DLC_DIR and validated against path traversal.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
import shutil
|
||||
import re
|
||||
|
||||
|
||||
# ── Pure, testable helpers ─────────────────────────────────────────────────
|
||||
|
||||
_UNSAFE_NAME_RE = re.compile(r'[\\/:*?"<>|]')
|
||||
|
||||
|
||||
def _safe_name(name: str) -> bool:
|
||||
"""A single path segment is safe: no separators, no traversal dot-names,
|
||||
no surrounding whitespace, no characters illegal across filesystems."""
|
||||
if not name or name.strip() != name:
|
||||
return False
|
||||
if _UNSAFE_NAME_RE.search(name):
|
||||
return False
|
||||
if name in (".", ".."):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _safe_path(path_str: str) -> bool:
|
||||
"""A slash-separated path is safe iff every segment is a safe name."""
|
||||
if not path_str:
|
||||
return False
|
||||
return all(_safe_name(p) for p in path_str.split("/"))
|
||||
|
||||
|
||||
def _is_within(root: Path, candidate: Path) -> bool:
|
||||
"""True iff ``candidate`` resolves to a location inside ``root`` (after
|
||||
normalising ``..`` and symlinks). Containment backstop for file moves so a
|
||||
crafted filename can't escape DLC_DIR even past the segment validator."""
|
||||
try:
|
||||
candidate.resolve().relative_to(root.resolve())
|
||||
return True
|
||||
except (ValueError, OSError):
|
||||
return False
|
||||
|
||||
|
||||
def _path_to_dir(root: Path, folder_path: str) -> Path:
|
||||
"""Resolve a slash-separated folder path relative to ``root``."""
|
||||
result = root
|
||||
for part in folder_path.split("/"):
|
||||
result = result / part
|
||||
return result
|
||||
|
||||
|
||||
def _load_is_loose_song():
|
||||
"""The host's authoritative loose-folder predicate (lib/loosefolder.py),
|
||||
imported lazily so the plugin still loads if it's ever unavailable. A
|
||||
loose-folder song is a directory carrying audio + an arrangement XML rather
|
||||
than a ``.sloppak`` bundle, so the plain suffix check below misses it."""
|
||||
try:
|
||||
from loosefolder import is_loose_song
|
||||
return is_loose_song
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
_IS_LOOSE_SONG = _load_is_loose_song()
|
||||
|
||||
|
||||
def _is_song(p: Path) -> bool:
|
||||
"""A song carrier is a ``.sloppak`` / ``.feedpak`` file or directory-form
|
||||
bundle (extension on the leaf name), or a host-recognised loose-folder song
|
||||
directory — so loose-folder charts surface in the tree like any other song
|
||||
instead of being walked into as if they were ordinary folders."""
|
||||
if p.suffix.lower() in (".sloppak", ".feedpak"):
|
||||
return True
|
||||
if _IS_LOOSE_SONG is not None and p.is_dir():
|
||||
try:
|
||||
return bool(_IS_LOOSE_SONG(p))
|
||||
except Exception:
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
def setup(app, context):
|
||||
log = context["log"]
|
||||
router = APIRouter(prefix="/api/plugins/folder_library")
|
||||
|
||||
# ── Two-level cache ────────────────────────────────────────────────
|
||||
# _meta_cache — expensive extract_meta() results keyed by abs path
|
||||
# (as_posix() string). Never cleared; keys are updated
|
||||
# in-place when files are moved so the data stays valid.
|
||||
# _cache — tree structure ("folders" / "root_songs"). Cleared on
|
||||
# every mutation so the next /tree request rebuilds it —
|
||||
# but that rebuild is now fast because _meta_cache is warm.
|
||||
_cache = {} # "tree" → JSONResponse-ready dict
|
||||
_meta_cache = {} # abs_posix_path → extracted meta (no filename/added)
|
||||
|
||||
def _invalidate():
|
||||
"""Clear the tree structure cache only. _meta_cache is preserved."""
|
||||
_cache.clear()
|
||||
|
||||
def _dlc_root() -> Path | None:
|
||||
try:
|
||||
return Path(context["get_dlc_dir"]())
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def _scan_root(dlc: Path) -> Path:
|
||||
sloppak = dlc / "sloppak"
|
||||
return sloppak if sloppak.exists() else dlc
|
||||
|
||||
def _meta(p: Path, dlc: Path) -> dict:
|
||||
# filename and added are always computed fresh — they change when files move.
|
||||
try:
|
||||
filename = "/".join(p.relative_to(dlc).parts)
|
||||
except ValueError:
|
||||
filename = p.name
|
||||
added = None
|
||||
try:
|
||||
added = p.stat().st_mtime
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Return cached extracted metadata if available.
|
||||
cache_key = p.as_posix()
|
||||
if cache_key in _meta_cache:
|
||||
m = dict(_meta_cache[cache_key]) # shallow copy
|
||||
m["filename"] = filename
|
||||
m["added"] = added
|
||||
return m
|
||||
|
||||
# Cache miss — run the expensive extract.
|
||||
m = {"title": None, "artist": None, "album": None, "duration": None,
|
||||
"year": None, "tuning": None, "arrangements": [], "stems": [], "lyrics": False}
|
||||
try:
|
||||
raw = context["extract_meta"](p)
|
||||
if raw:
|
||||
m["title"] = raw.get("title") or raw.get("name")
|
||||
m["artist"] = raw.get("artist") or raw.get("artistName")
|
||||
m["album"] = raw.get("album") or raw.get("albumName")
|
||||
m["duration"] = raw.get("duration")
|
||||
m["year"] = raw.get("year")
|
||||
m["tuning"] = raw.get("tuning")
|
||||
|
||||
# arrangements — objects with a "name" key e.g. [{name:"Lead",...}, ...]
|
||||
raw_arr = raw.get("arrangements") or []
|
||||
if isinstance(raw_arr, (list, tuple)):
|
||||
m["arrangements"] = [
|
||||
a["name"] if isinstance(a, dict) else str(a)
|
||||
for a in raw_arr
|
||||
if (isinstance(a, dict) and "name" in a) or isinstance(a, str)
|
||||
]
|
||||
|
||||
# stems — may also be objects with a "name" key, same as arrangements
|
||||
raw_stems = raw.get("stems") or []
|
||||
for _key in ("stems", "stem_types", "available_stems", "stemTypes"):
|
||||
_v = raw.get(_key)
|
||||
if _v:
|
||||
raw_stems = _v
|
||||
break
|
||||
if isinstance(raw_stems, (list, tuple)):
|
||||
m["stems"] = [
|
||||
a["name"] if isinstance(a, dict) else str(a)
|
||||
for a in raw_stems
|
||||
if (isinstance(a, dict) and "name" in a) or isinstance(a, str)
|
||||
]
|
||||
|
||||
# lyrics — try common key variants
|
||||
for _key in ("lyrics", "hasLyrics", "has_lyrics", "lyric", "hasLyric"):
|
||||
_val = raw.get(_key)
|
||||
if _val is not None:
|
||||
if isinstance(_val, str):
|
||||
m["lyrics"] = _val.lower() not in ("", "false", "no", "0")
|
||||
else:
|
||||
m["lyrics"] = bool(_val)
|
||||
break
|
||||
except Exception as exc:
|
||||
log.debug("meta failed for %s: %s", p.name, exc)
|
||||
if not m["title"]:
|
||||
m["title"] = p.stem
|
||||
|
||||
_meta_cache[cache_key] = m # store without filename/added
|
||||
result = dict(m)
|
||||
result["filename"] = filename
|
||||
result["added"] = added
|
||||
return result
|
||||
|
||||
def _scan_dir(path: Path, root: Path, dlc: Path) -> dict:
|
||||
"""Recursively scan a directory and return a folder node."""
|
||||
songs = []
|
||||
children = []
|
||||
try:
|
||||
for entry in sorted(path.iterdir(), key=lambda p: p.name.lower()):
|
||||
if entry.name.startswith("."):
|
||||
continue
|
||||
if _is_song(entry):
|
||||
songs.append(_meta(entry, dlc))
|
||||
elif entry.is_dir():
|
||||
children.append(_scan_dir(entry, root, dlc))
|
||||
except PermissionError:
|
||||
log.warning("permission denied: %s", path)
|
||||
try:
|
||||
rel = path.relative_to(root)
|
||||
folder_path = "/".join(rel.parts)
|
||||
except ValueError:
|
||||
folder_path = path.name
|
||||
return {
|
||||
"name": path.name,
|
||||
"path": folder_path,
|
||||
"songs": songs,
|
||||
"children": children,
|
||||
}
|
||||
|
||||
def _apply_tree_filters(tree, arrangements_has="", arrangements_lacks="",
|
||||
stems_has="", stems_lacks="", has_lyrics="", tunings=""):
|
||||
"""Filter a cached tree dict by arrangement/stem/lyrics/tuning params.
|
||||
The cache always holds the full unfiltered tree; this is applied per-request."""
|
||||
def _split(s):
|
||||
return [x.strip().lower() for x in s.split(",") if x.strip()] if s else []
|
||||
|
||||
arr_has = _split(arrangements_has)
|
||||
arr_lacks = _split(arrangements_lacks)
|
||||
st_has = _split(stems_has)
|
||||
st_lacks = _split(stems_lacks)
|
||||
tun_set = set(_split(tunings))
|
||||
lyr = None if has_lyrics == "" else (has_lyrics == "1")
|
||||
|
||||
if not any([arr_has, arr_lacks, st_has, st_lacks, tun_set, lyr is not None]):
|
||||
return tree # no filters active — return as-is
|
||||
|
||||
def _song_ok(s):
|
||||
arrs = [a.lower() for a in (s.get("arrangements") or [])]
|
||||
stms = [x.lower() for x in (s.get("stems") or [])]
|
||||
if arr_has and not any(a in arrs for a in arr_has): return False
|
||||
if arr_lacks and any(a in arrs for a in arr_lacks): return False
|
||||
if st_has and not any(x in stms for x in st_has): return False
|
||||
if st_lacks and any(x in stms for x in st_lacks): return False
|
||||
if lyr is not None and bool(s.get("lyrics")) != lyr: return False
|
||||
if tun_set and (s.get("tuning") or "").lower() not in tun_set: return False
|
||||
return True
|
||||
|
||||
def _filter_node(node):
|
||||
return {
|
||||
"name": node["name"],
|
||||
"path": node["path"],
|
||||
"songs": [s for s in node["songs"] if _song_ok(s)],
|
||||
"children": [_filter_node(c) for c in node.get("children", [])],
|
||||
}
|
||||
|
||||
return {
|
||||
"folders": [_filter_node(f) for f in tree["folders"]],
|
||||
"root_songs": [s for s in tree["root_songs"] if _song_ok(s)],
|
||||
}
|
||||
|
||||
@router.get("/tree")
|
||||
def get_tree(
|
||||
arrangements_has: str = "",
|
||||
arrangements_lacks: str = "",
|
||||
stems_has: str = "",
|
||||
stems_lacks: str = "",
|
||||
has_lyrics: str = "",
|
||||
tunings: str = "",
|
||||
):
|
||||
if "tree" not in _cache:
|
||||
dlc = _dlc_root()
|
||||
if not dlc or not dlc.exists():
|
||||
return JSONResponse({"folders": [], "root_songs": [],
|
||||
"error": "DLC directory not found"})
|
||||
root = _scan_root(dlc)
|
||||
log.info("folder_library: scanning %s", root)
|
||||
folders = []
|
||||
root_songs = []
|
||||
try:
|
||||
for entry in sorted(root.iterdir(), key=lambda p: p.name.lower()):
|
||||
if entry.name.startswith("."):
|
||||
continue
|
||||
if _is_song(entry):
|
||||
root_songs.append(_meta(entry, dlc))
|
||||
elif entry.is_dir():
|
||||
folders.append(_scan_dir(entry, root, dlc))
|
||||
except PermissionError:
|
||||
return JSONResponse({"folders": [], "root_songs": [],
|
||||
"error": "Permission denied"})
|
||||
_cache["tree"] = {"folders": folders, "root_songs": root_songs}
|
||||
|
||||
result = _apply_tree_filters(
|
||||
_cache["tree"], arrangements_has, arrangements_lacks,
|
||||
stems_has, stems_lacks, has_lyrics, tunings,
|
||||
)
|
||||
return JSONResponse(result)
|
||||
|
||||
@router.post("/folder/create")
|
||||
async def create_folder(request: Request):
|
||||
body = await request.json()
|
||||
name = (body.get("name") or "").strip()
|
||||
parent = (body.get("parent") or "").strip()
|
||||
if not _safe_name(name):
|
||||
return JSONResponse({"error": "Invalid folder name"}, status_code=400)
|
||||
if parent and not _safe_path(parent):
|
||||
return JSONResponse({"error": "Invalid parent path"}, status_code=400)
|
||||
dlc = _dlc_root()
|
||||
if not dlc:
|
||||
return JSONResponse({"error": "DLC dir not found"}, status_code=500)
|
||||
root = _scan_root(dlc)
|
||||
parent_dir = _path_to_dir(root, parent) if parent else root
|
||||
if parent and not parent_dir.exists():
|
||||
return JSONResponse({"error": "Parent folder not found"}, status_code=404)
|
||||
target = parent_dir / name
|
||||
if target.exists():
|
||||
return JSONResponse({"error": "Folder already exists"}, status_code=400)
|
||||
try:
|
||||
target.mkdir(parents=False)
|
||||
_invalidate()
|
||||
return JSONResponse({"ok": True})
|
||||
except Exception as e:
|
||||
return JSONResponse({"error": str(e)}, status_code=500)
|
||||
|
||||
@router.post("/folder/rename")
|
||||
async def rename_folder(request: Request):
|
||||
body = await request.json()
|
||||
old = (body.get("old") or "").strip()
|
||||
new = (body.get("new") or "").strip()
|
||||
if not _safe_path(old) or not _safe_name(new):
|
||||
return JSONResponse({"error": "Invalid folder name"}, status_code=400)
|
||||
dlc = _dlc_root()
|
||||
if not dlc:
|
||||
return JSONResponse({"error": "DLC dir not found"}, status_code=500)
|
||||
root = _scan_root(dlc)
|
||||
src = _path_to_dir(root, old)
|
||||
dst = src.parent / new # rename within the same parent
|
||||
if not src.exists():
|
||||
return JSONResponse({"error": "Folder not found"}, status_code=404)
|
||||
if dst.exists():
|
||||
return JSONResponse({"error": "Name already taken"}, status_code=400)
|
||||
try:
|
||||
# Pre-compute meta cache key updates (keys change because the
|
||||
# folder path changes — all files under src get a new prefix).
|
||||
old_prefix = src.as_posix() + "/"
|
||||
new_prefix = dst.as_posix() + "/"
|
||||
meta_updates = {
|
||||
key: new_prefix + key[len(old_prefix):]
|
||||
for key in list(_meta_cache)
|
||||
if key.startswith(old_prefix)
|
||||
}
|
||||
src.rename(dst)
|
||||
_invalidate()
|
||||
for old_key, new_key in meta_updates.items():
|
||||
if old_key in _meta_cache:
|
||||
_meta_cache[new_key] = _meta_cache.pop(old_key)
|
||||
return JSONResponse({"ok": True})
|
||||
except Exception as e:
|
||||
return JSONResponse({"error": str(e)}, status_code=500)
|
||||
|
||||
@router.post("/folder/delete")
|
||||
async def delete_folder(request: Request):
|
||||
body = await request.json()
|
||||
name = (body.get("name") or "").strip()
|
||||
if not _safe_path(name):
|
||||
return JSONResponse({"error": "Invalid folder path"}, status_code=400)
|
||||
dlc = _dlc_root()
|
||||
if not dlc:
|
||||
return JSONResponse({"error": "DLC dir not found"}, status_code=500)
|
||||
root = _scan_root(dlc)
|
||||
target = _path_to_dir(root, name)
|
||||
if not target.exists():
|
||||
return JSONResponse({"error": "Folder not found"}, status_code=404)
|
||||
try:
|
||||
# Relocate every song (at any depth) up to the scan root BEFORE
|
||||
# removing the folder. Colliding filenames are de-duplicated so a
|
||||
# name clash never leaves a song behind to be destroyed by rmtree
|
||||
# (the folder is advertised as "moves its songs to Unsorted").
|
||||
for song_path in sorted(target.rglob("*")):
|
||||
if not song_path.exists():
|
||||
continue # a parent song-dir was already relocated
|
||||
if not _is_song(song_path):
|
||||
continue
|
||||
old_key = song_path.as_posix()
|
||||
dest = root / song_path.name
|
||||
if dest.exists():
|
||||
stem, suffix = song_path.stem, song_path.suffix
|
||||
n = 1
|
||||
while dest.exists():
|
||||
dest = root / f"{stem} ({n}){suffix}"
|
||||
n += 1
|
||||
song_path.rename(dest)
|
||||
if old_key in _meta_cache:
|
||||
_meta_cache[dest.as_posix()] = _meta_cache.pop(old_key)
|
||||
shutil.rmtree(target)
|
||||
_invalidate()
|
||||
return JSONResponse({"ok": True})
|
||||
except Exception as e:
|
||||
return JSONResponse({"error": str(e)}, status_code=500)
|
||||
|
||||
@router.post("/song/move")
|
||||
async def move_song(request: Request):
|
||||
body = await request.json()
|
||||
filename = (body.get("filename") or "").strip()
|
||||
dest_folder = (body.get("folder") or "").strip()
|
||||
# Validate the source path like the folder ops, AND confirm it resolves
|
||||
# inside DLC_DIR — without this a filename such as "../../etc/passwd"
|
||||
# would be renamed (moved) into the served library and become readable.
|
||||
if not filename or not _safe_path(filename):
|
||||
return JSONResponse({"error": "Invalid filename"}, status_code=400)
|
||||
dlc = _dlc_root()
|
||||
if not dlc:
|
||||
return JSONResponse({"error": "DLC dir not found"}, status_code=500)
|
||||
src = dlc / Path(*filename.split("/"))
|
||||
if not _is_within(dlc, src):
|
||||
return JSONResponse({"error": "Invalid filename"}, status_code=400)
|
||||
if not src.exists():
|
||||
return JSONResponse({"error": "Song not found"}, status_code=404)
|
||||
root = _scan_root(dlc)
|
||||
if dest_folder:
|
||||
if not _safe_path(dest_folder):
|
||||
return JSONResponse({"error": "Invalid folder path"}, status_code=400)
|
||||
dst_dir = _path_to_dir(root, dest_folder)
|
||||
if not dst_dir.exists():
|
||||
return JSONResponse({"error": "Destination folder not found"}, status_code=404)
|
||||
else:
|
||||
dst_dir = root
|
||||
dst = dst_dir / src.name
|
||||
if dst.exists():
|
||||
return JSONResponse({"error": "File already exists at destination"}, status_code=400)
|
||||
try:
|
||||
old_key = src.as_posix()
|
||||
src.rename(dst)
|
||||
if old_key in _meta_cache:
|
||||
_meta_cache[dst.as_posix()] = _meta_cache.pop(old_key)
|
||||
_invalidate()
|
||||
return JSONResponse({"ok": True})
|
||||
except Exception as e:
|
||||
return JSONResponse({"error": str(e)}, status_code=500)
|
||||
|
||||
app.include_router(router)
|
||||
log.info("folder_library routes registered")
|
||||
@@ -0,0 +1,159 @@
|
||||
<!-- Folder Browser — screen.html
|
||||
Slopsmith injects this into a div#plugin-folder_library.screen automatically.
|
||||
Do NOT add an outer wrapper div with class="screen". -->
|
||||
|
||||
<!-- ── toolbar ──────────────────────────────────────────────────────── -->
|
||||
<div class="flex items-center gap-2 px-4 py-3 border-b border-dark-400 flex-wrap"
|
||||
style="position:fixed; top:64px; left:0; right:0; z-index:40; background-color:#0f1117; border-bottom: 1px solid #1f2937;">
|
||||
|
||||
<h2 class="text-base font-semibold text-white mr-1">Folders</h2>
|
||||
|
||||
<!-- search -->
|
||||
<div class="relative flex-1 min-w-40 max-w-xs">
|
||||
<svg class="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-500 pointer-events-none"
|
||||
viewBox="0 0 20 20" fill="currentColor">
|
||||
<path fill-rule="evenodd"
|
||||
d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z"
|
||||
clip-rule="evenodd"/>
|
||||
</svg>
|
||||
<input id="fb-search" type="text" placeholder="Search songs…"
|
||||
class="w-full pl-8 pr-3 py-1.5 rounded bg-dark-500 border border-dark-400
|
||||
text-sm text-gray-200 placeholder-gray-500
|
||||
focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500"/>
|
||||
</div>
|
||||
|
||||
<!-- new folder -->
|
||||
<button id="fb-new-folder" title="New parent folder"
|
||||
class="p-1.5 rounded text-gray-400 hover:text-white hover:bg-dark-400 transition-colors">
|
||||
<svg viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4">
|
||||
<path d="M2 6a2 2 0 012-2h5l2 2h5a2 2 0 012 2v6a2 2 0 01-2 2H4a2 2 0 01-2-2V6z"/>
|
||||
<path fill-rule="evenodd" d="M10 9a1 1 0 011 1v1h1a1 1 0 110 2h-1v1a1 1 0 11-2 0v-1H8a1 1 0 110-2h1v-1a1 1 0 011-1z" clip-rule="evenodd"/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<!-- expand all -->
|
||||
<button id="fb-expand-all" title="Expand all"
|
||||
class="p-1.5 rounded text-gray-400 hover:text-white hover:bg-dark-400 transition-colors">
|
||||
<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.8"
|
||||
stroke-linecap="round" class="w-4 h-4">
|
||||
<path d="M5 8l5 5 5-5"/>
|
||||
<path d="M5 4l5 5 5-5" opacity=".4"/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<!-- collapse all -->
|
||||
<button id="fb-collapse-all" title="Collapse all"
|
||||
class="p-1.5 rounded text-gray-400 hover:text-white hover:bg-dark-400 transition-colors">
|
||||
<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.8"
|
||||
stroke-linecap="round" class="w-4 h-4">
|
||||
<path d="M5 12l5-5 5 5"/>
|
||||
<path d="M5 16l5-5 5 5" opacity=".4"/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<!-- sort -->
|
||||
<select id="fb-sort" title="Sort songs within folders"
|
||||
style="padding:4px 8px; border-radius:6px; border:1px solid #374151;
|
||||
background:#1f2937; color:#d1d5db; font-size:12px; cursor:pointer; outline:none;">
|
||||
<option value="default">Default</option>
|
||||
<option value="title">Title</option>
|
||||
<option value="artist">Artist</option>
|
||||
<option value="duration">Duration</option>
|
||||
<option value="year">Year</option>
|
||||
<option value="tuning">Tuning</option>
|
||||
<option value="added">Recently Added</option>
|
||||
</select>
|
||||
|
||||
<!-- sort direction -->
|
||||
<button id="fb-sort-dir" title="Ascending"
|
||||
class="p-1.5 rounded text-gray-400 hover:text-white hover:bg-dark-400 transition-colors">
|
||||
<svg id="fb-sort-dir-icon" viewBox="0 0 20 20" fill="none" stroke="currentColor"
|
||||
stroke-width="1.8" stroke-linecap="round" class="w-4 h-4">
|
||||
<path d="M5 12l5-5 5 5"/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<!-- view toggle -->
|
||||
<button id="fb-view-list" title="List view"
|
||||
class="p-1.5 rounded text-gray-400 hover:text-white hover:bg-dark-400 transition-colors">
|
||||
<svg viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4">
|
||||
<path fill-rule="evenodd"
|
||||
d="M3 4a1 1 0 000 2h14a1 1 0 100-2H3zm0 4a1 1 0 000 2h14a1 1 0 100-2H3zm0 4a1 1 0 000 2h14a1 1 0 100-2H3z"
|
||||
clip-rule="evenodd"/>
|
||||
</svg>
|
||||
</button>
|
||||
<button id="fb-view-grid" title="Grid view"
|
||||
class="p-1.5 rounded text-gray-400 hover:text-white hover:bg-dark-400 transition-colors">
|
||||
<svg viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4">
|
||||
<path d="M5 3a2 2 0 00-2 2v2a2 2 0 002 2h2a2 2 0 002-2V5a2 2 0 00-2-2H5zM5 11a2 2 0 00-2 2v2a2 2 0 002 2h2a2 2 0 002-2v-2a2 2 0 00-2-2H5zM11 5a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V5zM11 13a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<!-- filters -->
|
||||
<button id="fb-filter" title="Filters"
|
||||
class="p-1.5 rounded text-gray-400 hover:text-white hover:bg-dark-400 transition-colors"
|
||||
style="position:relative;">
|
||||
<svg viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4">
|
||||
<path fill-rule="evenodd"
|
||||
d="M3 3a1 1 0 011-1h12a1 1 0 011 1v3a1 1 0 01-.293.707L12 11.414V15a1 1 0 01-.293.707l-2 2A1 1 0 018 17v-5.586L3.293 6.707A1 1 0 013 6V3z"
|
||||
clip-rule="evenodd"/>
|
||||
</svg>
|
||||
<span id="fb-filter-badge"
|
||||
style="display:none; position:absolute; top:-2px; right:-2px; min-width:14px; height:14px;
|
||||
padding:0 3px; border-radius:7px; background:#3b82f6; color:#fff;
|
||||
font-size:9px; font-weight:700; line-height:14px; text-align:center;
|
||||
box-sizing:border-box;"></span>
|
||||
</button>
|
||||
|
||||
<!-- reload -->
|
||||
<button id="fb-reload" title="Reload"
|
||||
class="p-1.5 rounded text-gray-400 hover:text-white hover:bg-dark-400 transition-colors">
|
||||
<svg viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4">
|
||||
<path fill-rule="evenodd"
|
||||
d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z"
|
||||
clip-rule="evenodd"/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<span id="fb-status" class="text-xs text-gray-500 ml-1"></span>
|
||||
</div>
|
||||
|
||||
<!-- ── tree ─────────────────────────────────────────────────────────── -->
|
||||
<div id="fb-tree" class="px-2 py-2" style="padding-top: 120px;"></div>
|
||||
|
||||
<!-- ── filter backdrop ───────────────────────────────────────────────── -->
|
||||
<div id="fb-filter-backdrop"
|
||||
style="display:none; position:fixed; inset:0; z-index:44;"></div>
|
||||
|
||||
<!-- ── filter panel ──────────────────────────────────────────────────── -->
|
||||
<div id="fb-filter-panel"
|
||||
style="display:none; position:fixed; top:64px; right:0; bottom:0; width:300px;
|
||||
z-index:45; background:#0f1117; border-left:1px solid #1f2937;
|
||||
flex-direction:column; overflow:hidden;"></div>
|
||||
|
||||
<!-- ── custom modal ──────────────────────────────────────────────────── -->
|
||||
<div id="fb-modal" style="display:none; position:fixed; inset:0; z-index:9999;
|
||||
background:rgba(0,0,0,0.6); align-items:center; justify-content:center;">
|
||||
<div style="background:#1e2130; border:1px solid #374151; border-radius:8px;
|
||||
padding:24px; width:360px; max-width:90vw; box-shadow:0 20px 60px rgba(0,0,0,0.5);">
|
||||
<p id="fb-modal-msg" style="color:#e5e7eb; font-size:14px; margin:0 0 16px 0;
|
||||
white-space:pre-wrap; line-height:1.5;"></p>
|
||||
<input id="fb-modal-input" type="text"
|
||||
style="display:none; width:100%; box-sizing:border-box; padding:8px 12px;
|
||||
background:#111827; border:1px solid #374151; border-radius:6px;
|
||||
color:#e5e7eb; font-size:14px; outline:none; margin-bottom:16px;"
|
||||
placeholder=""/>
|
||||
<div style="display:flex; gap:8px; justify-content:flex-end;">
|
||||
<button id="fb-modal-cancel"
|
||||
style="padding:6px 16px; border-radius:6px; border:1px solid #374151;
|
||||
background:transparent; color:#9ca3af; font-size:13px; cursor:pointer;">
|
||||
Cancel
|
||||
</button>
|
||||
<button id="fb-modal-ok"
|
||||
style="padding:6px 16px; border-radius:6px; border:none;
|
||||
background:#3b82f6; color:#fff; font-size:13px; cursor:pointer; font-weight:500;">
|
||||
OK
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user