Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added auth providers for `Plex`, `Spotify` and `Tidal`, including a reusable `OAuth2Provider` implementing the authorization code flow with PKCE, and `Service.auth()` for resolving a service's registered provider.
- Registering playlists to a synced playlists now has a `mode`, to select which source takes priority.
CLI: `plistsync sync register --mode`. Supported Modes are `append|skip-duplicates|take-incoming|take-existing`.
- traktor: `NMLLibrary` now implements `InfoLookup` (`find_by_info`), allowing metadata searches; playlist tracks resolve their metadata through the linked library. File-path lookups are backed by a lazily built index.

### Changes

Expand Down
5 changes: 5 additions & 0 deletions docs/library/guides/matching.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,11 @@ Metadata and fuzzy matching are the fallback when no identifier produces a relia

Each {class}`~plistsync.core.track.Track` exposes its metadata through the {py:attr}`~plistsync.core.track.Track.info` property. This layer is purely metadata based.

How a collection searches depends on the service: Spotify searches its own catalog,
Traktor scans its local collection and treats each supplied field as a case-insensitive
substring. See the {doc}`service overview <../../services/index>` for which services
support metadata lookups at all.

Collections without {class}`~plistsync.core.collection.IDLookup` or {class}`~plistsync.core.collection.InfoLookup` fall back to streaming every track through the same comparison, which is much slower.

```{note}
Expand Down
2 changes: 1 addition & 1 deletion docs/services/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ you can check whether a service fits what you want to do before setting it up.
| {doc}`Spotify <spotify/index>` | <span class="cap yes">✓</span> | <span class="cap yes">✓</span> | <span class="cap yes">✓</span> | <span class="cap yes">✓</span> |
| {doc}`Tidal <tidal/index>` | <span class="cap yes">✓</span> | <span class="cap yes">✓</span> | <span class="cap yes">✓</span> | <span class="cap no">—</span> |
| {doc}`Plex <plex/index>` | <span class="cap yes">✓</span> | <span class="cap yes">✓</span> | <span class="cap yes">✓</span> | <span class="cap no">—</span> |
| {doc}`Traktor <traktor/index>` | <span class="cap no">—</span> | <span class="cap yes">✓</span> | <span class="cap yes">✓</span> | <span class="cap no">—</span> |
| {doc}`Traktor <traktor/index>` | <span class="cap no">—</span> | <span class="cap yes">✓</span> | <span class="cap yes">✓</span> | <span class="cap yes">✓</span> |
| {doc}`Local <local/index>` | <span class="cap no">—</span> | <span class="cap no">—</span> | <span class="cap yes">✓</span> | <span class="cap no">—</span> |
```

Expand Down
69 changes: 50 additions & 19 deletions plistsync/services/traktor/library.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from lxml import etree

from plistsync.core.collection import IDLookup, Library, TrackStream
from plistsync.core.collection import IDLookup, InfoLookup, Library, TrackStream
from plistsync.core.ids import FilePath, PlaylistID
from plistsync.logger import log

Expand All @@ -24,7 +24,7 @@

from lxml.etree import _Element, _ElementTree

from plistsync.core import TrackID
from plistsync.core import TrackID, TrackInfo

from .track import NMLPlaylistTrack

Expand All @@ -33,19 +33,20 @@ class NMLLibrary(
Library[NMLTrack, NMLPlaylist, TraktorConfig],
TrackStream[NMLTrack],
IDLookup[NMLTrack],
InfoLookup[NMLTrack],
):
"""A Traktor NML Library.

Allows to parse and interact with a Traktor NML file. I.e. traktor export playlist

Sadly nml files do not contain unique identifiers for tracks, thus we need to
iterate over all tracks to find a match. Might be less efficient than other
collections.
NML files have no unique track identifiers, so track lookups use the file path
(indexed lazily) or a metadata scan.
"""

path: Path
tree: _ElementTree
backup_before_write: bool
_track_index_cache: dict[NMLPath, NMLTrack] | None

def __init__(self, path: Path | str, backup_before_write: bool):
self.path = Path(path)
Expand All @@ -54,6 +55,7 @@ def __init__(self, path: Path | str, backup_before_write: bool):
self.backup_before_write = backup_before_write
# An NML file is a XML file
self.tree = etree.parse(self.path)
self._track_index_cache = None

@classmethod
def from_config(cls, config: TraktorConfig) -> Self:
Expand Down Expand Up @@ -232,22 +234,40 @@ def find_by_ids(self, ids: Iterable[TrackID]) -> NMLTrack | None:
def find_by_traktor_path(self, traktor_path: NMLPath) -> NMLTrack | None:
"""Find a track by its file path.

Parameter
---------
traktor_path : TraktorPath
The file path of the track to find. This should be the full path including
the filename. In traktor notation /:foo/:bar.mp3. If a volume is specified,
it should will be ignored for the search.
The volume id is ignored, playlist paths only contain the volume name.
"""
entry = self._collection.xpath(
f".//ENTRY/LOCATION[@DIR={xpath_string_escape(traktor_path.directories)}]"
f"[@FILE={xpath_string_escape(traktor_path.file)}]"
f"[@VOLUME={xpath_string_escape(traktor_path.volume)}]/.."
)
if len(entry) == 0:
return None
return self._track_index().get(traktor_path)

# --------------------------- InfoLookup protocol ---------------------------- #

def find_by_info(self, info: TrackInfo) -> Iterable[NMLTrack]:
"""Find tracks by metadata, scanning the collection.

Every supplied, non-empty field must match as a case-insensitive substring;
artists and albums match if any requested value is contained in any value of
the track. Results preserve collection order.

TODO: make this behaviour consistent across services.
"""
title = (info.get("title") or "").casefold()
artists = {a.casefold() for a in info.get("artists") or [] if a}
albums = {a.casefold() for a in info.get("albums") or [] if a}

return NMLTrack(entry[0])
if not (title or artists or albums):
return

def matches(needles: set[str], candidates: Iterable[str]) -> bool:
folded = [c.casefold() for c in candidates]
return any(n in c for n in needles for c in folded)

for track in self.tracks:
if title and title not in (track.title or "").casefold():
continue
if artists and not matches(artists, track.artists):
continue
if albums and not matches(albums, track.albums):
continue
yield track

# --------------------------- TrackStream protocol --------------------------- #

Expand All @@ -267,6 +287,15 @@ def __len__(self) -> int:

# ---------------------------------- Helper ---------------------------------- #

def _track_index(self) -> dict[NMLPath, NMLTrack]:
"""Return a path index for the collection, building the cache on first use."""
if self._track_index_cache is None:
index: dict[NMLPath, NMLTrack] = {}
for track in self.tracks:
index.setdefault(track.traktor_path, track)
self._track_index_cache = index
return self._track_index_cache

@property
def _collection(self):
collection = self.tree.find("COLLECTION")
Expand Down Expand Up @@ -317,6 +346,8 @@ def insert_track(self, track: NMLTrack | NMLPlaylistTrack, force: bool = False):
count = int(collection.get("ENTRIES", "0"))
collection.set("ENTRIES", str(count + 1))
inserted = NMLTrack(entry)
if self._track_index_cache is not None:
self._track_index_cache.setdefault(inserted.traktor_path, inserted)

log.debug(f"Inserted track into COLLECTION: {inserted.traktor_path}")
return inserted
36 changes: 12 additions & 24 deletions plistsync/services/traktor/path.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import re
from dataclasses import dataclass, field
from pathlib import PurePosixPath, PureWindowsPath
from typing import TYPE_CHECKING, Literal, Self

Expand All @@ -12,19 +13,18 @@
from lxml.etree import _Element


@dataclass(frozen=True, slots=True, init=False)
class NMLPath:
"""OS-agnostik representation of a File Path in Traktor.

Follows the logic in NML Playlists: volume/:directory/:file
"""

_parts: list[str]
_parts: tuple[str, ...]
# Not part of equality: playlist paths only carry the volume name.
_volume_id: str | None = field(compare=False, default=None)

# We treat volume id as optional, and use the volume by default
# Should only be changed through our location helpers
_volume_id: str | None

def __init__(self, path: str):
def __init__(self, path: str, volume_id: str | None = None):
"""Construct a TraktorPath from a Traktor-style path string.

As used by Traktors NML files in the playlist section: volume/:directory/:file
Expand All @@ -33,15 +33,16 @@ def __init__(self, path: str):
raise ValueError(
f"Invalid Traktor path: {path}, follow schema volume/:directory/:file"
)
self._parts = [p for p in path.split("/:") if p]
self._volume_id = None
object.__setattr__(self, "_parts", tuple(p for p in path.split("/:") if p))
object.__setattr__(self, "_volume_id", volume_id)

@property
def volume(self) -> str:
return self._parts[0]

@property
def volume_id(self) -> str | None:
def volume_id(self) -> str:
"""Optional volume ID, falling back to the volume name."""
if self._volume_id is not None:
return self._volume_id
return self.volume
Expand All @@ -53,7 +54,7 @@ def directories(self) -> str:
return "/:" + "/:".join(self._parts[1:-1]) + "/:"

@property
def parts(self) -> list[str]:
def parts(self) -> tuple[str, ...]:
return self._parts

@property
Expand Down Expand Up @@ -90,10 +91,7 @@ def from_nml_location(cls, loc: _Element) -> Self:
raise ValueError("Could not find DIR, FILE or VOLUME in NML LOCATION entry")

dir_parts = [p for p in dir.split("/:") if p]
tp = cls("/:".join([vol, *dir_parts, file]))
tp._volume_id = volid

return tp
return cls("/:".join([vol, *dir_parts, file]), volume_id=volid)

def to_nml_location(self, parent: _Element | None = None) -> _Element:
"""
Expand Down Expand Up @@ -164,13 +162,3 @@ def __str__(self) -> str:

def __repr__(self) -> str:
return f"{type(self).__name__}(path={str(self)!r})"

def __eq__(self, value: object) -> bool:
"""
Check tracks are the same.

Currently not comparing volume ids.
"""
if not isinstance(value, NMLPath):
return False
return str(self) == str(value)
26 changes: 12 additions & 14 deletions plistsync/services/traktor/playlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@

from plistsync.core.collection import IDLookup
from plistsync.core.ids import FilePath, PlaylistID
from plistsync.core.playlist import (
PlaylistInfo,
ServicePlaylist,
)
from plistsync.core.playlist import PlaylistInfo, ServicePlaylist
from plistsync.logger import log

from .config import TraktorConfig
Expand All @@ -30,9 +27,7 @@
from lxml.etree import _Element

from plistsync.core import TrackID
from plistsync.core.playlist import (
Snapshot,
)
from plistsync.core.playlist import Snapshot

from .library import NMLLibrary
from .track import NMLTrack
Expand Down Expand Up @@ -161,9 +156,9 @@ def tracks(self, value: list[NMLPlaylistTrack] | Sequence[NMLTrack]):
def convert(t: NMLPlaylistTrack | NMLTrack):
# convert tracks to playlist tracks
if isinstance(t, NMLPlaylistTrack):
return t
return NMLPlaylistTrack(t.entry, library=self.library)
else:
return NMLPlaylistTrack.from_track(t)
return NMLPlaylistTrack.from_track(t, library=self.library)

self._tracks = list(map(convert, value))

Expand Down Expand Up @@ -210,18 +205,21 @@ def _overwrite_track_entries(self, tracks: list[NMLPlaylistTrack]) -> None:
# Append new entries (avoid reusing Elements that may already have parents)
for track in tracks:
self.playlist_node.append(
NMLPlaylistTrack.from_traktor_path(track.traktor_path).entry
NMLPlaylistTrack.from_traktor_path(
track.traktor_path, library=self.library
).entry
)
if self.library.find_by_traktor_path(track.traktor_path) is None:
self.library.insert_track(track)
self.library.insert_track(track)

self.playlist_node.set("ENTRIES", str(len(tracks)))

# ---------------------------- Track lazy loading ---------------------------- #

def _fetch_tracks(self):
entries = self.playlist_node.xpath(".//ENTRY/PRIMARYKEY[@TYPE='TRACK']/..")
self._tracks = [NMLPlaylistTrack(entry) for entry in entries]
self._tracks = [
NMLPlaylistTrack(entry, library=self.library) for entry in entries
]
return self._tracks

# --------------------------- IDLookup protocol ------------------------------ #
Expand Down Expand Up @@ -258,4 +256,4 @@ def find_by_traktor_path(self, traktor_path: NMLPath) -> NMLPlaylistTrack | None
", using first one."
)

return NMLPlaylistTrack(entries[0])
return NMLPlaylistTrack(entries[0], library=self.library)
Loading
Loading