Files
lintunes/lintunes/importers/file_importer.py
T
trav b7f8761bd1 Import existing LinTunes project
Snapshot of the existing codebase before working through the TASKS.md
backlog. Real library data (data/) and the iTunes import fixture
(itunes-test-library/) are gitignored.
2026-06-26 21:12:01 -04:00

107 lines
3.7 KiB
Python

import re
import shutil
from datetime import datetime, timezone
from pathlib import Path
from lintunes.models import Track
from lintunes import tagging
AUDIO_EXTENSIONS = {".mp3", ".m4a", ".flac", ".aac", ".wav", ".aiff", ".aif"}
_UNSAFE_CHARS = re.compile(r'[/\\:*?"<>|\x00-\x1f]')
def is_audio_file(path: Path) -> bool:
return path.suffix.lower() in AUDIO_EXTENSIONS
def sanitize_component(name: str) -> str:
name = _UNSAFE_CHARS.sub("_", name).strip().rstrip(".")
return name or "Unknown"
def organized_destination(music_dir: Path, fields: dict, filename: str) -> Path:
"""<music_dir>/<Artist>/<Album>/<filename>, like iTunes' folder layout."""
artist = sanitize_component(fields.get("album_artist") or fields.get("artist") or "Unknown Artist")
album = sanitize_component(fields.get("album") or "Unknown Album")
return music_dir / artist / album / sanitize_component(filename)
def unique_path(dest: Path) -> Path:
if not dest.exists():
return dest
for i in range(1, 1000):
candidate = dest.with_stem(f"{dest.stem} {i}")
if not candidate.exists():
return candidate
raise FileExistsError(f"Could not find a free name for {dest}")
def import_file(source: Path, music_dir: Path, manager) -> Track | None:
"""Copy an external audio file into the organized music dir and add it
to the library. Returns the new Track, or the existing one if this exact
file is already in the library."""
source = Path(source).resolve()
if not source.is_file() or not is_audio_file(source):
return None
fields = tagging.read_tags(source)
# Already in the library? (same target path, or source is inside music_dir)
for track in manager.library.tracks.values():
if track.location and Path(track.location) == source:
return track
if music_dir in source.parents:
dest = source # already organized inside the music dir; don't copy
else:
dest = organized_destination(music_dir, fields, source.name)
for track in manager.library.tracks.values():
if track.location and Path(track.location) == dest:
return track
dest = unique_path(dest)
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, dest)
now = datetime.now(timezone.utc).replace(tzinfo=None).isoformat()
track = Track(
name=fields.get("name") or source.stem,
location=str(dest),
date_added=now,
date_modified=now,
)
for key in ("artist", "album_artist", "album", "genre", "composer",
"year", "track_number", "track_count", "disc_number", "disc_count",
"comments", "total_time", "bit_rate", "sample_rate", "size", "kind"):
if key in fields:
setattr(track, key, fields[key])
manager.add_track(track)
return track
def import_paths(paths: list[Path], music_dir: Path, manager,
playlist_pid: str = "") -> list[Track]:
"""Import files and directories (recursively); optionally add to a playlist."""
files: list[Path] = []
for path in paths:
path = Path(path)
if path.is_dir():
files.extend(sorted(p for p in path.rglob("*") if p.is_file() and is_audio_file(p)))
elif path.is_file() and is_audio_file(path):
files.append(path)
imported = []
for file_path in files:
try:
track = import_file(file_path, music_dir, manager)
except Exception as e:
print(f"Failed to import {file_path}: {e}")
continue
if track:
imported.append(track)
if playlist_pid and imported:
manager.add_tracks_to_playlist(playlist_pid, [t.track_id for t in imported])
return imported