From 67fc1a04f0f4877f088f8ac6ddfb7052a4a46d00 Mon Sep 17 00:00:00 2001 From: Sebastian Mohr Date: Tue, 22 Sep 2026 23:03:17 +0200 Subject: [PATCH 01/11] Moved config into cli layer. --- plistsync/__init__.py | 3 +- plistsync/cli/app.py | 4 +- plistsync/cli/commands/config.py | 2 +- plistsync/{ => cli}/config.py | 176 +++++++++++------------------ plistsync/core/__init__.py | 5 + plistsync/core/config.py | 38 +++++++ plistsync/errors.py | 7 +- plistsync/logger.py | 36 ++++-- plistsync/services/beets/config.py | 2 +- plistsync/utils/__init__.py | 14 --- tests/abc/playlist.py | 17 ++- tests/cli/test_auth.py | 6 +- tests/conftest.py | 1 - tests/core/test_auth.py | 2 +- tests/test_config.py | 30 ++--- tests/test_logger.py | 4 +- 16 files changed, 173 insertions(+), 174 deletions(-) rename plistsync/{ => cli}/config.py (62%) create mode 100644 plistsync/core/config.py diff --git a/plistsync/__init__.py b/plistsync/__init__.py index 935f1a70..52856794 100644 --- a/plistsync/__init__.py +++ b/plistsync/__init__.py @@ -1,9 +1,8 @@ """Toolbox for transferring, converting and matching music collections.""" -from . import config, core, logger, services +from . import core, logger, services __all__ = [ - "config", "core", "logger", "services", diff --git a/plistsync/cli/app.py b/plistsync/cli/app.py index 41899285..9514f4a0 100644 --- a/plistsync/cli/app.py +++ b/plistsync/cli/app.py @@ -10,12 +10,12 @@ from typer.core import TyperGroup from typer.main import get_group -from plistsync.config import Config from plistsync.logger import basic_logging_handler, init_logging, log from plistsync.services import ServiceLoader from .commands.config import config_app from .commands.sync import sync_app +from .config import Config from .context import ServiceContext from .service_commands import cli_service_factory @@ -26,7 +26,7 @@ # signatures must use those types rather than the standalone click package. from typer._click import Command, Context - from plistsync.config import LoggingConfig + from plistsync.logger import LoggingConfig from plistsync.services import Service diff --git a/plistsync/cli/commands/config.py b/plistsync/cli/commands/config.py index 956342d4..bccc8f21 100644 --- a/plistsync/cli/commands/config.py +++ b/plistsync/cli/commands/config.py @@ -2,6 +2,6 @@ from eyconf.cli import create_config_cli -from plistsync.config import Config +from plistsync.cli.config import Config config_app = create_config_cli(Config) diff --git a/plistsync/config.py b/plistsync/cli/config.py similarity index 62% rename from plistsync/config.py rename to plistsync/cli/config.py index 85255730..2b861409 100644 --- a/plistsync/config.py +++ b/plistsync/cli/config.py @@ -1,106 +1,49 @@ -"""Plistsync configuration management using YAML files. +"""YAML configuration management for the plistsync CLI. -We use the `eyconf` library to handle configuration loading and validation. -For more information see `EYConf `_. +Uses the ``eyconf`` library to load and validate the configuration file. The +plain dataclasses live in :mod:`plistsync.core.config` and +:mod:`plistsync.logger`; this module owns everything that is specific to the +CLI: file locations and the disk-backed loading. """ from __future__ import annotations import os -from abc import ABC from dataclasses import dataclass, field, make_dataclass from functools import cache from pathlib import Path -from typing import Annotated, Literal, Self +from typing import Annotated, TypeVar from eyconf import EYConf from eyconf.decorators import allow_additional from platformdirs import user_config_dir -from plistsync.logger import log +from plistsync.core.config import ServiceConfig +from plistsync.logger import LoggingConfig, log from plistsync.services import ServiceLoader -from plistsync.services.registry import Registry -# ---------------------------------------------------------------------------- # -# Schema building-block # -# ---------------------------------------------------------------------------- # - - -@dataclass -class ServiceConfig(ABC, Registry): - """Base class for service configurations. - - Classes that inherit from this class will automatically be included in the config - schema and can be validated/used. - """ - - @classmethod - def get(cls) -> Self: - """Get the service config instance from the global config. - - Convenience classmethod so that callers can write - ``PlexConfig.get()`` instead of manually plumbing the - singleton :class:`Config` instance. - """ - config: Config = Config() - - for service_name, config_classes in cls.registry().items(): - if cls in config_classes: - service_config = config.get_service_config(service_name) - return service_config # type: ignore[return-value] - - raise ValueError(f"Service config {cls.__name__} is not registered.") - - @property - def token_path(self) -> Path: - return Config.get_dir() / f"{self.service().lower()}_token.json" - - -@dataclass -class LoggingConfig: - level: Annotated[ - Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL", "NOTSET"], - "Log level to set when `enabled=True` (one of: DEBUG, INFO, WARNING, ERROR," - "CRITICAL, NOTSET); INFO is recommended for production, DEBUG is useful for " - "troubleshooting.", - ] = field(default="INFO") - handler: Annotated[ - Literal["basic", "rich"], - "Logging backend to initialize when `enabled=True`: 'basic' uses standard " - "library logging with plain text output to stderr, while 'rich' uses " - "RichHandler for nicer console formatting (and richer tracebacks if enabled).", - ] = field(default="rich") +C = TypeVar("C", bound=ServiceConfig) @dataclass class BaseConfigSchema: """The configuration schema for plistsync. - The static fields (``logging``, ``redirect_port``) are always present. The ``services`` field is dynamically populated at runtime from registered - :class:`ServiceConfig` subclasses. The schema is reconstructed — and the - configuration reloaded — every time a new service is first accessed. + :class:`ServiceConfig` subclasses. The schema is reconstructed and the + configuration reloaded every time a new service is first accessed. This class serves as the type-hint base so that ``config.data.logging`` - and ``config.data.redirect_port`` are properly typed. The - ``services: dict[str, ServiceConfig]`` annotation is a placeholder for - type-checkers; at runtime the field is overridden by a dynamically-built - dataclass with one named field per service (e.g. ``plex: PlexConfig | None``). + is properly typed. The ``services: dict[str, ServiceConfig]`` annotation is + a placeholder for type-checkers; at runtime the field is overridden by a + dynamically-built dataclass with one named field per service (e.g. + ``plex: PlexConfig | None``). """ logging: LoggingConfig = field(default_factory=LoggingConfig) - redirect_port: Annotated[int, "The port used for authentication callbacks"] = field( - default=5001 - ) services: dict[str, ServiceConfig] = field(default_factory=dict) -# ---------------------------------------------------------------------------- # -# Config class # -# ---------------------------------------------------------------------------- # -# Uses the eyconf library to handle configuration - - class Config(EYConf[BaseConfigSchema]): """Plistsync configuration class. @@ -112,15 +55,42 @@ class Config(EYConf[BaseConfigSchema]): Any service that cannot be imported (e.g. missing optional dependency) is silently ignored. - Type hints for static fields (``logging``, ``redirect_port``) come - from :class:`BaseConfigSchema`. The ``services`` section is built - dynamically and is therefore typed as ``Any``. + The ``services`` section is built dynamically and is therefore typed as ``Any``. """ + @staticmethod + @cache + def get_dir() -> Path: + """Return the path to the plistsync config directory. + + The configuration file and stored authentication tokens live here. + We check if the following folders exist to determine the config + directory: + + 1. PSYNC_CONFIG_DIR environment variable + 2. OS-specific global config directory + """ + if env_dir := os.getenv("PSYNC_CONFIG_DIR"): + path = Path(env_dir) + else: + path = Path(user_config_dir("plistsync", appauthor=False)) + + path.mkdir(parents=True, exist_ok=True) + return path.resolve() + + @staticmethod + def get_file() -> Path: + """Return the path to the configuration file. + + Overrides the eyconf default so the config lives in the plistsync + config directory. Called by eyconf during instantiation. + """ + return Config.get_dir() / "config.yaml" + # ---------- instantiation ------------------------------------------------- def __init__(self, preload_services: bool = False) -> None: - log.debug(f"Using config dir: {self.get_dir()}") + log.debug(f"Using config dir: {Config.get_dir()}") if preload_services: log.debug("Preloading all discoverable services...") @@ -128,12 +98,6 @@ def __init__(self, preload_services: bool = False) -> None: super().__init__(self._build_schema()) - # ------------------------------ Config helpers ------------------------------ # - - @property - def redirect_port(self) -> int: - return self.data.redirect_port - # ------------------------------ Dynamic schema ------------------------------ # # To allow lazy loading our config from different services we need # to be able to dynamically build our schema @@ -199,6 +163,23 @@ class ServiceConfig namespace={"__module__": cls.__module__}, ) + def get_config_for(self, config_cls: type[C]) -> C: + """Get the config instance for a service config class. + + Convenience for callers that know the config class but not the + service name. + + Raises + ------ + ValueError + If the config class is not registered. + """ + for service_name, config_classes in ServiceConfig.registry().items(): + if config_cls in config_classes: + return self.get_service_config(service_name) # type: ignore[return-value] + + raise ValueError(f"Service config {config_cls.__name__} is not registered.") + def get_service_config(self, service_name: str) -> ServiceConfig: """Get the service config instance for a given service name. @@ -261,39 +242,8 @@ def default_yaml(self): self._schema = self._build_schema() return super().default_yaml() - # ---------------------- Overwrites for config location ---------------------- # - # Eyconf uses the get_file method but we also add a get_dir as we allow storing - # additional files in the main config dir - - @staticmethod - @cache - def get_dir() -> Path: - """Get the path to the config directory. - - We check if the following folders exist to - determine the config directory: - - 1. PSYCNC_CONFIG_DIR environment variable - 2. OS-specific global config directory - """ - if env_dir := os.getenv("PSYNC_CONFIG_DIR"): - path = Path(env_dir) - else: - path = Path(user_config_dir("plistsync", appauthor=False)) - - path.mkdir(parents=True, exist_ok=True) - return path.resolve() - - @staticmethod - def get_file() -> Path: - """Get OS-specific global config directory.""" - dir = Config.get_dir() - return dir / "config.yaml" - __all__ = [ "BaseConfigSchema", "Config", - "LoggingConfig", - "ServiceConfig", ] diff --git a/plistsync/core/__init__.py b/plistsync/core/__init__.py index 95946e8e..4453e97a 100644 --- a/plistsync/core/__init__.py +++ b/plistsync/core/__init__.py @@ -6,7 +6,9 @@ and path rewriting. """ +from .auth import AuthProvider, Interaction from .collection import Collection, Library +from .config import ServiceConfig from .ids import PlaylistID, TrackID from .matching import Matches from .playlist import Playlist, ServicePlaylist @@ -14,12 +16,15 @@ from .track import Track, TrackInfo __all__ = [ + "AuthProvider", "Collection", + "Interaction", "Library", "Matches", "PathRewrite", "Playlist", "PlaylistID", + "ServiceConfig", "ServicePlaylist", "Track", "TrackID", diff --git a/plistsync/core/config.py b/plistsync/core/config.py new file mode 100644 index 00000000..31aba10a --- /dev/null +++ b/plistsync/core/config.py @@ -0,0 +1,38 @@ +"""Service configuration base classes. + +Defines :class:`ServiceConfig`, the dataclass base that services subclass to +declare their settings. Library consumers construct these in code; the CLI +loads them from the YAML configuration file (see :mod:`plistsync.cli.config`). +""" + +from __future__ import annotations + +from abc import ABC +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from plistsync.services.registry import Registry + +if TYPE_CHECKING: + from pathlib import Path + + +@dataclass +class ServiceConfig(ABC, Registry): + """Base class for service configurations. + + Classes that inherit from this class will automatically be included in the + CLI config schema and can be validated/used. + """ + + @property + def token_path(self) -> Path: + """Path to the stored authentication token for this service. + + Token storage is a plistsync-wide convention, but the config directory + itself is resolved by the CLI, which is why the import is lazy. A bit + inconsistent but the best I could come up with right now! + """ + from plistsync.cli.config import Config + + return Config.get_dir() / f"{self.service().lower()}_token.json" diff --git a/plistsync/errors.py b/plistsync/errors.py index b3113a9f..46dfbe15 100644 --- a/plistsync/errors.py +++ b/plistsync/errors.py @@ -1,10 +1,9 @@ import importlib.util -from eyconf.validation import ConfigurationError, MultiConfigurationError - __all__ = [ - "ConfigurationError", - "MultiConfigurationError", + "AuthenticationError", + "DependencyError", + "HowTheForkDidYouEndUpHereError", ] diff --git a/plistsync/logger.py b/plistsync/logger.py index 531da7ea..122d8484 100644 --- a/plistsync/logger.py +++ b/plistsync/logger.py @@ -1,27 +1,35 @@ +"""Logging setup helpers for plistsync.""" + from __future__ import annotations import logging -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from plistsync.config import LoggingConfig +from dataclasses import dataclass, field +from typing import Annotated, Literal log = logging.getLogger("plistsync") -def _parse_log_level(level: str | int) -> int: - if isinstance(level, int): - return level - return logging.getLevelNamesMapping().get(level.upper(), logging.INFO) +@dataclass +class LoggingConfig: + level: Annotated[ + Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL", "NOTSET"], + "Log level to set when `enabled=True` (one of: DEBUG, INFO, WARNING, ERROR," + "CRITICAL, NOTSET); INFO is recommended for production, DEBUG is useful for " + "troubleshooting.", + ] = field(default="INFO") + handler: Annotated[ + Literal["basic", "rich"], + "Logging backend to initialize when `enabled=True`: 'basic' uses standard " + "library logging with plain text output to stderr, while 'rich' uses " + "RichHandler for nicer console formatting (and richer tracebacks if enabled).", + ] = field(default="rich") def init_logging( config: LoggingConfig | None = None, log_level_offset: int | None = None, ) -> None: - """Initialize plistsync logging from config. Call from CLI/app, not at import.""" - from plistsync.config import LoggingConfig - + """Initialize plistsync logging from config.""" logging_config = config or LoggingConfig() # set level of log from config or use overwrite @@ -102,3 +110,9 @@ def rich_logging_handler( handler.setFormatter(logging.Formatter("%(message)s")) handler.name = "rich" return handler + + +def _parse_log_level(level: str | int) -> int: + if isinstance(level, int): + return level + return logging.getLevelNamesMapping().get(level.upper(), logging.INFO) diff --git a/plistsync/services/beets/config.py b/plistsync/services/beets/config.py index 8198998b..c6cfe31f 100644 --- a/plistsync/services/beets/config.py +++ b/plistsync/services/beets/config.py @@ -1,6 +1,6 @@ from dataclasses import dataclass, field -from plistsync.config import ServiceConfig +from plistsync.core.config import ServiceConfig @dataclass diff --git a/plistsync/utils/__init__.py b/plistsync/utils/__init__.py index 477dfd6c..9f22a1a3 100644 --- a/plistsync/utils/__init__.py +++ b/plistsync/utils/__init__.py @@ -2,8 +2,6 @@ import dataclasses import json -import os -import pathlib import re import urllib.parse from typing import TYPE_CHECKING, TypeVar @@ -46,18 +44,6 @@ def build_url(base_url: str, params: dict) -> str: return url -def get_config_dir() -> pathlib.Path: - """Get the configuration directory. - - Returns - ------- - str: The configuration directory. - """ - o = os.getenv("PSYNC_CONFIG_DIR", "./config") - pathlib.Path(o).mkdir(parents=True) - return pathlib.Path(o).resolve() - - def camel_to_snake(text: str) -> str: """Convert camelCase to snake_case.""" s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", text) diff --git a/tests/abc/playlist.py b/tests/abc/playlist.py index a3186410..9c0b0de5 100644 --- a/tests/abc/playlist.py +++ b/tests/abc/playlist.py @@ -1,7 +1,9 @@ from __future__ import annotations from abc import ABC, abstractmethod from functools import wraps -from typing import Any, ClassVar, ParamSpec, TypeVar, TYPE_CHECKING +from typing import Any, ClassVar, Generic, ParamSpec, TYPE_CHECKING + +from typing_extensions import TypeVar from unittest.mock import ANY, Mock import pytest @@ -13,15 +15,20 @@ if TYPE_CHECKING: from collections.abc import Callable + from plistsync.core.config import ServiceConfig from plistsync.core.playlist import ( MultiRequestServicePlaylist, Playlist, ServicePlaylist, ) + from plistsync.core.track import Track P = ParamSpec("P") R = TypeVar("R") +T = TypeVar("T", bound="Track") +C = TypeVar("C", bound="ServiceConfig | None", default="ServiceConfig | None") +"""Track and service config type of the playlist under test.""" def requires_feature(feature: str) -> Callable[[Callable[P, R]], Callable[P, R]]: @@ -140,9 +147,9 @@ def test_get_snapshot(self, playlist: Playlist) -> None: assert id(getattr(playlist, key)) != id(getattr(snapshot, key)) -class TestServicePlaylistBase(TestPlaylistBase, ABC): +class TestServicePlaylistBase(TestPlaylistBase, ABC, Generic[T, C]): @abstractmethod - def create_playlist(self) -> ServicePlaylist: + def create_playlist(self) -> ServicePlaylist[T, C]: """Create a playlist. FIXME: Temporary until we unify the playlist init! @@ -201,9 +208,9 @@ def test_remote_edit_rollback(self, playlist: ServicePlaylist): playlist._remote_commit.assert_not_called() -class TestMultiRequestServicePlaylistBase(TestServicePlaylistBase, ABC): +class TestMultiRequestServicePlaylistBase(TestServicePlaylistBase[T, C], ABC): @abstractmethod - def create_playlist(self) -> MultiRequestServicePlaylist: + def create_playlist(self) -> MultiRequestServicePlaylist[T, C]: """Create a playlist. FIXME: Temporary until we unify the playlist init! diff --git a/tests/cli/test_auth.py b/tests/cli/test_auth.py index 9685e1e7..817f52da 100644 --- a/tests/cli/test_auth.py +++ b/tests/cli/test_auth.py @@ -12,8 +12,9 @@ from typer._click._compat import strip_ansi from typer.main import get_group +from plistsync.cli.config import Config from plistsync.cli.service_commands.auth import CLIInteraction, RawRedirectHandler -from plistsync.config import Config, ServiceConfig +from plistsync.core.config import ServiceConfig from plistsync.core.auth import AuthProvider from plistsync.errors import AuthenticationError, HowTheForkDidYouEndUpHereError from plistsync.services import Service, ServiceLoader @@ -54,7 +55,8 @@ class FakeConfig(ServiceConfig, service="fake"): valid, since an empty service section is parsed as ``None``. """ - redirect_port: int = 5001 + fake_option: str = "default" + # ``__module__`` must be set after the class body: ``@dataclass`` resolves diff --git a/tests/conftest.py b/tests/conftest.py index 2403d44e..66ef7dcf 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -19,7 +19,6 @@ def plist_config(tmpdir_factory): f""" logging: level: DEBUG - redirect_port: 5001 services: beets: enabled: true diff --git a/tests/core/test_auth.py b/tests/core/test_auth.py index ec2d28b8..1b384d74 100644 --- a/tests/core/test_auth.py +++ b/tests/core/test_auth.py @@ -13,7 +13,7 @@ import requests from requests_oauth2client import BearerToken -from plistsync.config import ServiceConfig +from plistsync.core.config import ServiceConfig from plistsync.core.auth import AuthProvider, OAuth2Provider from plistsync.errors import AuthenticationError from plistsync.utils.auth.bearer_token import Oauth2Token, Token diff --git a/tests/test_config.py b/tests/test_config.py index 90aec6ed..ed24d57d 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -3,11 +3,11 @@ import sys from unittest.mock import MagicMock, patch import pytest -import os import yaml from importlib.metadata import entry_points from importlib.util import find_spec -from plistsync.config import Config, ServiceConfig +from plistsync.cli.config import Config +from plistsync.core.config import ServiceConfig from plistsync.services import ServiceLoader from typing import TYPE_CHECKING @@ -16,14 +16,15 @@ @pytest.fixture(autouse=True) -def temp_config_file(tmp_path): +def temp_config_file(tmp_path, monkeypatch): config_file = tmp_path / "config.yaml" # Pre-seed a minimal valid config so that Config() loads it config_file.write_text("logging:\n level: INFO\n") - os.environ["PSYNC_CONFIG_DIR"] = str(tmp_path) + monkeypatch.setenv("PSYNC_CONFIG_DIR", str(tmp_path)) # The first get_dir() call is cached for the whole process Config.get_dir.cache_clear() - return config_file, tmp_path + yield config_file, tmp_path + Config.get_dir.cache_clear() def _reload_service_configs() -> None: @@ -104,16 +105,18 @@ def test_default_config_file_includes_service(self, temp_config_file): assert "my_option" in content def test_get_returns_config(self): - """ServiceConfig subclass can retrieve its own instance from Config.""" - cfg = self.MyConfig.get() + """ServiceConfig subclasses can retrieve their instance from Config.""" + cfg = Config().get_config_for(self.MyConfig) assert isinstance(cfg, self.MyConfig) assert cfg.my_option == "default_value" def test_get_raises_when_not_registered(self): - """ServiceConfig.get() raises ValueError if the class is not registered.""" - with patch.dict("plistsync.config.ServiceConfig._REGISTRY", {}, clear=True): + """get_config_for raises ValueError if the class is not registered.""" + with patch.dict( + "plistsync.core.config.ServiceConfig._REGISTRY", {}, clear=True + ): with pytest.raises(ValueError, match="is not registered"): - TestServiceConfig.MyConfig.get() + Config().get_config_for(TestServiceConfig.MyConfig) class TestConfigDirectory: @@ -128,9 +131,9 @@ def setup_mocks(self, tmp_path, monkeypatch): self.global_config_dir = tmp_path / "user_config_dir" # Store patches as instance variables - cwd_patcher = patch("plistsync.config.Path.cwd", return_value=cwd_dir) + cwd_patcher = patch("plistsync.cli.config.Path.cwd", return_value=cwd_dir) user_config_patcher = patch( - "plistsync.config.user_config_dir", + "plistsync.cli.config.user_config_dir", return_value=self.global_config_dir, ) @@ -249,9 +252,6 @@ def test_preload_services_calls_service_loader(self): Config(preload_services=True) mock_all.assert_called_once() - def test_redirect_port_default(self): - assert Config().redirect_port == 5001 - class TestGetServiceConfigSlowPath: """The slow path of get_service_config (service not yet in the schema).""" diff --git a/tests/test_logger.py b/tests/test_logger.py index dca6130e..2e347d78 100644 --- a/tests/test_logger.py +++ b/tests/test_logger.py @@ -57,7 +57,7 @@ def test_init_logging_no_config_no_overwrite(self): @pytest.mark.parametrize("handler_type", ["basic", "rich"]) def test_init_logging_with_handler(self, handler_type): - from plistsync.config import LoggingConfig + from plistsync.logger import LoggingConfig logger.log.handlers.clear() config = LoggingConfig(handler=handler_type) @@ -65,7 +65,7 @@ def test_init_logging_with_handler(self, handler_type): assert logging.root.handlers def test_init_logging_debug_log(self, monkeypatch): - from plistsync.config import LoggingConfig + from plistsync.logger import LoggingConfig config = LoggingConfig(handler="basic") monkeypatch.setattr( From c8d53075c28d7a73f718ab3bdf579fc997224639 Mon Sep 17 00:00:00 2001 From: Sebastian Mohr Date: Tue, 22 Sep 2026 23:21:41 +0200 Subject: [PATCH 02/11] Added from_config method to library. Needed to properly separate from yaml config loading layer. --- plistsync/cli/context.py | 26 +++++++++++++++++++++----- plistsync/core/auth.py | 4 +++- plistsync/core/collection.py | 20 +++++++++++++++----- plistsync/core/diff.py | 2 ++ plistsync/core/ids.py | 2 ++ plistsync/core/playlist.py | 8 ++++---- plistsync/services/__init__.py | 4 ++-- tests/cli/conftest.py | 2 +- tests/core/mock_collections.py | 13 ++++++++++++- 9 files changed, 62 insertions(+), 19 deletions(-) diff --git a/plistsync/cli/context.py b/plistsync/cli/context.py index 1eda3bee..02376aff 100644 --- a/plistsync/cli/context.py +++ b/plistsync/cli/context.py @@ -4,13 +4,13 @@ from dataclasses import dataclass from functools import cached_property -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, cast import typer if TYPE_CHECKING: - from plistsync.config import ServiceConfig - from plistsync.core import Library + from plistsync.core import Library, ServicePlaylist, Track + from plistsync.core.config import ServiceConfig from plistsync.services import Service @@ -23,14 +23,30 @@ class ServiceContext: @cached_property def library(self) -> Library | None: """Instantiate the service's library, if it supports one.""" + from plistsync.cli.config import Config + library_cls = self.service.library() - return library_cls() if library_cls is not None else None + if library_cls is None: + return None + + config_cls = self.service.config() + config = Config().get_config_for(config_cls) if config_cls is not None else None + + # The registry pairs every library class with its service config class; + # the erased ``type[Library]`` view cannot express that pairing. + factory = cast( + "type[Library[Track, ServicePlaylist, ServiceConfig | None]]", + library_cls, + ) + return cast("Library", factory.from_config(config)) @cached_property def config(self) -> ServiceConfig | None: """Resolve the service's config, if it supports one.""" + from plistsync.cli.config import Config + config_cls = self.service.config() - return config_cls.get() if config_cls is not None else None + return Config().get_config_for(config_cls) if config_cls is not None else None @property def name(self) -> str: diff --git a/plistsync/core/auth.py b/plistsync/core/auth.py index dcc0240e..70610a5a 100644 --- a/plistsync/core/auth.py +++ b/plistsync/core/auth.py @@ -1,3 +1,5 @@ +"""Authentication providers that obtain initial tokens for plistsync services.""" + from __future__ import annotations import base64 @@ -21,7 +23,7 @@ if TYPE_CHECKING: from pathlib import Path - from plistsync.config import ServiceConfig + from plistsync.core.config import ServiceConfig class Interaction(Protocol): diff --git a/plistsync/core/collection.py b/plistsync/core/collection.py index 27395d0c..f5b63031 100644 --- a/plistsync/core/collection.py +++ b/plistsync/core/collection.py @@ -51,6 +51,7 @@ class MyTrackCollection(Collection, IDLookup, TrackStream): Generic, ParamSpec, Protocol, + Self, overload, runtime_checkable, ) @@ -70,15 +71,15 @@ class MyTrackCollection(Collection, IDLookup, TrackStream): if TYPE_CHECKING: from collections.abc import Callable, Iterable, Sequence + from .config import ServiceConfig from .ids import PlaylistID, TrackID from .matching import Similarity - from .playlist import ServicePlaylist + from .playlist import Playlist, ServicePlaylist from .track import TrackInfo -Plist = TypeVar( - "Plist", bound="ServicePlaylist", default="ServicePlaylist", covariant=True -) +Plist = TypeVar("Plist", bound="Playlist", default="ServicePlaylist", covariant=True) +C = TypeVar("C", bound="ServiceConfig | None", default=None) @runtime_checkable @@ -533,7 +534,7 @@ def record(idx: int, found_track, similarity: float) -> None: ) -class Library(Generic[T, Plist], Collection[T], ABC, Registry): +class Library(Generic[T, Plist, C], Collection[T], ABC, Registry): """Represents a collection of tracks in a library with playlist management. This class serves as a base for library collections across diverse services. @@ -541,6 +542,15 @@ class Library(Generic[T, Plist], Collection[T], ABC, Registry): to implement its specifics. """ + @classmethod + @abstractmethod + def from_config(cls, config: C) -> Self: + """Create a library from its service config. + + ``config`` is ``None`` for services that have no configuration. + """ + ... + @property def name(self) -> str: """Name of the library, typically the service name.""" diff --git a/plistsync/core/diff.py b/plistsync/core/diff.py index b93cb0f7..4eb39836 100644 --- a/plistsync/core/diff.py +++ b/plistsync/core/diff.py @@ -1,3 +1,5 @@ +"""Diffing operations for turning two playlist states into a list of edits.""" + from __future__ import annotations import bisect diff --git a/plistsync/core/ids.py b/plistsync/core/ids.py index ea7e17d3..f5a8a5a3 100644 --- a/plistsync/core/ids.py +++ b/plistsync/core/ids.py @@ -1,3 +1,5 @@ +"""Track and playlist identifiers shared across plistsync services.""" + from __future__ import annotations import re diff --git a/plistsync/core/playlist.py b/plistsync/core/playlist.py index 3d930a05..5a6c5363 100644 --- a/plistsync/core/playlist.py +++ b/plistsync/core/playlist.py @@ -29,7 +29,7 @@ class MyPlaylistCollection(PlaylistCollection): from plistsync.services.registry import Registry -from .collection import Collection, TrackStream +from .collection import C, Collection, TrackStream from .diff import DeleteOp, InsertOp, MoveOp, batch_consecutive, list_diff from .track import OfflineTrack, Track @@ -171,7 +171,7 @@ def __len__(self) -> int: return len(self.tracks) -class ServicePlaylist(Generic[T], Playlist[T], ABC): +class ServicePlaylist(Generic[T, C], Playlist[T], ABC): """Abstract base class for playlists synchronized with music services. Extends `Playlist` with methods to manage the lifecycle and state synchronization @@ -186,7 +186,7 @@ class ServicePlaylist(Generic[T], Playlist[T], ABC): - `update()` - bulk update by comparing remote and local snapshots """ - library: Library[Track, Self] + library: Library[Track, Self, C] # --------------------------- Required (protocol) ---------------------------- # @@ -268,7 +268,7 @@ def edit(self): raise -class MultiRequestServicePlaylist(ServicePlaylist[T], ABC): +class MultiRequestServicePlaylist(ServicePlaylist[T, C], ABC): """Playlist for APIs where modifications have to be split into mulitple requests. Subclass this and implement: diff --git a/plistsync/services/__init__.py b/plistsync/services/__init__.py index bf0b8553..9e7a6422 100644 --- a/plistsync/services/__init__.py +++ b/plistsync/services/__init__.py @@ -15,9 +15,9 @@ if TYPE_CHECKING: from collections.abc import Sequence - from plistsync.config import ServiceConfig from plistsync.core import Library, Playlist, Track from plistsync.core.auth import AuthProvider + from plistsync.core.config import ServiceConfig from plistsync.core.ids import PlaylistID, TrackID @@ -39,7 +39,7 @@ def name(self) -> str: def config(self) -> type[ServiceConfig] | None: """Return the service config class registered for this service, if any.""" - from plistsync.config import ServiceConfig + from plistsync.core.config import ServiceConfig return ServiceConfig.registry().get(self.name, (None,))[0] diff --git a/tests/cli/conftest.py b/tests/cli/conftest.py index 9b54bae9..7b433724 100644 --- a/tests/cli/conftest.py +++ b/tests/cli/conftest.py @@ -9,7 +9,7 @@ from plistsync.cli import app as plist_app from plistsync.cli.service_commands import cli_service_factory -from plistsync.config import Config +from plistsync.cli.config import Config if TYPE_CHECKING: from collections.abc import Callable diff --git a/tests/core/mock_collections.py b/tests/core/mock_collections.py index f54ba536..ef931ef0 100644 --- a/tests/core/mock_collections.py +++ b/tests/core/mock_collections.py @@ -17,9 +17,10 @@ if TYPE_CHECKING: from collections.abc import Iterable, Iterator - from typing import Any + from typing import Any, Self from plistsync.core import PlaylistID, TrackID + from plistsync.core.config import ServiceConfig from plistsync.core.track import TrackInfo @@ -118,6 +119,11 @@ class MockLibrary( the library before the code under test instantiates it by class. """ + @classmethod + def from_config(cls, config: ServiceConfig | None = None) -> Self: + """Mock libraries ignore the config.""" + return cls() + tracks: ClassVar[list[MockTrack]] = [] """Tracks :meth:`find_by_ids` searches.""" @@ -182,6 +188,11 @@ class MockNoLookupLibrary(Library[MockTrack, MockServicePlaylist], service="test capability-dependent CLI options (e.g. ``--add``) must be hidden. """ + @classmethod + def from_config(cls, config: ServiceConfig | None = None) -> Self: + """Mock libraries ignore the config.""" + return cls() + created: ClassVar[list[MockServicePlaylist]] = [] """Playlists created through :meth:`create_playlist`.""" From 346966226d030e54ca59f93ccc8642017da3cc3b Mon Sep 17 00:00:00 2001 From: Sebastian Mohr Date: Tue, 22 Sep 2026 23:31:36 +0200 Subject: [PATCH 03/11] Aligned plex library with from_config convention. --- plistsync/services/plex/api.py | 41 ++++++++++++---------------- plistsync/services/plex/config.py | 6 ++-- plistsync/services/plex/library.py | 23 +++++++++++++--- plistsync/services/plex/playlist.py | 3 +- tests/services/plex/conftest.py | 12 ++------ tests/services/plex/test_auth.py | 4 ++- tests/services/plex/test_playlist.py | 4 ++- 7 files changed, 51 insertions(+), 42 deletions(-) diff --git a/plistsync/services/plex/api.py b/plistsync/services/plex/api.py index 95819310..cdc5c670 100644 --- a/plistsync/services/plex/api.py +++ b/plistsync/services/plex/api.py @@ -10,12 +10,11 @@ from concurrent.futures import ThreadPoolExecutor, as_completed from functools import cache, cached_property from pathlib import Path -from typing import TYPE_CHECKING, Any, ClassVar +from typing import TYPE_CHECKING, Any, ClassVar, Self from urllib.parse import quote import requests -from plistsync.errors import ConfigurationError from plistsync.logger import log from plistsync.utils.auth.bearer_token import InvalidTokenError, Token, TokenSession from plistsync.utils.session import PlistsyncSession @@ -35,6 +34,7 @@ PlexApiTrackResponse, PlexServerIdentity, ) + from .config import PlexConfig class PlexToken(Token): @@ -110,10 +110,12 @@ def __init__( self.server_url = server_url @classmethod - def from_config(cls): - from .config import PlexConfig + def from_config(cls, config: PlexConfig) -> Self: + """Construct a PlexApiSession from a config. - plex_config = PlexConfig.get() + Loads the stored token unless one is passed in, and resolves the + server URL from `server_url` or by looking up `server_name`. + """ def _resolve_server_name(server_name: str): # we need a temporary session for plex.tv, but later want one that uses the @@ -123,10 +125,10 @@ def _resolve_server_name(server_name: str): "To speed this up, use a server_url in stead of server_name." ) temp_session = cls( - plex_config.app_name, - plex_config.client_identifier, + config.app_name, + config.client_identifier, "https://plex.tv", - PlexToken.from_file(plex_config.token_path), + PlexToken.from_file(config.token_path), ) conns = PlexApi.get_server_connections_for_name(temp_session, server_name) @@ -134,20 +136,16 @@ def _resolve_server_name(server_name: str): # priority of server url sources: server_url: str - if plex_config.server_url: - server_url = plex_config.server_url - elif plex_config.server_name: - server_url = _resolve_server_name(plex_config.server_name) - else: - raise ConfigurationError( - "Specify either plex.server_url or plex.server_name." - ) + if config.server_url: + server_url = config.server_url + elif config.server_name: + server_url = _resolve_server_name(config.server_name) return cls( - plex_config.app_name, - plex_config.client_identifier, + config.app_name, + config.client_identifier, server_url, - PlexToken.from_file(plex_config.token_path), + PlexToken.from_file(config.token_path), ) def _validate_token(self) -> None: @@ -202,10 +200,7 @@ class PlexApi: track: TrackApi converts: ConvertsApi - def __init__(self, session: PlexApiSession | None = None) -> None: - if session is None: - session = PlexApiSession.from_config() - + def __init__(self, session: PlexApiSession) -> None: # create permanent session for remaining requests self.session = session self.playlist = PlaylistApi(self) diff --git a/plistsync/services/plex/config.py b/plistsync/services/plex/config.py index cb1cb9e2..fac82a89 100644 --- a/plistsync/services/plex/config.py +++ b/plistsync/services/plex/config.py @@ -3,7 +3,7 @@ from dataclasses import dataclass, field from typing import Annotated -from plistsync.config import ServiceConfig +from plistsync.core.config import ServiceConfig @dataclass @@ -26,11 +26,11 @@ class PlexConfig(ServiceConfig): redirect_port: Annotated[ int, "The port to use for the local redirect server when authenticating.", - ] = field(default=5001) + ] = field(default=20556) @property def app_name(self) -> str: - return "plistsync-local" + return "plistsync" @property def client_identifier(self) -> str: diff --git a/plistsync/services/plex/library.py b/plistsync/services/plex/library.py index 366f0a9a..a5fea348 100644 --- a/plistsync/services/plex/library.py +++ b/plistsync/services/plex/library.py @@ -12,18 +12,20 @@ from plistsync.logger import log from plistsync.services.plex.playlist import PlexPlaylist, PlexPlaylistID -from .api import PlexApi +from .api import PlexApi, PlexApiSession +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.services.local.track import FileCache class PlexLibrary( - Library[PlexTrack, PlexPlaylist], + Library[PlexTrack, PlexPlaylist, PlexConfig], TrackStream[PlexTrack], IDLookup[PlexTrack], ): @@ -42,17 +44,30 @@ class PlexLibrary( id: int api: PlexApi - def __init__(self, section_name_or_id: str | int = "Music"): + def __init__( + self, + api: PlexApi, + section_name_or_id: str | int = "Music", + ): """Initialize the PlexLibrary from plex given a section id. Parameters ---------- + api : PlexApi + Authenticated Plex API client. section_name_or_id : str | int The Name or ID of the Plex library section to fetch. """ - self.api = PlexApi() + self.api = api self.id = self.api.converts.section_name_to_id(section_name_or_id) + @classmethod + def from_config( + cls, config: PlexConfig, section_name_or_id: str | int = "Music" + ) -> Self: + """Construct a Plex library from a service config.""" + return cls(PlexApi(PlexApiSession.from_config(config)), section_name_or_id) + def preload(self, force_reload=False) -> None: """Preload the collections tracks. diff --git a/plistsync/services/plex/playlist.py b/plistsync/services/plex/playlist.py index ee4e892f..b4efe50e 100644 --- a/plistsync/services/plex/playlist.py +++ b/plistsync/services/plex/playlist.py @@ -11,6 +11,7 @@ ) from plistsync.logger import log +from .config import PlexConfig from .track import PlexTrack if TYPE_CHECKING: @@ -73,7 +74,7 @@ def __int__(self) -> int: return self.id -class PlexPlaylist(MultiRequestServicePlaylist[PlexTrack]): +class PlexPlaylist(MultiRequestServicePlaylist[PlexTrack, PlexConfig]): """ A collection of all tracks in a Plex playlist. diff --git a/tests/services/plex/conftest.py b/tests/services/plex/conftest.py index ff91ee8c..6a0513aa 100644 --- a/tests/services/plex/conftest.py +++ b/tests/services/plex/conftest.py @@ -184,14 +184,8 @@ def mock_plex_api_with_data( @pytest.fixture -def plex_library_collection_mock(monkeypatch, mock_plex_api_with_data): - """Fixture for a PlexLibrary with mocked API.""" +def plex_library_collection_mock(mock_plex_api_with_data): + """Fixture for a PlexLibrary with a mocked API client.""" from plistsync.services.plex import PlexLibrary - # Monkeypatch the PlexApi constructor to return our mock - monkeypatch.setattr( - "plistsync.services.plex.library.PlexApi", - lambda **kwargs: mock_plex_api_with_data, - ) - - return PlexLibrary("Music") + return PlexLibrary(mock_plex_api_with_data, section_name_or_id="Music") diff --git a/tests/services/plex/test_auth.py b/tests/services/plex/test_auth.py index 72860bd3..7da517d8 100644 --- a/tests/services/plex/test_auth.py +++ b/tests/services/plex/test_auth.py @@ -65,7 +65,9 @@ class TestPlexAuth: @pytest.fixture def auth(self) -> PlexAuth: - return PlexAuth(PlexConfig(server_url="http://localhost:32400")) + return PlexAuth( + PlexConfig(server_url="http://localhost:32400", redirect_port=5001) + ) @pytest.fixture def session(self, monkeypatch: pytest.MonkeyPatch) -> MagicMock: diff --git a/tests/services/plex/test_playlist.py b/tests/services/plex/test_playlist.py index fb4ca56b..d1207825 100644 --- a/tests/services/plex/test_playlist.py +++ b/tests/services/plex/test_playlist.py @@ -1,7 +1,9 @@ from __future__ import annotations from unittest.mock import Mock import pytest +from plistsync.services.plex.config import PlexConfig from plistsync.services.plex.playlist import PlexPlaylist, PlexPlaylistID +from plistsync.services.plex.track import PlexTrack from tests.abc.playlist import TestMultiRequestServicePlaylistBase from typing import TYPE_CHECKING @@ -12,7 +14,7 @@ ) -class TestPlexPlaylist(TestMultiRequestServicePlaylistBase): +class TestPlexPlaylist(TestMultiRequestServicePlaylistBase[PlexTrack, PlexConfig]): """Unit tests for the plex playlist collection.""" @pytest.fixture(autouse=True) From 86319bca3d0dbc51d8dc7618df5e326d3f3c5783 Mon Sep 17 00:00:00 2001 From: Sebastian Mohr Date: Tue, 22 Sep 2026 23:36:50 +0200 Subject: [PATCH 04/11] Aligned spotify library with from_config convention. --- plistsync/services/spotify/api.py | 16 +--------------- plistsync/services/spotify/config.py | 2 +- plistsync/services/spotify/library.py | 24 ++++++++++++++++++++---- plistsync/services/spotify/playlist.py | 3 ++- tests/services/spotify/test_playlist.py | 6 +++++- 5 files changed, 29 insertions(+), 22 deletions(-) diff --git a/plistsync/services/spotify/api.py b/plistsync/services/spotify/api.py index 1ed7a707..7cae564a 100644 --- a/plistsync/services/spotify/api.py +++ b/plistsync/services/spotify/api.py @@ -53,17 +53,6 @@ def __init__( self.client_id = client_id self.headers["Accept"] = "application/json" - @classmethod - def from_config(cls): - """Construct a SpotifyApiSession from the config file.""" - from .config import SpotifyConfig - - spotify_config = SpotifyConfig.get() - return cls( - client_id=spotify_config.client_id, - token=Oauth2Token.from_file(spotify_config.token_path), - ) - def _refresh_token(self) -> None: """Validate the spotify token by making a test request. @@ -130,10 +119,7 @@ class SpotifyApi: track: TrackApi user: UserApi - def __init__(self, session: SpotifyApiSession | None = None): - if session is None: - session = SpotifyApiSession.from_config() - + def __init__(self, session: SpotifyApiSession): self.session = session self.playlist = PlaylistApi(self.session, self) self.user = UserApi(self.session, self) diff --git a/plistsync/services/spotify/config.py b/plistsync/services/spotify/config.py index 7cf1528a..8e2865cb 100644 --- a/plistsync/services/spotify/config.py +++ b/plistsync/services/spotify/config.py @@ -1,7 +1,7 @@ from dataclasses import dataclass, field from typing import Annotated -from plistsync.config import ServiceConfig +from plistsync.core.config import ServiceConfig @dataclass diff --git a/plistsync/services/spotify/library.py b/plistsync/services/spotify/library.py index e5b7b583..ec7fb4d3 100644 --- a/plistsync/services/spotify/library.py +++ b/plistsync/services/spotify/library.py @@ -11,19 +11,22 @@ ) from plistsync.core.ids import ISRC, PlaylistID from plistsync.logger import log +from plistsync.utils.auth.bearer_token import Oauth2Token -from .api import SpotifyApi +from .api import SpotifyApi, SpotifyApiSession +from .config import SpotifyConfig from .playlist import SpotifyPlaylist, SpotifyPlaylistID from .track import SpotifyTrack, SpotifyTrackID if TYPE_CHECKING: from collections.abc import Iterable, Sequence + from typing import Self from plistsync.core import TrackID, TrackInfo class SpotifyLibrary( - Library[SpotifyTrack, SpotifyPlaylist], + Library[SpotifyTrack, SpotifyPlaylist, SpotifyConfig], IDLookup[SpotifyTrack], InfoLookup[SpotifyTrack], ): @@ -35,8 +38,21 @@ class SpotifyLibrary( api: SpotifyApi - def __init__(self) -> None: - self.api = SpotifyApi() + def __init__(self, api: SpotifyApi) -> None: + self.api = api + + @classmethod + def from_config(cls, config: SpotifyConfig) -> Self: + """Construct a Spotify library from a service config.""" + + return cls( + SpotifyApi( + SpotifyApiSession( + client_id=config.client_id, + token=Oauth2Token.from_file(config.token_path), + ) + ) + ) # ------------------------ LibraryCollection protocol ------------------------ # diff --git a/plistsync/services/spotify/playlist.py b/plistsync/services/spotify/playlist.py index b1e68a81..f48c0b3e 100644 --- a/plistsync/services/spotify/playlist.py +++ b/plistsync/services/spotify/playlist.py @@ -10,6 +10,7 @@ PlaylistInfo, ) +from .config import SpotifyConfig from .track import SpotifyPlaylistTrack if TYPE_CHECKING: @@ -63,7 +64,7 @@ def __str__(self) -> str: return self.id -class SpotifyPlaylist(MultiRequestServicePlaylist[SpotifyPlaylistTrack]): +class SpotifyPlaylist(MultiRequestServicePlaylist[SpotifyPlaylistTrack, SpotifyConfig]): """A collection representing a spotify playlist.""" library: SpotifyLibrary diff --git a/tests/services/spotify/test_playlist.py b/tests/services/spotify/test_playlist.py index aa7820f4..870294e2 100644 --- a/tests/services/spotify/test_playlist.py +++ b/tests/services/spotify/test_playlist.py @@ -2,7 +2,9 @@ from unittest.mock import Mock import pytest +from plistsync.services.spotify.config import SpotifyConfig from plistsync.services.spotify.playlist import SpotifyPlaylist, SpotifyPlaylistID +from plistsync.services.spotify.track import SpotifyPlaylistTrack from tests.abc.playlist import TestMultiRequestServicePlaylistBase from typing import TYPE_CHECKING @@ -10,7 +12,9 @@ from plistsync.services.spotify.api_types import SpotifyApiPlaylistResponseFull -class TestSpotifyPlaylist(TestMultiRequestServicePlaylistBase): +class TestSpotifyPlaylist( + TestMultiRequestServicePlaylistBase[SpotifyPlaylistTrack, SpotifyConfig] +): """Unit tests for the spotify playlist collection.""" @pytest.fixture(autouse=True) From c2c5d05bd72c60c5ad95655b42f126d2226fc20e Mon Sep 17 00:00:00 2001 From: Sebastian Mohr Date: Tue, 22 Sep 2026 23:39:44 +0200 Subject: [PATCH 05/11] Aligned tidal library with from_config convention. --- plistsync/services/tidal/api.py | 16 +--------------- plistsync/services/tidal/config.py | 2 +- plistsync/services/tidal/library.py | 23 +++++++++++++++++++---- plistsync/services/tidal/playlist.py | 3 ++- tests/services/tidal/test_auth.py | 4 ++-- tests/services/tidal/test_playlist.py | 6 +++++- 6 files changed, 30 insertions(+), 24 deletions(-) diff --git a/plistsync/services/tidal/api.py b/plistsync/services/tidal/api.py index c37e885a..7ba12ad7 100644 --- a/plistsync/services/tidal/api.py +++ b/plistsync/services/tidal/api.py @@ -75,17 +75,6 @@ def __init__( ) self.client_id = client_id - @classmethod - def from_config(cls): - """Initialize a tidal api from configutation file.""" - from .config import TidalConfig - - tidal_config = TidalConfig.get() - return cls( - client_id=tidal_config.client_id, - token=Oauth2Token.from_file(tidal_config.token_path), - ) - def _refresh_token(self) -> None: """Refresh the Tidal token. @@ -295,10 +284,7 @@ class TidalApi: playlist: TidalPlaylistApi user: TidalUserApi - def __init__(self, session: TidalApiSession | None = None): - if session is None: - session = TidalApiSession.from_config() - + def __init__(self, session: TidalApiSession): self.session = session self.tracks = TidalTrackApi(self.session) self.playlist = TidalPlaylistApi(self.session) diff --git a/plistsync/services/tidal/config.py b/plistsync/services/tidal/config.py index d27cba5f..56f9486f 100644 --- a/plistsync/services/tidal/config.py +++ b/plistsync/services/tidal/config.py @@ -1,7 +1,7 @@ from dataclasses import dataclass, field from typing import Annotated -from plistsync.config import ServiceConfig +from plistsync.core.config import ServiceConfig @dataclass diff --git a/plistsync/services/tidal/library.py b/plistsync/services/tidal/library.py index a5066216..82cd96cf 100644 --- a/plistsync/services/tidal/library.py +++ b/plistsync/services/tidal/library.py @@ -10,27 +10,42 @@ ) from plistsync.core.ids import ISRC, PlaylistID from plistsync.logger import log +from plistsync.utils.auth.bearer_token import Oauth2Token -from .api import TidalApi +from .api import TidalApi, TidalApiSession +from .config import TidalConfig from .playlist import TidalPlaylist, TidalPlaylistID from .track import TidalTrack, TidalTrackID if TYPE_CHECKING: from collections.abc import Iterable, Sequence + from typing import Self from plistsync.core import TrackID class TidalLibrary( - Library[TidalTrack, TidalPlaylist], + Library[TidalTrack, TidalPlaylist, TidalConfig], IDLookup[TidalTrack], ): """A collection of Tidal library items.""" api: TidalApi - def __init__(self) -> None: - self.api = TidalApi() + def __init__(self, api: TidalApi) -> None: + self.api = api + + @classmethod + def from_config(cls, config: TidalConfig) -> Self: + """Construct a Tidal library from a service config.""" + return cls( + TidalApi( + TidalApiSession( + client_id=config.client_id, + token=Oauth2Token.from_file(config.token_path), + ) + ) + ) # ------------------------ LibraryCollection protocol ------------------------ # diff --git a/plistsync/services/tidal/playlist.py b/plistsync/services/tidal/playlist.py index 5afab4d6..a32c8ec0 100644 --- a/plistsync/services/tidal/playlist.py +++ b/plistsync/services/tidal/playlist.py @@ -11,6 +11,7 @@ ) from plistsync.logger import log +from .config import TidalConfig from .track import TidalPlaylistTrack if TYPE_CHECKING: @@ -68,7 +69,7 @@ def __str__(self) -> str: return self.id -class TidalPlaylist(MultiRequestServicePlaylist[TidalPlaylistTrack]): +class TidalPlaylist(MultiRequestServicePlaylist[TidalPlaylistTrack, TidalConfig]): library: TidalLibrary data: PlaylistResource diff --git a/tests/services/tidal/test_auth.py b/tests/services/tidal/test_auth.py index c1766b50..1d571fab 100644 --- a/tests/services/tidal/test_auth.py +++ b/tests/services/tidal/test_auth.py @@ -9,7 +9,7 @@ class TestTidalAuth: - """Tidal uses the generic OAuth2 provider with a custom redirect port.""" + """Tidal uses the generic OAuth2 provider.""" @pytest.fixture def auth(self) -> TidalAuth: @@ -20,7 +20,7 @@ def test_registered_with_service(self, auth: TidalAuth) -> None: assert TidalService().auth() is TidalAuth - def test_client_id_and_redirect_uri_come_from_config(self, auth: TidalAuth) -> None: + def test_client_id_and_redirect_uri(self, auth: TidalAuth) -> None: assert auth.client_id() == "my-client" assert auth.redirect_uri() == "http://127.0.0.1:5001" diff --git a/tests/services/tidal/test_playlist.py b/tests/services/tidal/test_playlist.py index 4cd2126e..15026b7e 100644 --- a/tests/services/tidal/test_playlist.py +++ b/tests/services/tidal/test_playlist.py @@ -2,7 +2,9 @@ from unittest.mock import Mock import pytest +from plistsync.services.tidal.config import TidalConfig from plistsync.services.tidal.playlist import TidalPlaylist, TidalPlaylistID +from plistsync.services.tidal.track import TidalPlaylistTrack from tests.abc.playlist import TestMultiRequestServicePlaylistBase from typing import TYPE_CHECKING @@ -10,7 +12,9 @@ from plistsync.services.tidal.api_types import PlaylistResource -class TestsTidalPlaylist(TestMultiRequestServicePlaylistBase): +class TestsTidalPlaylist( + TestMultiRequestServicePlaylistBase[TidalPlaylistTrack, TidalConfig] +): """Unit tests for the tidal playlist collection.""" @pytest.fixture(autouse=True) From ed5cfe306df9f47a708a06c47ac61606093fce0b Mon Sep 17 00:00:00 2001 From: Sebastian Mohr Date: Tue, 22 Sep 2026 23:42:09 +0200 Subject: [PATCH 06/11] Aligned traktor library with from_config convention. --- plistsync/services/traktor/config.py | 2 +- plistsync/services/traktor/library.py | 26 ++++++++++++------------- plistsync/services/traktor/playlist.py | 3 ++- tests/services/traktor/test_playlist.py | 4 +++- 4 files changed, 19 insertions(+), 16 deletions(-) diff --git a/plistsync/services/traktor/config.py b/plistsync/services/traktor/config.py index dcf3faea..10968a2a 100644 --- a/plistsync/services/traktor/config.py +++ b/plistsync/services/traktor/config.py @@ -1,7 +1,7 @@ from dataclasses import dataclass, field from typing import Annotated -from plistsync.config import ServiceConfig +from plistsync.core.config import ServiceConfig @dataclass diff --git a/plistsync/services/traktor/library.py b/plistsync/services/traktor/library.py index 4010a730..6b915cf0 100644 --- a/plistsync/services/traktor/library.py +++ b/plistsync/services/traktor/library.py @@ -19,6 +19,7 @@ if TYPE_CHECKING: from collections.abc import Iterable, Sequence + from typing import Self from uuid import UUID from lxml.etree import _Element, _ElementTree @@ -29,7 +30,7 @@ class NMLLibrary( - Library[NMLTrack, NMLPlaylist], + Library[NMLTrack, NMLPlaylist, TraktorConfig], TrackStream[NMLTrack], IDLookup[NMLTrack], ): @@ -44,22 +45,21 @@ class NMLLibrary( path: Path tree: _ElementTree + backup_before_write: bool - def __init__(self, path: Path | str | None = None): - if path is None: - path = TraktorConfig.get().path - - if isinstance(path, str): - path = Path(path) - - if not path.exists(): - raise FileNotFoundError(f"File {path} does not exist") - + def __init__(self, path: Path | str, backup_before_write: bool = True): self.path = Path(path) - + if not self.path.exists(): + raise FileNotFoundError(f"File {path} does not exist") + self.backup_before_write = backup_before_write # An NML file is a XML file self.tree = etree.parse(self.path) + @classmethod + def from_config(cls, config: TraktorConfig) -> Self: + """Construct a Traktor library from a service config.""" + return cls(Path(config.path), backup_before_write=config.backup_before_write) + def write(self, backup: bool | None = None): """Write changes to NML file. @@ -67,7 +67,7 @@ def write(self, backup: bool | None = None): """ if backup is None: - backup = TraktorConfig.get().backup_before_write + backup = self.backup_before_write if backup: nml_backup = self.path.with_suffix( diff --git a/plistsync/services/traktor/playlist.py b/plistsync/services/traktor/playlist.py index 9c35ca5c..c860dde2 100644 --- a/plistsync/services/traktor/playlist.py +++ b/plistsync/services/traktor/playlist.py @@ -15,6 +15,7 @@ ) from plistsync.logger import log +from .config import TraktorConfig from .path import NMLPath from .track import NMLPlaylistTrack from .utility import ( @@ -83,7 +84,7 @@ def __str__(self) -> str: return str(self.id.hex) # Uses hex in internal repr -class NMLPlaylist(ServicePlaylist[NMLPlaylistTrack], IDLookup): +class NMLPlaylist(ServicePlaylist[NMLPlaylistTrack, TraktorConfig], IDLookup): """A Traktor NML playlist collection. Traktor playlists use file paths as the identifiers. diff --git a/tests/services/traktor/test_playlist.py b/tests/services/traktor/test_playlist.py index 0bb77e17..39b354b6 100644 --- a/tests/services/traktor/test_playlist.py +++ b/tests/services/traktor/test_playlist.py @@ -3,7 +3,9 @@ from uuid import UUID import pytest +from plistsync.services.traktor.config import TraktorConfig from plistsync.services.traktor.playlist import NMLPlaylistID +from plistsync.services.traktor.track import NMLPlaylistTrack from tests.abc.playlist import ( TestServicePlaylistBase, ) @@ -13,7 +15,7 @@ from plistsync.services.traktor import NMLPlaylist, NMLLibrary -class TestsTidalPlaylist(TestServicePlaylistBase): +class TestsTidalPlaylist(TestServicePlaylistBase[NMLPlaylistTrack, TraktorConfig]): """Unit tests for the spotify playlist collection.""" supports_description = False From 850d2f15fbfb6b98da3aed1695188f14487a05c1 Mon Sep 17 00:00:00 2001 From: Sebastian Mohr Date: Wed, 23 Sep 2026 12:13:50 +0200 Subject: [PATCH 07/11] Fixed typing and ruff and test. --- docs/details/advanced/logging.md | 7 +-- examples/community/plex_to_m3u.py | 20 ++++--- .../community/plex_traktor_bidirectional.py | 15 +++-- pyproject.toml | 1 + tests/cli/test_auth.py | 1 - tests/services/test_registry.py | 4 ++ tests/utils/test_session.py | 57 +++++++++++++++---- 7 files changed, 78 insertions(+), 27 deletions(-) diff --git a/docs/details/advanced/logging.md b/docs/details/advanced/logging.md index fca2e636..a931da9b 100644 --- a/docs/details/advanced/logging.md +++ b/docs/details/advanced/logging.md @@ -1,6 +1,6 @@ # Logging -`plistsync` provides a {py:func}`plistsync.logger.init_logging` function that configures logging for the plistsync logger based on a {py:class}`plistsync.config.LoggingConfig`. The CLI calls this function automatically; for scripts and library usage you should call it yourself. +`plistsync` provides a {py:func}`plistsync.logger.init_logging` function that configures logging for the plistsync logger based on a {py:class}`plistsync.logger.LoggingConfig`. The CLI calls this function automatically; for scripts and library usage you should call it yourself. You can retrieve the logger as usual: @@ -24,11 +24,10 @@ logging: ## Configuring logging from a script -Call {py:func}`plistsync.logger.init_logging` with a {py:class}`~plistsync.config.LoggingConfig` to set up the plistsync logger: +Call {py:func}`plistsync.logger.init_logging` with a {py:class}`~plistsync.logger.LoggingConfig` to set up the plistsync logger: ```python -from plistsync.config import LoggingConfig -from plistsync.logger import init_logging +from plistsync.logger import init_logging, LoggingConfig # Use defaults (level="INFO", handler="rich") init_logging() diff --git a/examples/community/plex_to_m3u.py b/examples/community/plex_to_m3u.py index 06b4612c..cc49fd6d 100644 --- a/examples/community/plex_to_m3u.py +++ b/examples/community/plex_to_m3u.py @@ -1,13 +1,18 @@ """Export a single Plex playlist to M3U format, with optional path rewriting.""" -from pathlib import Path -from typing import Annotated +from __future__ import annotations + +from typing import TYPE_CHECKING, Annotated import typer +from plistsync.cli.config import Config from plistsync.core.rewrite import PathRewrite from plistsync.logger import log -from plistsync.services.plex import PlexLibrary +from plistsync.services.plex import PlexConfig, PlexLibrary + +if TYPE_CHECKING: + from pathlib import Path def main( @@ -53,7 +58,8 @@ def main( path_rewrite = PathRewrite.from_str(plex_path_base, m3u_path_base) # Load Plex library and playlist - plex_library = PlexLibrary(plex_section_name) + plex_config = Config().get_config_for(PlexConfig) + plex_library = PlexLibrary.from_config(plex_config, plex_section_name) playlist = plex_library.get_playlist(name=playlist_name) if playlist is None: @@ -70,16 +76,14 @@ def main( if not track.path: log.warning(f"Track '{track.title}' has no file path — skipping.") continue - m3u += str(path_rewrite.apply(track.path)) + '\n' + m3u += str(path_rewrite.apply(track.path)) + "\n" num_m3u_tracks += 1 # Write M3U file output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text(m3u, encoding="utf-8") - log.info( - f"Exported '{playlist.name}' → {output_path} with {num_m3u_tracks} tracks" - ) + log.info(f"Exported '{playlist.name}' → {output_path} with {num_m3u_tracks} tracks") main.__doc__ = __doc__ # set help text from module docstring diff --git a/examples/community/plex_traktor_bidirectional.py b/examples/community/plex_traktor_bidirectional.py index 2f611cd8..298181af 100644 --- a/examples/community/plex_traktor_bidirectional.py +++ b/examples/community/plex_traktor_bidirectional.py @@ -7,17 +7,23 @@ The Path rewrite assumes your plex is remote and traktor is local. """ -from pathlib import Path -from typing import Annotated +from __future__ import annotations + +from typing import TYPE_CHECKING, Annotated import typer +from plistsync.cli.config import Config from plistsync.core.ids import FilePath from plistsync.core.rewrite import PathRewrite from plistsync.logger import log +from plistsync.services.plex.config import PlexConfig from plistsync.services.plex.library import PlexLibrary from plistsync.services.traktor import NMLLibrary, NMLPlaylistTrack +if TYPE_CHECKING: + from pathlib import Path + def main( traktor_nml_path: Annotated[ @@ -59,7 +65,8 @@ def main( path_rewrite = PathRewrite.from_str(plex_path_base, traktor_path_base) # Get libraries - plex_library = PlexLibrary(plex_section_name) + plex_config = Config().get_config_for(PlexConfig) + plex_library = PlexLibrary.from_config(plex_config, plex_section_name) traktor_library = NMLLibrary(traktor_nml_path) # Get playlists @@ -120,7 +127,7 @@ def main( p_for_plex = path_rewrite.invert.apply(p) plex_track = plex_library.find_by_ids([FilePath(p_for_plex)]) if plex_track is None: - log.warning(f"Could not find track in plex: {str(p_for_plex)}") + log.warning(f"Could not find track in plex: {p_for_plex!s}") else: plex_playlist.tracks.append(plex_track) diff --git a/pyproject.toml b/pyproject.toml index 8af76452..5ccae4b8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -111,6 +111,7 @@ include = ["plistsync/py.typed"] include = [ "pyproject.toml", "plistsync/**/*.py", + "examples/**/*.py", "tests/**/*.py", "docs/**/*.ipynb", ] diff --git a/tests/cli/test_auth.py b/tests/cli/test_auth.py index 817f52da..4fc8f840 100644 --- a/tests/cli/test_auth.py +++ b/tests/cli/test_auth.py @@ -58,7 +58,6 @@ class FakeConfig(ServiceConfig, service="fake"): fake_option: str = "default" - # ``__module__`` must be set after the class body: ``@dataclass`` resolves # string annotations via ``sys.modules[cls.__module__]``, and no # ``plistsync.services.fake`` module exists. diff --git a/tests/services/test_registry.py b/tests/services/test_registry.py index 54246163..c7aa0a0c 100644 --- a/tests/services/test_registry.py +++ b/tests/services/test_registry.py @@ -66,6 +66,10 @@ def ids(self) -> frozenset[TrackID]: class FakeLibrary(Library[Any, Any]): __module__ = SERVICE_MODULE + @classmethod + def from_config(cls, config: object | None = None) -> Self: + return cls() + @property def playlists(self) -> Iterable[Any]: return [] diff --git a/tests/utils/test_session.py b/tests/utils/test_session.py index 2e56c3f5..5d952640 100644 --- a/tests/utils/test_session.py +++ b/tests/utils/test_session.py @@ -1,10 +1,11 @@ import threading from importlib.metadata import version -from unittest.mock import MagicMock, patch +from unittest.mock import MagicMock, call, patch import pytest import requests from requests import Response +from requests.adapters import HTTPAdapter from plistsync.utils.session import RateLimitAdapter, PlistsyncSession @@ -31,6 +32,24 @@ def mock_sleep(self, monkeypatch): monkeypatch.setattr("plistsync.utils.session.time.sleep", sleep_mock) return sleep_mock + @pytest.fixture + def no_network(self, monkeypatch: pytest.MonkeyPatch) -> None: + """Stub the HTTP transport so ``send`` runs without real network I/O.""" + + def fake_send( + adapter: HTTPAdapter, + request: requests.PreparedRequest, + *args: object, + **kwargs: object, + ) -> Response: + response = Response() + response.status_code = 200 + response.request = request + response._content = b"{}" + return response + + monkeypatch.setattr(HTTPAdapter, "send", fake_send) + @pytest.mark.parametrize( "rate_limit, expected_calls_after_two_sends", [ @@ -40,18 +59,25 @@ def mock_sleep(self, monkeypatch): ) def test_rate_limiting( self, - adapter, - mock_sleep, - rate_limit, - expected_calls_after_two_sends, - ): + adapter: RateLimitAdapter, + mock_sleep: MagicMock, + no_network: None, + rate_limit: float, + expected_calls_after_two_sends: int, + ) -> None: """Fixed: Assert total sleeps after exactly two sends.""" adapter.rate_limit = rate_limit adapter.send(_prepared_request()) adapter.send(_prepared_request()) assert mock_sleep.call_count == expected_calls_after_two_sends - def test_custom_wait_time(self, adapter, mock_sleep, monkeypatch): + def test_custom_wait_time( + self, + adapter: RateLimitAdapter, + mock_sleep: MagicMock, + no_network: None, + monkeypatch: pytest.MonkeyPatch, + ) -> None: """Fixed: Force elapsed=0 so custom wait always triggers once per send.""" adapter._wait_time = lambda elapsed: 0.5 monkeypatch.setattr( @@ -61,17 +87,28 @@ def test_custom_wait_time(self, adapter, mock_sleep, monkeypatch): adapter.send(_prepared_request()) adapter.send(_prepared_request()) assert mock_sleep.call_count == 2 - mock_sleep.assert_has_calls([((0.5,),), ((0.5,),)], any_order=False) + mock_sleep.assert_has_calls([call(0.5), call(0.5)], any_order=False) @pytest.mark.parametrize("method", ["GET", "POST", "PUT", "DELETE", "PATCH"]) - def test_different_methods(self, adapter, mock_sleep, method): + def test_different_methods( + self, + adapter: RateLimitAdapter, + mock_sleep: MagicMock, + no_network: None, + method: str, + ) -> None: """Parameterized: works with all HTTP methods.""" request = _prepared_request(method=method) adapter.send(_prepared_request()) # First: no sleep adapter.send(request) mock_sleep.assert_called_once() - def test_thread_safety(self, adapter, mock_sleep): + def test_thread_safety( + self, + adapter: RateLimitAdapter, + mock_sleep: MagicMock, + no_network: None, + ) -> None: """Thread-safe: concurrent requests respect rate limit.""" def make_request(): From 2a053ff9ab5204c72838ee0a640fa80e7a535b86 Mon Sep 17 00:00:00 2001 From: pSpitzner Date: Sun, 27 Sep 2026 17:04:58 +0200 Subject: [PATCH 08/11] moved default plex section name from constructor into config. removed default traktor bool kwarg. from_config is the most likely entrypoint now. --- docs/services/plex/getting-started.md | 2 ++ examples/community/plex_traktor_bidirectional.py | 2 +- plistsync/services/plex/config.py | 5 +++++ plistsync/services/plex/library.py | 11 ++++++----- plistsync/services/traktor/library.py | 2 +- tests/services/traktor/conftest.py | 2 +- tests/services/traktor/test_collection.py | 5 ++++- 7 files changed, 20 insertions(+), 9 deletions(-) diff --git a/docs/services/plex/getting-started.md b/docs/services/plex/getting-started.md index 60d4b67b..72e9e590 100644 --- a/docs/services/plex/getting-started.md +++ b/docs/services/plex/getting-started.md @@ -49,6 +49,8 @@ services: # via plex.tv. In this case, we try local routes first. # E.g. 'my_plex_server' server_name: null + # The name or ID of the Plex library section to use by default. + section_name_or_id: Music ``` ## Authentication diff --git a/examples/community/plex_traktor_bidirectional.py b/examples/community/plex_traktor_bidirectional.py index 298181af..66226d72 100644 --- a/examples/community/plex_traktor_bidirectional.py +++ b/examples/community/plex_traktor_bidirectional.py @@ -67,7 +67,7 @@ def main( # Get libraries plex_config = Config().get_config_for(PlexConfig) plex_library = PlexLibrary.from_config(plex_config, plex_section_name) - traktor_library = NMLLibrary(traktor_nml_path) + traktor_library = NMLLibrary(traktor_nml_path, backup_before_write=True) # Get playlists plex_playlist = plex_library.get_playlist(name=playlist_name) diff --git a/plistsync/services/plex/config.py b/plistsync/services/plex/config.py index fac82a89..5a510f06 100644 --- a/plistsync/services/plex/config.py +++ b/plistsync/services/plex/config.py @@ -23,6 +23,11 @@ class PlexConfig(ServiceConfig): "E.g. 'my_plex_server'", ] = field(default=None) + section_name_or_id: Annotated[ + str | int, + "The name or ID of the Plex library section to use by default.", + ] = field(default="Music") + redirect_port: Annotated[ int, "The port to use for the local redirect server when authenticating.", diff --git a/plistsync/services/plex/library.py b/plistsync/services/plex/library.py index a5fea348..1a7304d0 100644 --- a/plistsync/services/plex/library.py +++ b/plistsync/services/plex/library.py @@ -47,7 +47,7 @@ class PlexLibrary( def __init__( self, api: PlexApi, - section_name_or_id: str | int = "Music", + section_name_or_id: str | int, ): """Initialize the PlexLibrary from plex given a section id. @@ -62,11 +62,12 @@ def __init__( self.id = self.api.converts.section_name_to_id(section_name_or_id) @classmethod - def from_config( - cls, config: PlexConfig, section_name_or_id: str | int = "Music" - ) -> Self: + def from_config(cls, config: PlexConfig) -> Self: """Construct a Plex library from a service config.""" - return cls(PlexApi(PlexApiSession.from_config(config)), section_name_or_id) + return cls( + PlexApi(PlexApiSession.from_config(config)), + section_name_or_id=config.section_name_or_id, + ) def preload(self, force_reload=False) -> None: """Preload the collections tracks. diff --git a/plistsync/services/traktor/library.py b/plistsync/services/traktor/library.py index 6b915cf0..35f42c23 100644 --- a/plistsync/services/traktor/library.py +++ b/plistsync/services/traktor/library.py @@ -47,7 +47,7 @@ class NMLLibrary( tree: _ElementTree backup_before_write: bool - def __init__(self, path: Path | str, backup_before_write: bool = True): + def __init__(self, path: Path | str, backup_before_write: bool): self.path = Path(path) if not self.path.exists(): raise FileNotFoundError(f"File {path} does not exist") diff --git a/tests/services/traktor/conftest.py b/tests/services/traktor/conftest.py index d281c3f1..2118faf4 100644 --- a/tests/services/traktor/conftest.py +++ b/tests/services/traktor/conftest.py @@ -24,7 +24,7 @@ def collection(tmp_path: Path) -> NMLLibrary: src = Path(__file__).parent.parent.parent / "data" / "traktor_playlist.nml" dest = tmp_path / "traktor_playlist.nml" shutil.copyfile(src, dest) - return NMLLibrary(dest) + return NMLLibrary(dest, backup_before_write=True) @pytest.fixture diff --git a/tests/services/traktor/test_collection.py b/tests/services/traktor/test_collection.py index 52dfa7c1..5618dce0 100644 --- a/tests/services/traktor/test_collection.py +++ b/tests/services/traktor/test_collection.py @@ -87,7 +87,10 @@ def test_write_persists(self, collection: NMLLibrary) -> None: collection.write() # After reload should be persisteted! - reloaded = NMLLibrary(collection.path) + reloaded = NMLLibrary( + collection.path, + backup_before_write=collection.backup_before_write, + ) p2 = reloaded.get_playlist_or_raise(id="6868ecd66b354d37a33b965dae7a82e7") assert p2.name == new_name From 1faecaa57b4d81d392ad4be04bba69f60c1eec75 Mon Sep 17 00:00:00 2001 From: pSpitzner Date: Thu, 1 Oct 2026 01:27:12 +0200 Subject: [PATCH 09/11] fixed mypy (examples) --- examples/community/plex_to_m3u.py | 3 ++- examples/community/plex_traktor_bidirectional.py | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/community/plex_to_m3u.py b/examples/community/plex_to_m3u.py index cc49fd6d..7d5b1fcd 100644 --- a/examples/community/plex_to_m3u.py +++ b/examples/community/plex_to_m3u.py @@ -59,7 +59,8 @@ def main( # Load Plex library and playlist plex_config = Config().get_config_for(PlexConfig) - plex_library = PlexLibrary.from_config(plex_config, plex_section_name) + plex_config.section_name_or_id = plex_section_name + plex_library = PlexLibrary.from_config(plex_config) playlist = plex_library.get_playlist(name=playlist_name) if playlist is None: diff --git a/examples/community/plex_traktor_bidirectional.py b/examples/community/plex_traktor_bidirectional.py index 66226d72..a43ccf68 100644 --- a/examples/community/plex_traktor_bidirectional.py +++ b/examples/community/plex_traktor_bidirectional.py @@ -66,7 +66,8 @@ def main( # Get libraries plex_config = Config().get_config_for(PlexConfig) - plex_library = PlexLibrary.from_config(plex_config, plex_section_name) + plex_config.section_name_or_id = plex_section_name + plex_library = PlexLibrary.from_config(plex_config) traktor_library = NMLLibrary(traktor_nml_path, backup_before_write=True) # Get playlists From cfd711c8e2e593d74f84ccb21037d2d48ae270f7 Mon Sep 17 00:00:00 2001 From: Sebastian Mohr Date: Mon, 12 Oct 2026 18:23:29 +0200 Subject: [PATCH 10/11] Renamed C to Conf see https://github.com/metasauce/plistsync/pull/140#discussion_r4243053423 --- plistsync/core/collection.py | 6 +++--- plistsync/core/playlist.py | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/plistsync/core/collection.py b/plistsync/core/collection.py index f5b63031..4ca08eab 100644 --- a/plistsync/core/collection.py +++ b/plistsync/core/collection.py @@ -79,7 +79,7 @@ class MyTrackCollection(Collection, IDLookup, TrackStream): Plist = TypeVar("Plist", bound="Playlist", default="ServicePlaylist", covariant=True) -C = TypeVar("C", bound="ServiceConfig | None", default=None) +Conf = TypeVar("Conf", bound="ServiceConfig | None", default=None) @runtime_checkable @@ -534,7 +534,7 @@ def record(idx: int, found_track, similarity: float) -> None: ) -class Library(Generic[T, Plist, C], Collection[T], ABC, Registry): +class Library(Generic[T, Plist, Conf], Collection[T], ABC, Registry): """Represents a collection of tracks in a library with playlist management. This class serves as a base for library collections across diverse services. @@ -544,7 +544,7 @@ class Library(Generic[T, Plist, C], Collection[T], ABC, Registry): @classmethod @abstractmethod - def from_config(cls, config: C) -> Self: + def from_config(cls, config: Conf) -> Self: """Create a library from its service config. ``config`` is ``None`` for services that have no configuration. diff --git a/plistsync/core/playlist.py b/plistsync/core/playlist.py index 5a6c5363..fe90bf05 100644 --- a/plistsync/core/playlist.py +++ b/plistsync/core/playlist.py @@ -29,7 +29,7 @@ class MyPlaylistCollection(PlaylistCollection): from plistsync.services.registry import Registry -from .collection import C, Collection, TrackStream +from .collection import Collection, Conf, TrackStream from .diff import DeleteOp, InsertOp, MoveOp, batch_consecutive, list_diff from .track import OfflineTrack, Track @@ -171,7 +171,7 @@ def __len__(self) -> int: return len(self.tracks) -class ServicePlaylist(Generic[T, C], Playlist[T], ABC): +class ServicePlaylist(Generic[T, Conf], Playlist[T], ABC): """Abstract base class for playlists synchronized with music services. Extends `Playlist` with methods to manage the lifecycle and state synchronization @@ -186,7 +186,7 @@ class ServicePlaylist(Generic[T, C], Playlist[T], ABC): - `update()` - bulk update by comparing remote and local snapshots """ - library: Library[Track, Self, C] + library: Library[Track, Self, Conf] # --------------------------- Required (protocol) ---------------------------- # @@ -268,7 +268,7 @@ def edit(self): raise -class MultiRequestServicePlaylist(ServicePlaylist[T, C], ABC): +class MultiRequestServicePlaylist(ServicePlaylist[T, Conf], ABC): """Playlist for APIs where modifications have to be split into mulitple requests. Subclass this and implement: From 2e14c4134494c800f8a97c87fc9ac3738159e0d7 Mon Sep 17 00:00:00 2001 From: Sebastian Mohr Date: Mon, 12 Oct 2026 18:28:20 +0200 Subject: [PATCH 11/11] Removed unnecessary comment and casts. see https://github.com/metasauce/plistsync/pull/140#discussion_r4243125958 --- plistsync/cli/context.py | 13 +++---------- plistsync/core/collection.py | 4 ++-- 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/plistsync/cli/context.py b/plistsync/cli/context.py index 02376aff..b653a099 100644 --- a/plistsync/cli/context.py +++ b/plistsync/cli/context.py @@ -4,12 +4,12 @@ from dataclasses import dataclass from functools import cached_property -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING import typer if TYPE_CHECKING: - from plistsync.core import Library, ServicePlaylist, Track + from plistsync.core import Library from plistsync.core.config import ServiceConfig from plistsync.services import Service @@ -31,14 +31,7 @@ def library(self) -> Library | None: config_cls = self.service.config() config = Config().get_config_for(config_cls) if config_cls is not None else None - - # The registry pairs every library class with its service config class; - # the erased ``type[Library]`` view cannot express that pairing. - factory = cast( - "type[Library[Track, ServicePlaylist, ServiceConfig | None]]", - library_cls, - ) - return cast("Library", factory.from_config(config)) + return library_cls.from_config(config) @cached_property def config(self) -> ServiceConfig | None: diff --git a/plistsync/core/collection.py b/plistsync/core/collection.py index 4ca08eab..7cd24cc8 100644 --- a/plistsync/core/collection.py +++ b/plistsync/core/collection.py @@ -60,6 +60,7 @@ class MyTrackCollection(Collection, IDLookup, TrackStream): from plistsync.services.registry import Registry +from .config import ServiceConfig from .ids import Scope from .matching import Matches, fuzzy_match from .track import Track @@ -71,7 +72,6 @@ class MyTrackCollection(Collection, IDLookup, TrackStream): if TYPE_CHECKING: from collections.abc import Callable, Iterable, Sequence - from .config import ServiceConfig from .ids import PlaylistID, TrackID from .matching import Similarity from .playlist import Playlist, ServicePlaylist @@ -79,7 +79,7 @@ class MyTrackCollection(Collection, IDLookup, TrackStream): Plist = TypeVar("Plist", bound="Playlist", default="ServicePlaylist", covariant=True) -Conf = TypeVar("Conf", bound="ServiceConfig | None", default=None) +Conf = TypeVar("Conf", bound="ServiceConfig | None", default=ServiceConfig | None) @runtime_checkable