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 @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- 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.
- plex: Now implements the `find_by_info` protocol, this allows to search for tracks via metadata.

### Changes

Expand Down
127 changes: 112 additions & 15 deletions plistsync/services/plex/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,16 @@
from plistsync.logger import log
from plistsync.utils.session import PlistsyncSession, TokenSession

from .api_types import (
PlexMediaTypes,
)
from .api_types import PlexMediaTypes

if TYPE_CHECKING:
from collections.abc import Iterable, Mapping

from plistsync.core import TrackInfo

from .api_types import (
PlexApiConnection,
PlexApiMediaContainer,
PlexApiPlaylistResponse,
PlexApiPlaylistTrackResponse,
PlexApiResourcesResponse,
Expand Down Expand Up @@ -148,6 +149,10 @@ def _resolve_server_name(server_name: str):
server_url = config.server_url
elif config.server_name:
server_url = _resolve_server_name(config.server_name)
else:
raise ValueError(
"Plex requires either server_url or server_name to be configured."
)

return cls(
config.app_name,
Expand Down Expand Up @@ -543,6 +548,32 @@ def clear(self, playlist_id: int) -> PlexApiPlaylistResponse:
return response.json()["MediaContainer"]["Metadata"][0]


def matches_track_info(track: PlexApiTrackResponse, info: TrackInfo) -> bool:
"""Whether a Plex track matches the given metadata.

Matching is case-insensitive containment, and the artist may be stored in
either `grandparentTitle` (album artist) or `originalTitle` (track artist,
e.g. for compilations).
"""
title = info.get("title")
if title and title.casefold() not in (track.get("title") or "").casefold():
return False

artists = [artist.casefold() for artist in info.get("artists", [])]
if artists:
names = [
(track.get("grandparentTitle") or "").casefold(),
(track.get("originalTitle") or "").casefold(),
]
if not any(artist in name for artist in artists for name in names):
return False

albums = [album.casefold() for album in info.get("albums", [])]
return not albums or any(
album in (track.get("parentTitle") or "").casefold() for album in albums
)


class TrackApi:
"""Track-specific Plex API client."""

Expand All @@ -561,46 +592,112 @@ def fetch_tracks(
section_id : str | int
The id of the Plex library (section).
page_size : int
Number of tracks to fetch per request (default: 1000).
Number of tracks to fetch per request (default: 5000).

Returns
-------
list[dict]: List of track metadata dicts.
"""
yield from self._iter_all(
section_id, {"type": PlexMediaTypes.TRACK.value}, page_size
)

def fetch_tracks_by_info(
self,
section_id: str | int,
*,
title: str | None = None,
artist: str | None = None,
album: str | None = None,
page_size: int = 500,
) -> list[PlexApiTrackResponse]:
"""Fetch tracks matching the given metadata, filtered by the server.

Parameters
----------
section_id : str | int
The id of the Plex library (section).
title : str | None
Track title to filter by, by default None.
artist : str | None
Artist to match against, by default None.
album : str | None
Album title to filter by, by default None.
page_size : int
Number of tracks to fetch per request (default: 500).

Dev Note:
---------

Only title, album and (for artist-only lookups) `artist.title` are sent
to the server. Plex's artist filter targets the album artist, while a
track's artist may only be stored in `originalTitle`, so the returned
tracks are additionally matched locally against all given metadata.

Raises
------
ValueError
If none of ``title``, ``artist`` or ``album`` is provided.
"""
info: TrackInfo = {}
if title:
info["title"] = title
if artist:
info["artists"] = [artist]
if album:
info["albums"] = [album]
if not info:
raise ValueError("Provide at least one of artist, album, or title.")

params: dict[str, str | int] = {"type": PlexMediaTypes.TRACK.value}
if title:
params["title"] = title
if album:
params["album.title"] = album
if artist and not title and not album:
params["artist.title"] = artist

return [
track
for track in self._iter_all(section_id, params, page_size)
if matches_track_info(track, info)
]

def _iter_all(
self,
section_id: str | int,
params: Mapping[str, str | int],
page_size: int,
) -> Iterable[PlexApiTrackResponse]:
"""Iterate a section's `/all` endpoint, paginated, applying filters."""
start = 0
total_size = 0
num_fetched = 0
while True:
response = self.session.request(
"GET",
f"{self.session.server_url}/library/sections/{section_id}/all",
params={
"type": PlexMediaTypes.TRACK.value,
**params,
"X-Plex-Container-Start": start,
"X-Plex-Container-Size": page_size,
},
)
response.raise_for_status()
tracks = response.json()["MediaContainer"].get("Metadata", [])
container: PlexApiMediaContainer = response.json().get("MediaContainer", {})
tracks = container.get("Metadata", [])
yield from tracks
if len(tracks) < page_size:
yield from tracks
break
return
num_fetched += len(tracks)
start += page_size

# log some progress
total_size = response.json()["MediaContainer"].get("totalSize", 0)
total_size = container.get("totalSize", 0)
if total_size != 0:
log.debug(
f"Fetched {num_fetched} of {total_size} tracks"
f" from section {section_id}."
)

yield from tracks

return

def fetch_tracks_by_path(
self,
file_path: Path | str,
Expand Down
11 changes: 11 additions & 0 deletions plistsync/services/plex/api_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,17 @@ class PlexApiTrackImage(TypedDict, total=False):
url: str # '/library/metadata/55906/thumb/1713284398'


# -------------------------------- Container -------------------------------- #


class PlexApiMediaContainer(TypedDict, total=False):
"""Fields of the `MediaContainer` envelope read by the typed endpoints."""

size: int # 2
totalSize: int # 2
Metadata: list[PlexApiTrackResponse] # tracks


# --------------------------------- Playlist --------------------------------- #


Expand Down
40 changes: 37 additions & 3 deletions plistsync/services/plex/library.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,28 @@
from requests import HTTPError

from plistsync.core import Library
from plistsync.core.collection import IDLookup, TrackStream
from plistsync.core.collection import IDLookup, InfoLookup, TrackStream
from plistsync.core.ids import ISRC, FilePath, PlaylistID
from plistsync.logger import log
from plistsync.services.plex.playlist import PlexPlaylist, PlexPlaylistID

from .api import PlexApi, PlexApiSession
from .api import PlexApi, PlexApiSession, matches_track_info
from .config import PlexConfig
from .track import PlexTrack, PlexTrackID

if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
from typing import Self

from plistsync.core import PathRewrite, TrackID
from plistsync.core import PathRewrite, TrackID, TrackInfo
from plistsync.services.local.track import FileCache


class PlexLibrary(
Library[PlexTrack, PlexPlaylist, PlexConfig],
TrackStream[PlexTrack],
IDLookup[PlexTrack],
InfoLookup[PlexTrack],
):
"""A collection of all tracks in a Plex library section.

Expand Down Expand Up @@ -256,3 +257,36 @@ def find_by_ids(
return track

return None

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

def find_by_info(self, info: TrackInfo) -> Iterable[PlexTrack]:
"""Find Plex tracks matching the given metadata.

Raises
------
ValueError
If none of ``title``, ``artists`` or ``albums`` is provided.
"""
title = info.get("title")
artists = info.get("artists") or []
albums = info.get("albums") or []
if not (title or artists or albums):
raise ValueError("Provide at least one of artist, album, or title.")

if self._fetched and self._tracks is not None:
return [
PlexTrack(track.data)
for track in self._tracks
if matches_track_info(track.data, info)
]

return [
PlexTrack(track)
for track in self.api.track.fetch_tracks_by_info(
section_id=self.id,
title=title,
artist=artists[0] if artists else None,
album=albums[0] if albums else None,
)
]
1 change: 1 addition & 0 deletions tests/services/plex/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ def mock_plex_api() -> Mock:
# Mock track methods
mock_api.track = Mock()
mock_api.track.fetch_tracks = Mock(return_value=[])
mock_api.track.fetch_tracks_by_info = Mock(return_value=[])

# Mock machine_id
mock_api.machine_id = "mock-machine-id"
Expand Down
91 changes: 76 additions & 15 deletions tests/services/plex/test_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,31 +85,92 @@ def unknown_playlists(self) -> list[tuple[str, str]]:

def test_preload(self):
"""Test that preloading the library collection works."""
library_collection = next(iter(self.create_collection()))
assert isinstance(library_collection, PlexLibrary)
library_collection.preload()
assert library_collection._fetched is True, (
library = self.collection
assert isinstance(library, PlexLibrary)
library.preload()
assert library._fetched is True, (
"Library collection should be marked as fetched after preload()"
)
assert library_collection._tracks is not None, (
assert library._tracks is not None, (
"Library collection should have tracks loaded after preload()"
)

tracks = list(library_collection.tracks)
tracks = list(library.tracks)
assert len(tracks) > 0, "Library collection should yield tracks after preload()"

def test_locations_property(self):
"""Test that the locations property returns the expected results."""
for library_collection in self.create_collection():
locations = library_collection.locations
assert isinstance(locations, Iterable), "Locations should be iterable"
assert len(list(locations)) > 0, "Locations should not be empty"
assert all(isinstance(loc, Path) for loc in locations), (
"All locations should be Path instances"
)
locations = self.collection.locations
assert isinstance(locations, Iterable), "Locations should be iterable"
assert len(list(locations)) > 0, "Locations should not be empty"
assert all(isinstance(loc, Path) for loc in locations), (
"All locations should be Path instances"
)

def test_get_playlist_raise(self):
"""Get playlist via path not allowed."""
with pytest.raises(ValueError):
for library_collection in self.create_collection():
library_collection.get_playlist(name="foo", id=121)
self.collection.get_playlist(name="foo", id=121)

@pytest.mark.parametrize(
("info", "expected_titles", "expected_call"),
[
(
{
"title": "Test Track",
"artists": ["Test Original Title"],
"albums": ["Test Album"],
},
["Test Track"],
{
"title": "Test Track",
"artist": "Test Original Title",
"album": "Test Album",
},
),
(
{"title": "Test Track", "artists": ["Test Artist"]},
["Test Track"],
{"title": "Test Track", "artist": "Test Artist", "album": None},
),
(
{"artists": ["Test Artist"]},
["Test Track"],
{"title": None, "artist": "Test Artist", "album": None},
),
],
)
def test_find_by_info(self, info, expected_titles, expected_call):
"""Find tracks through the server-side media query filter."""
library = self.collection
library.api.track.fetch_tracks_by_info.return_value = [
library.api.track.fetch_tracks.return_value[0]
]

tracks = list(library.find_by_info(info))

assert [track.title for track in tracks] == expected_titles
library.api.track.fetch_tracks_by_info.assert_called_once_with(
section_id=library.id, **expected_call
)

@pytest.mark.parametrize(
("info", "expected_titles"),
[
({"title": "Test Track", "albums": ["Test Album"]}, ["Test Track"]),
({"title": "Test Track", "artists": ["Someone Else"]}, []),
],
)
def test_find_by_info_uses_cached_tracks(self, info, expected_titles):
"""After iterating, the in-memory tracks are matched without a request."""
library = self.collection
library.preload()

tracks = list(library.find_by_info(info))

assert [track.title for track in tracks] == expected_titles
library.api.track.fetch_tracks_by_info.assert_not_called()

def test_find_by_info_requires_metadata(self):
with pytest.raises(ValueError, match="at least one"):
self.collection.find_by_info({})
Loading