Files
stemengine_old/backend/services/local_library_service.py
2026-04-21 16:24:11 +09:00

310 lines
9.5 KiB
Python

"""Local filesystem music library helpers.
Phase 1 provides:
- path validation
- file listing with pagination/filtering
- secure import (copy) into IMPORTS_DIR
"""
from __future__ import annotations
import json
import os
import shutil
from datetime import datetime, timezone
from pathlib import Path
from typing import Iterable, Optional
from ..config import IMPORTS_DIR, SETTINGS_PATH
_AUDIO_EXTS = {'.mp3', '.flac', '.wav', '.m4a', '.ogg', '.opus', '.aac'}
_VIDEO_EXTS = {'.mp4', '.mkv', '.webm', '.mov', '.m4v'}
_SUPPORTED_EXTS = _AUDIO_EXTS | _VIDEO_EXTS
def read_configured_music_library_path() -> str:
"""Return the configured library path.
Resolution order:
1. ``settings.json`` ``music_library_path`` key (user-saved via UI).
2. ``MUSIC_LIBRARY_PATH`` environment variable (deployment bootstrap).
"""
if SETTINGS_PATH.exists():
try:
raw = json.loads(SETTINGS_PATH.read_text(encoding="utf-8"))
if isinstance(raw, dict):
value = raw.get("music_library_path")
if value is not None:
cleaned = str(value).strip()
if cleaned:
return cleaned
except Exception:
pass
env_val = os.environ.get("MUSIC_LIBRARY_PATH", "").strip()
return env_val
def read_configured_music_library_path_with_source() -> tuple[str, str]:
"""Return configured music library path and its source.
Source values:
- ``settings`` when a non-empty ``music_library_path`` exists in settings.json
- ``env`` when falling back to ``MUSIC_LIBRARY_PATH``
- ``settings`` when neither source provides a path (default/empty state)
"""
env_val = os.environ.get("MUSIC_LIBRARY_PATH", "").strip()
if SETTINGS_PATH.exists():
try:
raw = json.loads(SETTINGS_PATH.read_text(encoding="utf-8"))
if isinstance(raw, dict):
value = raw.get("music_library_path")
if value is not None:
cleaned = str(value).strip()
if cleaned:
if env_val and cleaned == env_val:
return cleaned, "env"
return cleaned, "settings"
except Exception:
pass
if env_val:
return env_val, "env"
return "", "settings"
def seed_music_library_path_from_env() -> bool:
"""If ``MUSIC_LIBRARY_PATH`` env var is set and settings.json has no
value for ``music_library_path``, write the env var value into
settings.json so the Settings UI reflects the deployment default.
Returns ``True`` if settings were updated, ``False`` otherwise.
"""
env_val = os.environ.get("MUSIC_LIBRARY_PATH", "").strip()
if not env_val:
return False
existing: dict = {}
if SETTINGS_PATH.exists():
try:
existing = json.loads(SETTINGS_PATH.read_text(encoding="utf-8"))
if not isinstance(existing, dict):
existing = {}
except Exception:
existing = {}
if existing.get("music_library_path", "").strip():
return False # Already configured via UI — do not override.
existing["music_library_path"] = env_val
try:
SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True)
SETTINGS_PATH.write_text(json.dumps(existing, indent=2, ensure_ascii=False), encoding="utf-8")
return True
except Exception:
return False
def validate_library_path(path_text: str) -> dict:
cleaned = str(path_text or "").strip()
if not cleaned:
return {
"configured": False,
"path": "",
"absolute": False,
"exists": False,
"is_dir": False,
"readable": False,
"writable": False,
"valid": False,
"error": "No path configured.",
}
if "\x00" in cleaned:
return {
"configured": True,
"path": cleaned,
"absolute": False,
"exists": False,
"is_dir": False,
"readable": False,
"writable": False,
"valid": False,
"error": "Path contains null bytes.",
}
path = Path(cleaned)
absolute = path.is_absolute()
exists = path.exists()
is_dir = path.is_dir() if exists else False
readable = os.access(path, os.R_OK | os.X_OK) if exists and is_dir else False
writable = os.access(path, os.W_OK | os.X_OK) if exists and is_dir else False
error = None
if not absolute:
error = "Path must be absolute."
elif not exists:
error = "Path does not exist."
elif not is_dir:
error = "Path is not a directory."
elif not readable:
error = "Path is not readable by the backend process."
return {
"configured": True,
"path": cleaned,
"absolute": absolute,
"exists": exists,
"is_dir": is_dir,
"readable": readable,
"writable": writable,
"valid": error is None,
"error": error,
}
def list_tracks(
library_root: Path,
*,
offset: int = 0,
limit: int = 100,
query: str = "",
extensions: Optional[Iterable[str]] = None,
) -> dict:
safe_offset = max(0, int(offset or 0))
safe_limit = max(1, min(500, int(limit or 100)))
selected_exts = _normalize_extensions(extensions)
query_text = (query or "").strip().lower()
tracks: list[dict] = []
root_resolved = library_root.resolve()
for base, dirs, files in os.walk(root_resolved):
dirs[:] = [d for d in dirs if not d.startswith('.')]
for file_name in files:
if file_name.startswith('.'):
continue
path = Path(base) / file_name
ext = path.suffix.lower()
if ext not in selected_exts:
continue
if query_text and query_text not in file_name.lower() and query_text not in str(path).lower():
continue
try:
stat = path.stat()
rel = path.resolve().relative_to(root_resolved)
except Exception:
continue
tracks.append({
"name": file_name,
"path": str(path),
"relative_path": str(rel),
"size": int(stat.st_size),
"mtime": int(stat.st_mtime),
"ext": ext,
"is_video": ext in _VIDEO_EXTS,
})
tracks.sort(key=lambda item: item.get("mtime", 0), reverse=True)
total = len(tracks)
page = tracks[safe_offset:safe_offset + safe_limit]
return {
"path": str(root_resolved),
"offset": safe_offset,
"limit": safe_limit,
"total": total,
"tracks": page,
}
def import_track(library_root: Path, source_path_text: str) -> dict:
source_text = str(source_path_text or "").strip()
if not source_text:
raise ValueError("source_path is required.")
if "\x00" in source_text:
raise ValueError("source_path contains null bytes.")
source = Path(source_text)
if not source.is_absolute():
raise ValueError("source_path must be an absolute path.")
root_resolved = library_root.resolve()
source_resolved = source.resolve()
try:
source_resolved.relative_to(root_resolved)
except ValueError as exc:
raise ValueError("source_path must be inside the configured music library path.") from exc
if not source_resolved.exists() or not source_resolved.is_file():
raise ValueError("source_path does not point to an existing file.")
ext = source_resolved.suffix.lower()
if ext not in _SUPPORTED_EXTS:
raise ValueError(f"Unsupported file extension '{ext}'.")
IMPORTS_DIR.mkdir(parents=True, exist_ok=True)
dest = _collision_safe_path(IMPORTS_DIR, source_resolved.name)
shutil.copy2(source_resolved, dest)
_write_import_metadata(dest, {
"source": "local-library",
"source_path": str(source_resolved),
"library_root": str(root_resolved),
"is_video": ext in _VIDEO_EXTS,
})
stat = dest.stat()
return {
"filename": dest.name,
"path": str(dest),
"size": int(stat.st_size),
"is_video": ext in _VIDEO_EXTS,
"source": "local-library",
}
def _normalize_extensions(extensions: Optional[Iterable[str]]) -> set[str]:
if not extensions:
return set(_SUPPORTED_EXTS)
normalized = set()
for value in extensions:
cleaned = str(value or "").strip().lower()
if not cleaned:
continue
if not cleaned.startswith('.'):
cleaned = f".{cleaned}"
if cleaned in _SUPPORTED_EXTS:
normalized.add(cleaned)
return normalized or set(_SUPPORTED_EXTS)
def _collision_safe_path(folder: Path, filename: str) -> Path:
candidate = folder / filename
if not candidate.exists():
return candidate
stem = Path(filename).stem
suffix = Path(filename).suffix
idx = 2
while True:
candidate = folder / f"{stem} ({idx}){suffix}"
if not candidate.exists():
return candidate
idx += 1
def _sidecar_path(media_path: Path) -> Path:
return media_path.with_suffix(media_path.suffix + '.json')
def _write_import_metadata(media_path: Path, payload: dict) -> None:
data = {
**payload,
"filename": media_path.name,
"path": str(media_path),
"updated_at": datetime.now(timezone.utc).isoformat(),
}
_sidecar_path(media_path).write_text(json.dumps(data, indent=2), encoding="utf-8")