261 lines
8.7 KiB
Python
261 lines
8.7 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import shutil
|
|
from pathlib import Path
|
|
from urllib import error as urlerror
|
|
from urllib import request as urlrequest
|
|
|
|
from ..config import UPLOAD_DIR
|
|
from ..repositories import jobs as jobs_repo
|
|
from ..repositories import projects as projects_repo
|
|
from .metadata_util import _read_cover_art, read_metadata
|
|
from .project_service_common import ProjectOperationError, _infer_stem_name, project_output_dir
|
|
|
|
|
|
def _sidecar_path(media_path: Path) -> Path:
|
|
return media_path.with_suffix(media_path.suffix + ".json")
|
|
|
|
|
|
def _read_import_sidecar(media_path: Path) -> dict:
|
|
sidecar = _sidecar_path(media_path)
|
|
if not sidecar.exists():
|
|
return {}
|
|
try:
|
|
raw = json.loads(sidecar.read_text(encoding="utf-8"))
|
|
return raw if isinstance(raw, dict) else {}
|
|
except Exception:
|
|
return {}
|
|
|
|
|
|
def _read_source_thumbnail_url(source_path: Path) -> str:
|
|
sidecar = _read_import_sidecar(source_path)
|
|
value = str(sidecar.get("thumbnail") or "").strip()
|
|
if value.startswith(("http://", "https://")):
|
|
return value
|
|
return ""
|
|
|
|
|
|
def _fetch_remote_image(url: str) -> tuple[bytes, str | None]:
|
|
req = urlrequest.Request(url, headers={"User-Agent": "StemEngine/cover-art-fallback"})
|
|
with urlrequest.urlopen(req, timeout=8) as resp:
|
|
data = resp.read()
|
|
mime = resp.headers.get_content_type() if resp.headers else None
|
|
return data, mime
|
|
|
|
|
|
def list_projects() -> list[dict]:
|
|
return projects_repo.list_all()
|
|
|
|
|
|
def get_project_or_raise(project_id: str) -> dict:
|
|
project = projects_repo.get(project_id)
|
|
if project is None:
|
|
raise ProjectOperationError(404, f"Project not found: {project_id}")
|
|
return project
|
|
|
|
|
|
def collect_related_job_ids(project: dict) -> set[str]:
|
|
job_ids = {project["sep_job_id"]}
|
|
for job_id in (project.get("trans_jobs") or {}).values():
|
|
job_ids.add(job_id)
|
|
for job_id in (project.get("abc_jobs") or {}).values():
|
|
job_ids.add(job_id)
|
|
for job_id in (project.get("lrc_jobs") or {}).values():
|
|
job_ids.add(job_id)
|
|
if project.get("mix_job_id"):
|
|
job_ids.add(project["mix_job_id"])
|
|
return job_ids
|
|
|
|
|
|
def delete_project_with_related_jobs(project: dict) -> bool:
|
|
"""Delete project files plus the project record and all linked job records."""
|
|
project_dir = project_output_dir(project)
|
|
if project_dir.exists():
|
|
shutil.rmtree(project_dir, ignore_errors=True)
|
|
|
|
upload_dir = UPLOAD_DIR / project["sep_job_id"]
|
|
if upload_dir.exists():
|
|
shutil.rmtree(upload_dir, ignore_errors=True)
|
|
|
|
job_ids_to_delete = collect_related_job_ids(project)
|
|
|
|
deleted = projects_repo.delete(project["id"])
|
|
for job_id in job_ids_to_delete:
|
|
jobs_repo.delete(job_id)
|
|
return deleted
|
|
|
|
|
|
def build_project_detail(project: dict) -> dict:
|
|
"""Expand linked jobs and source metadata for a project detail response."""
|
|
trans_jobs_expanded = {
|
|
stem: jobs_repo.get(job_id)
|
|
for stem, job_id in (project.get("trans_jobs") or {}).items()
|
|
}
|
|
abc_jobs_expanded = {
|
|
stem: jobs_repo.get(job_id)
|
|
for stem, job_id in (project.get("abc_jobs") or {}).items()
|
|
}
|
|
lrc_jobs_expanded = {
|
|
stem: jobs_repo.get(job_id)
|
|
for stem, job_id in (project.get("lrc_jobs") or {}).items()
|
|
}
|
|
|
|
sep_job = jobs_repo.get(project["sep_job_id"])
|
|
mix_job = jobs_repo.get(project.get("mix_job_id")) if project.get("mix_job_id") else None
|
|
|
|
source_artist = ""
|
|
source_title = ""
|
|
source_thumbnail_url = ""
|
|
source_file = next(
|
|
(file_entry for file_entry in (sep_job or {}).get("files", []) if file_entry.get("type") == "source"),
|
|
None,
|
|
)
|
|
if source_file:
|
|
src_path = source_file.get("path", "")
|
|
if src_path and Path(src_path).exists():
|
|
source_thumbnail_url = _read_source_thumbnail_url(Path(src_path))
|
|
try:
|
|
meta = read_metadata(src_path)
|
|
source_artist = meta.get("artist") or meta.get("albumartist") or ""
|
|
source_title = meta.get("title") or ""
|
|
except Exception:
|
|
pass
|
|
|
|
return {
|
|
**project,
|
|
"sep_job": sep_job,
|
|
"trans_jobs": trans_jobs_expanded,
|
|
"abc_jobs": abc_jobs_expanded,
|
|
"lrc_jobs": lrc_jobs_expanded,
|
|
"mix_job": mix_job,
|
|
"source_artist": source_artist,
|
|
"source_title": source_title,
|
|
"source_thumbnail_url": source_thumbnail_url,
|
|
}
|
|
|
|
|
|
def rename_project_stem(project: dict, stem_name: str, new_name: str) -> dict:
|
|
"""Rename a tracked stem on disk and update the separation job record."""
|
|
from .separator_service import _stem_filename
|
|
|
|
sep_job = jobs_repo.get(project["sep_job_id"])
|
|
if sep_job is None:
|
|
raise ProjectOperationError(404, "Separation job not found")
|
|
|
|
stem_files = list(sep_job.get("files", []))
|
|
stem_file = None
|
|
stem_idx = None
|
|
for index, file_entry in enumerate(stem_files):
|
|
if file_entry.get("stem") == stem_name or file_entry.get("name") == stem_name:
|
|
stem_file = file_entry
|
|
stem_idx = index
|
|
break
|
|
|
|
if stem_file is None or stem_idx is None:
|
|
raise ProjectOperationError(404, f"Stem not found: {stem_name}")
|
|
|
|
old_path = Path(stem_file["path"])
|
|
if not old_path.exists():
|
|
raise ProjectOperationError(404, f"Stem file not found on disk: {old_path}")
|
|
|
|
cleaned_name = new_name.strip()
|
|
if not cleaned_name:
|
|
raise ProjectOperationError(400, "New name cannot be empty")
|
|
|
|
new_filename = _stem_filename(project["name"], cleaned_name, old_path.suffix)
|
|
new_path = old_path.parent / new_filename
|
|
if new_path.exists() and new_path != old_path:
|
|
raise ProjectOperationError(409, f"A file with name '{new_filename}' already exists")
|
|
|
|
try:
|
|
os.rename(str(old_path), str(new_path))
|
|
except Exception as exc:
|
|
raise ProjectOperationError(500, f"Failed to rename stem: {exc}") from exc
|
|
|
|
stem_files[stem_idx] = {
|
|
**stem_file,
|
|
"name": new_filename,
|
|
"stem": cleaned_name,
|
|
"path": str(new_path),
|
|
}
|
|
jobs_repo.update(project["sep_job_id"], files=stem_files)
|
|
|
|
return {
|
|
"success": True,
|
|
"old_name": stem_name,
|
|
"new_name": cleaned_name,
|
|
"new_path": str(new_path),
|
|
}
|
|
|
|
|
|
def rescan_project_stems(project: dict, audio_exts: set[str]) -> dict:
|
|
"""Register untracked audio files under the project's Stems directory."""
|
|
sep_job = jobs_repo.get(project["sep_job_id"])
|
|
if sep_job is None:
|
|
raise ProjectOperationError(404, "Separation job not found")
|
|
|
|
stems_dir = project_output_dir(project) / "Stems"
|
|
if not stems_dir.exists():
|
|
raise ProjectOperationError(404, "Stems directory not found")
|
|
|
|
files = list(sep_job.get("files", []))
|
|
tracked_paths = {file_entry["path"] for file_entry in files}
|
|
added = []
|
|
|
|
for audio_file in sorted(stems_dir.rglob("*")):
|
|
if not audio_file.is_file():
|
|
continue
|
|
if audio_file.suffix.lower() not in audio_exts:
|
|
continue
|
|
if str(audio_file) in tracked_paths:
|
|
continue
|
|
|
|
entry = {
|
|
"name": audio_file.name,
|
|
"path": str(audio_file),
|
|
"type": "stem",
|
|
"stem": _infer_stem_name(audio_file.stem, project["name"]),
|
|
}
|
|
files.append(entry)
|
|
tracked_paths.add(str(audio_file))
|
|
added.append(entry)
|
|
|
|
if added:
|
|
jobs_repo.update(project["sep_job_id"], files=files)
|
|
|
|
return {"added": len(added), "stems": [entry["stem"] for entry in added]}
|
|
|
|
|
|
def get_project_cover_art(project: dict) -> tuple[bytes, str]:
|
|
"""Return embedded cover-art bytes and mime type from a project's source file."""
|
|
sep_job_data = jobs_repo.get(project["sep_job_id"]) or {}
|
|
source_file = next(
|
|
(file_entry for file_entry in sep_job_data.get("files", []) if file_entry.get("type") == "source"),
|
|
None,
|
|
)
|
|
if not source_file:
|
|
raise ProjectOperationError(404, "No source file")
|
|
|
|
source_path = source_file.get("path", "")
|
|
if not source_path or not Path(source_path).exists():
|
|
raise ProjectOperationError(404, "Source file not found")
|
|
|
|
data, mime = _read_cover_art(source_path)
|
|
if data:
|
|
return data, mime or "image/jpeg"
|
|
|
|
thumbnail_url = _read_source_thumbnail_url(Path(source_path))
|
|
if thumbnail_url:
|
|
try:
|
|
remote_data, remote_mime = _fetch_remote_image(thumbnail_url)
|
|
if remote_data:
|
|
return remote_data, remote_mime or "image/jpeg"
|
|
except (urlerror.URLError, TimeoutError, ValueError, OSError):
|
|
pass
|
|
except Exception:
|
|
pass
|
|
|
|
raise ProjectOperationError(404, "No cover art")
|