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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Added a service-agnostic authentication layer in `plistsync.core.auth`. The `AuthProvider` base class splits a flow into `build_request`, `collect_response` and `obtain_token`, and drives user interaction through the `Interaction` protocol, allowing library consumers to run authentication flows programmatically without the CLI. (#117)
- 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`.

### Changes

Expand Down
19 changes: 16 additions & 3 deletions plistsync/cli/commands/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

from plistsync.logger import log
from plistsync.services import ServiceLoader
from plistsync.services.sync import SyncedPlaylist
from plistsync.services.sync import RegisterMode, SyncedPlaylist

if TYPE_CHECKING:
from collections.abc import Iterable
Expand Down Expand Up @@ -292,7 +292,7 @@ def list_(
_print(table)


@sync_app.command(name="register")
@sync_app.command(name="register", no_args_is_help=True)
def register(
name_or_id: Annotated[
str,
Expand All @@ -315,6 +315,19 @@ def register(
help="Output the result as JSON.",
),
] = False,
mode: Annotated[
RegisterMode,
typer.Option(
"--mode",
help=(
"How to merge the incoming playlist.\n\n"
" append: add all incoming tracks to the end;\n\n"
" skip-duplicates: add only tracks without matching IDs;\n\n"
" take-incoming: replace the internal tracks completely;\n\n"
" take-existing: ignore incoming tracks;"
),
),
] = RegisterMode.APPEND,
) -> None:
"""Link a existing service playlist to a synced playlist.

Expand Down Expand Up @@ -364,7 +377,7 @@ def register(

# Register the service playlist with the synced playlist and update on disk
playlist_name = service_playlist.name
sync.register(service_playlist)
sync.register(service_playlist, mode=mode)
sync.sync()
sync.save_to(__sync_dir() / f"{sync.id}.json")

Expand Down
7 changes: 6 additions & 1 deletion plistsync/services/sync/__init__.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
"""Synchronisation primitives for cross-service playlist management."""

from plistsync.services import Service
from plistsync.services.sync.playlist import SyncedPlaylist, SyncedPlaylistID
from plistsync.services.sync.playlist import (
RegisterMode,
SyncedPlaylist,
SyncedPlaylistID,
)


class SyncService(Service):
pass


__all__ = [
"RegisterMode",
"SyncedPlaylist",
"SyncedPlaylistID",
]
52 changes: 40 additions & 12 deletions plistsync/services/sync/playlist.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

from dataclasses import dataclass
from enum import StrEnum
from typing import TYPE_CHECKING, Any
from uuid import UUID, uuid4

Expand Down Expand Up @@ -33,6 +34,15 @@
ReplicaID = int


class RegisterMode(StrEnum):
"""Control how a service playlist is merged when it is registered."""

APPEND = "append"
SKIP_DUPLICATES = "skip-duplicates" # Use hyphens, strings are used in the CLI
Comment thread
pSpitzner marked this conversation as resolved.
Resolved
TAKE_INCOMING = "take-incoming"
TAKE_EXISTING = "take-existing"


@dataclass
class _TrackLink:
"""Helper to associate tracks with multiple service-specific playlists.
Expand Down Expand Up @@ -176,31 +186,49 @@ def n_linked(self) -> int:

# ------------------------------- Sync specific ------------------------------ #

def register(self, playlist: ServicePlaylist) -> None:
def register(
self,
playlist: ServicePlaylist,
*,
mode: RegisterMode = RegisterMode.APPEND,
) -> None:
"""Register a playlist as a synchronization target.

Existing tracks from the playlist are added to the internal collection.
Tracks already in the internal collection but missing from the playlist
are preserved.
The incoming playlist is merged according to *mode*. In all modes, tracks
already in the internal collection are preserved unless ``TAKE_INCOMING``
is selected.

Name and description from the playlist are not used; the internal state is
authoritative. Use :meth:`sync` to push the internal state back to the playlist.
Name and description from the playlist are not used unless
``TAKE_INCOMING`` is selected. In that mode, incoming metadata replaces the
internal metadata before the internal state is pushed back to the playlist.
"""
replica_id = self._new_replica_id()
self._linked_playlists[replica_id] = playlist

if playlist.tracks:
# Use a fork here so operations carry the new replica ID for versioning.
fork = self._fugue.fork(replica_id)
# Use a fork here so operations carry the new replica ID for versioning.
fork = self._fugue.fork(replica_id)
if mode is RegisterMode.TAKE_INCOMING:
while len(fork):
self._fugue.apply(fork.delete(0))

if mode is not RegisterMode.TAKE_EXISTING:
for track in playlist.tracks:
offline_track = OfflineTrack.from_track(track)
if mode is RegisterMode.SKIP_DUPLICATES and any(
# Simple, ID-based matching keeps this fast
linked_track.track.ids & offline_track.ids
for linked_track in fork
):
continue
op = fork.insert(
len(fork),
_TrackLink(
track=OfflineTrack.from_track(track), playlists={playlist.id}
),
_TrackLink(track=offline_track, playlists={playlist.id}),
)
self._fugue.apply(op)

if mode is RegisterMode.TAKE_INCOMING:
self.info = playlist.info

self._enrich_internal_from(playlist)
self._push_internal_to(playlist)

Expand Down
22 changes: 22 additions & 0 deletions tests/cli/test_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from plistsync.core.track import OfflineTrack
from plistsync.services.sync import SyncedPlaylist
from plistsync.services.sync.playlist import _TrackLink
from plistsync.services.sync.playlist import RegisterMode
from tests.core.mock_playlist import MockPlaylistID, MockServicePlaylist

if TYPE_CHECKING:
Expand Down Expand Up @@ -374,6 +375,27 @@ def test_register_json_output(self, synced):
assert payload["playlist"] == "test:playlist:abc123"
assert payload["tracks"] == 0

def test_register_mode_is_forwarded(self, synced):
"""The registration merge mode is forwarded to SyncedPlaylist."""
with (
self._patch_service(),
patch.object(SyncedPlaylist, "register") as register,
):
result = self.runner.invoke(
self.cli_app,
[
"sync",
"register",
"Party Mix",
"test:playlist:abc123",
"--mode",
RegisterMode.TAKE_INCOMING.value,
],
)

assert result.exit_code == 0
assert register.call_args.kwargs["mode"] is RegisterMode.TAKE_INCOMING

def test_register_synced_not_found(self, sync_dir):
"""Registering with an unknown synced playlist fails."""
result = self.runner.invoke(
Expand Down
49 changes: 48 additions & 1 deletion tests/services/sync/test_playlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@
from plistsync.services.sync.crdt.lww import LWWRegister
from plistsync.core.matching import Matches
from plistsync.core.playlist import PlaylistInfo
from plistsync.services.sync.playlist import SyncedPlaylist, SyncedPlaylistID
from plistsync.services.sync.playlist import (
RegisterMode,
SyncedPlaylist,
SyncedPlaylistID,
)
from plistsync.core.track import OfflineTrack
from plistsync.services.spotify import SpotifyPlaylistID
from plistsync.services.tidal import TidalPlaylistID
Expand Down Expand Up @@ -168,6 +172,49 @@ def test_register_assigns_incrementing_replica_ids(self):

assert playlist._linked_playlists == {1: first, 2: second}

def test_register_skip_duplicates_preserves_existing_tracks(self, track_a, track_b):
playlist = SyncedPlaylist("x", tracks=[OfflineTrack.from_track(track_a)])
service = make_playlist([track_a, track_b])

playlist.register(service, mode=RegisterMode.SKIP_DUPLICATES)

assert isrcs(playlist.tracks) == isrcs([track_a, track_b])

def test_register_take_incoming_replaces_existing_tracks(self, track_a, track_b):
playlist = SyncedPlaylist("x", tracks=[OfflineTrack.from_track(track_a)])
service = make_playlist([track_b])

playlist.register(service, mode=RegisterMode.TAKE_INCOMING)

assert isrcs(playlist.tracks) == isrcs([track_b])

def test_register_take_incoming_replaces_metadata(self, track_a):
playlist = SyncedPlaylist("internal", description="internal desc")
service = make_playlist([track_a], name="incoming")
service.info = PlaylistInfo(name="incoming", description="incoming desc")

playlist.register(service, mode=RegisterMode.TAKE_INCOMING)

assert playlist.info == {
"name": "incoming",
"description": "incoming desc",
}
assert service.info == playlist.info

def test_register_take_existing_preserves_internal_tracks(self, track_a, track_b):
playlist = SyncedPlaylist("x", tracks=[OfflineTrack.from_track(track_a)])
service = make_playlist([track_b])
service.library.match = Mock(
return_value=Matches(
truth=track_a, found=[track_a], found_similarities=[1.0]
)
)

playlist.register(service, mode=RegisterMode.TAKE_EXISTING)

assert isrcs(playlist.tracks) == isrcs([track_a])
assert isrcs(service.tracks) == isrcs([track_a])


class TestRefresh:
def test_refresh_replaces_linked_playlists(self):
Expand Down
Loading