Implemented drag to import

This commit is contained in:
patben8 committed 2026-10-13 17:42:24 +02:00
1 parent 87cbd3720e
commit a65ef959b2
14 files changed
+807 -114

No files matched your search

+102 -6
View File
@@ -14,7 +14,9 @@ This is opened by the folder routes and nothing else.
Three rules:
* **This folder only.** Subfolders are not scanned — the tree is how you get to
them — so a click on a drive root never walks the whole drive.
them — so a click on a drive root never walks the whole drive. A folder
DROPPED onto the window is the exception (`FolderScanner.dropped`): the user
asked for everything in it, so it recurses, capped at `MAX_DROPPED`.
* **A track id is the file's absolute path.** It is the one identity a loose
file has, and it is what the audio route checks a request against.
* **Tags are read once per folder state.** Reading tags opens every file, which
@@ -26,6 +28,7 @@ from __future__ import annotations
import logging
import os
import threading
from dataclasses import dataclass, field
from pathlib import Path
from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities
@@ -165,17 +168,88 @@ class FolderSource:
return capabilities_for(self.path)
# A drop of a whole drive must not read tags for hours: past this many audio
# files the rest are left out and the answer says so.
MAX_DROPPED = 20_000
@dataclass
class Dropped:
"""What a drop onto the window resolved to."""
tracks: list[Track] = field(default_factory=list)
# Dropped FILES that are not audio this library can hold (or are gone).
# Non-audio inside a dropped folder is not counted: an album folder's
# cover and cue sheet are not something the user asked to add.
skipped: int = 0
# More than MAX_DROPPED audio files: the rest were left out.
truncated: bool = False
class FolderScanner:
"""Scans folders on request, caching each until its contents change.
Also the gatekeeper for streaming: `source_for_file` answers only for a file
found by a scan, so the audio route cannot be used to read an arbitrary path
off the disk — only audio the user has browsed to.
found by a scan — or dropped onto the window by the user — so the audio
route cannot be used to read an arbitrary path off the disk, only audio the
user has browsed to or handed over.
"""
def __init__(self) -> None:
self._lock = threading.Lock()
self._cache: dict[str, tuple[float, tuple[str, ...], FolderSource]] = {}
# Files dropped one by one: their folder was never scanned (and is not
# cached as if it had been — a partial listing would hide its other
# files from the sidebar), so each is held on its own.
self._files: dict[str, Track] = {}
def dropped(self, paths: list[str], formats: list[str], limit: int = MAX_DROPPED) -> Dropped:
"""Resolve paths dropped onto the window: folders RECURSIVELY (hidden
and OS-housekeeping folders left out, as the tree leaves them out),
files as themselves. Every audio file found becomes addable and
playable through the folder routes, exactly as if it had been browsed."""
wanted = {f.lower() for f in formats}
out = Dropped()
seen: set[str] = set()
def take(tracks: list[Track]) -> bool:
for t in tracks:
if t.id in seen:
continue
if len(out.tracks) >= limit:
out.truncated = True
return False
seen.add(t.id)
out.tracks.append(t)
return True
for raw in paths:
path = Path(raw).expanduser()
if path.is_dir():
for folder in _walk(path):
if not audio_files(folder, formats):
continue
if not take(self.scan(folder, formats).tracks):
return out
elif path.is_file() and path.suffix.lower() in wanted and not is_hidden(path):
track = self._file_track(path)
if not take([track]):
return out
else:
out.skipped += 1
return out
def _file_track(self, path: Path) -> Track:
key = str(path)
with self._lock:
hit = self._cache.get(str(path.parent))
known = hit[2].track(key) if hit is not None else None
if known is not None:
return known
track = read_track(path)
with self._lock:
self._files[key] = track
return track
def scan(self, folder: Path, formats: list[str]) -> FolderSource:
folder = Path(folder)
@@ -198,10 +272,32 @@ class FolderScanner:
folder = str(Path(track_id).parent)
with self._lock:
hit = self._cache.get(folder)
if hit is None or hit[2].track(track_id) is None:
return None
return hit[2]
loose = self._files.get(track_id)
if hit is not None and hit[2].track(track_id) is not None:
return hit[2]
if loose is not None:
return FolderSource(Path(folder), [loose])
return None
def clear(self) -> None:
with self._lock:
self._cache.clear()
self._files.clear()
def _walk(root: Path):
"""`root` and every visible folder under it, depth first, sorted by name."""
yield root
try:
with os.scandir(root) as it:
subs = []
for entry in it:
try:
if entry.is_dir(follow_symlinks=False) and not is_hidden(entry):
subs.append(Path(entry.path))
except OSError:
continue
except OSError:
return
for sub in sorted(subs, key=lambda p: p.name.lower()):
yield from _walk(sub)
+36 -2
View File
@@ -69,6 +69,8 @@ from .schemas import (
ExportSetOut,
ExportPreview,
Drive,
DroppedFiles,
DroppedPaths,
FolderAddRequest,
FolderTracks,
FsEntry,
@@ -2321,6 +2323,18 @@ def folder_tracks(path: str) -> FolderTracks:
)
@app.post("/api/folder/dropped", response_model=DroppedFiles)
def folder_dropped(body: DroppedPaths) -> DroppedFiles:
"""Files and folders dropped onto the window. Folders are searched all the
way down; every audio file found is then addable and playable through the
folder routes, as if it had been browsed to in the sidebar."""
dest = require_adapter()
dropped = FOLDERS.dropped(body.paths, _formats())
held = importer._existing_files(dest)
rows, files = _folder_rows(dest, dropped.tracks, lambda t: held.get(importer._key(Path(t.id))))
return DroppedFiles(tracks=rows, files=files, skipped=dropped.skipped, truncated=dropped.truncated)
def _folder_track(track_id: str) -> FolderSource:
# Only a file a scan found. This is what keeps the audio route from being a
# way to read any path on the disk.
@@ -2447,8 +2461,28 @@ def folder_add_preview(body: FolderAddRequest) -> dict:
elif body.mode == "reference":
# Nothing is copied, so there is no size to fit anywhere.
out.update(total_bytes=0, free_bytes=None, enough_space=None)
drive = _drive_of(Path(body.track_ids[0]), places.drives()) if body.track_ids else None
out["removable"] = drive is None or drive["kind"] == "external"
elif destination is not None:
# Copying a file that is already in the import folder makes a second
# copy beside it — legal, but rarely meant, so the dialog says so.
home = destination.resolve()
out["in_destination"] = sum(
1 for t in plan.importable
if t.source_path is not None and t.source_path.resolve().is_relative_to(home)
)
# Per FILE, not per request: a drop can mix the computer's own disk with a
# stick, and only the files on the stick go missing when it is unplugged.
drives = places.drives()
external: dict[str, int] = {}
for t in plan.importable:
if t.source_path is None:
continue
drive = _drive_of(t.source_path, drives)
if drive is None or drive["kind"] == "external":
name = drive["name"] if drive else str(t.source_path.anchor or t.source_path.parent)
external[name] = external.get(name, 0) + 1
out["removable"] = bool(external)
out["removable_count"] = sum(external.values())
out["removable_drives"] = sorted(external)
return out
+19
View File
@@ -549,6 +549,25 @@ class FolderTracks(BaseModel):
removable: bool
class DroppedPaths(BaseModel):
"""Files and folders dropped onto the window from Finder / Explorer."""
paths: list[str]
class DroppedFiles(BaseModel):
"""What a drop resolved to: the audio in it, as a folder lists its files."""
tracks: list[Track]
# As FolderTracks: rows the collection holds are its tracks, and this maps
# their collection id back to the file's folder id, which adding takes.
files: dict[str, str] = {}
# Dropped files that are not audio the library can hold, or are gone.
skipped: int = 0
# Too many files: only the first MAX_DROPPED are here.
truncated: bool = False
class FolderAddRequest(BaseModel):
"""Add browsed files to the collection, and optionally to a playlist/export.
+76
View File
@@ -197,6 +197,82 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
c.post("/api/folder/add/preview",
json={"track_ids": ["/etc/passwd"], "mode": "reference"}).status_code == 404)
print("== a drop onto the window: folders all the way down, files as themselves ==")
drop = Path(tempfile.mkdtemp()) / "Dropped"
d_a = flac(drop / "Album" / "a.flac", title="Dropped A")
d_b = flac(drop / "Album" / "CD2" / "b.flac")
(drop / "Album" / "cover.jpg").write_bytes(b"not audio")
flac(drop / "Album" / ".cache" / "h.flac")
single = flac(drop / "Loose" / "single.flac", title="Single")
sibling = flac(drop / "Loose" / "sibling.flac")
(drop / "Loose" / "readme.txt").write_text("not audio")
r = c.post("/api/folder/dropped", json={"paths": [
str(drop / "Album"), str(single), str(drop / "Loose" / "readme.txt"),
str(drop / "gone.flac"), str(single), str(d_a),
]})
check("answers 200", r.status_code == 200, r.text[:300])
body = r.json()
ids = [t["id"] for t in body["tracks"]]
check("the folder's audio, subfolders included, then the file — each once",
ids == [str(d_a), str(d_b), str(single)], str(ids))
check("a hidden folder inside is left out", str(drop / "Album" / ".cache" / "h.flac") not in ids)
check("a dropped non-audio file and a missing one are counted as skipped",
body["skipped"] == 2, str(body["skipped"]))
check("non-audio INSIDE a dropped folder is not counted", body["skipped"] == 2)
check("tags are read", body["tracks"][0]["title"] == "Dropped A")
check("not truncated", body["truncated"] is False)
check("a dropped file streams",
c.get("/api/folder/tracks/audio", params={"track_id": str(single)}).status_code == 200)
check("so does one found inside a dropped folder",
c.get("/api/folder/tracks/audio", params={"track_id": str(d_b)}).status_code == 200)
check("but not its undropped sibling",
c.get("/api/folder/tracks/audio", params={"track_id": str(sibling)}).status_code == 404)
listed = [t["id"] for t in c.get("/api/folder/tracks", params={"path": str(drop / "Loose")}).json()["tracks"]]
check("browsing that folder afterwards still lists ALL of it",
listed == [str(sibling), str(single)], str(listed))
r = c.post("/api/folder/dropped", json={"paths": [str(drop / "Loose" / "readme.txt")]})
check("a non-audio file is never made streamable",
r.json()["tracks"] == [] and c.get("/api/folder/tracks/audio", params={
"track_id": str(drop / "Loose" / "readme.txt")}).status_code == 404)
capped = main.FOLDERS.dropped([str(drop / "Album")], main._formats(), limit=1)
check("past the cap the rest are left out, and it says so",
len(capped.tracks) == 1 and capped.truncated)
body = c.post("/api/folder/dropped", json={"paths": [str(one)]}).json()
check("a dropped file the collection holds IS its collection track",
[t["id"] for t in body["tracks"]] == [added] and body["files"] == {added: str(one)},
str(body))
req = {"track_ids": [str(d_b)], "mode": "copy", "destination": str(drop / "Album")}
p = c.post("/api/folder/add/preview", json=req).json()
check("copying into the folder they are already in is flagged", p.get("in_destination") == 1, str(p))
req["destination"] = str(Path(tempfile.mkdtemp()))
p = c.post("/api/folder/add/preview", json=req).json()
check("…and not elsewhere", p.get("in_destination") == 0, str(p))
real_drives = main.places.drives
main.places.drives = lambda: [
{"name": "Computer", "path": drop.anchor, "kind": "local"},
{"name": "Stick", "path": str(drop / "Album"), "kind": "external"},
]
try:
req = {"track_ids": [str(d_a), str(single)], "mode": "reference"}
p = c.post("/api/folder/add/preview", json=req).json()
check("the external-drive warning counts files per drive, not by the first",
p["removable"] is True and p["removable_count"] == 1 and p["removable_drives"] == ["Stick"],
str(p))
p = c.post("/api/folder/add/preview", json={"track_ids": [str(single), str(d_a)],
"mode": "reference"}).json()
check("…whichever file comes first", p["removable_count"] == 1, str(p))
finally:
main.places.drives = real_drives
n = len(a.tracks)
job = wait(c, c.post("/api/folder/add", json={"track_ids": [str(d_a), str(single)],
"mode": "reference"}).json())
check("dropped files are added like browsed ones", job["state"] == "done" and len(a.tracks) == n + 2,
str(job))
print("== Rekordbox: the same route adds to a master.db ==")
from konduktor.adapters.rekordbox import discovery as rb_discovery