From 305d06bb95dac39dc77f983f1df43df03480de09 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sat, 24 Oct 2026 23:07:44 +0200 Subject: [PATCH 01/32] feat(plex): sync track favorites securely --- docs/plex.md | 9 ++- external/plex/client.go | 59 +++++++++++++++++++ external/plex/client_test.go | 47 ++++++++++++++++ external/plex/provider.go | 100 +++++++++++++++++++++++++++++++-- external/plex/provider_test.go | 64 +++++++++++++++++---- provider/types.go | 1 + providers.go | 10 ++++ providers_test.go | 11 ++++ site/index.html | 2 +- 9 files changed, 283 insertions(+), 20 deletions(-) diff --git a/docs/plex.md b/docs/plex.md index 66177b642..b7ab71d2c 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -56,6 +56,9 @@ Artist - Album Title (Year) Select a playlist or album to load its tracks. Smart playlists are included. They resolve to current server content. +Press `f` on a Plex track to add or remove it from cliamp Favorites. The same +change is copied to Plex and appears in Plexamp and other Plex clients. + Start cliamp with Plex as the default provider: ```bash @@ -70,13 +73,13 @@ provider = "plex" ## How it works -cliamp calls the Plex HTTP API to list audio playlists (`/playlists`) and music library albums. When you select an entry, cliamp gets its track list from the playlist-items or album-children endpoint. It then creates authenticated streaming URLs in this form: +cliamp calls the Plex HTTP API to list audio playlists (`/playlists`) and music library albums. When you select an entry, cliamp gets its track list from the playlist-items or album-children endpoint. Queues, playlists, favorites, history, resume state, and IPC keep only a token-free logical path: ``` -http://:32400/library/parts///file.?X-Plex-Token= +plex:track: ``` -These URLs serve files directly. Plex serves the original file without transcoding. cliamp handles playback through its HTTP streaming pipeline. cliamp can play MP3, FLAC, AAC, OGG, OPUS, WAV, and other supported source formats. +When playback starts, cliamp resolves that path to the Plex part URL in memory and authenticates the request with your token. The token is not written into track paths or exposed through status output. Plex serves the original file without transcoding. cliamp handles playback through its HTTP streaming pipeline and can play MP3, FLAC, AAC, OGG, OPUS, WAV, and other supported source formats. ## Troubleshooting diff --git a/external/plex/client.go b/external/plex/client.go index 1a8eacc16..79c72a0f5 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -2,7 +2,9 @@ package plex import ( + "context" "fmt" + "io" "net/http" "net/url" "strconv" @@ -107,6 +109,46 @@ func (c *Client) get(path string, params url.Values, result any) error { return nil } +// SetRating updates the current user's rating for one Plex library item. +// Plex uses 10 for a liked track and 0 to clear the like. +func (c *Client) SetRating(ctx context.Context, ratingKey string, rating float64) error { + if ratingKey == "" { + return fmt.Errorf("plex: rate: missing rating key") + } + params := url.Values{ + "identifier": {"com.plexapp.plugins.library"}, + "key": {ratingKey}, + "rating": {fmt.Sprintf("%g", rating)}, + } + return c.doAction(ctx, http.MethodPut, "/:/rate", params) +} + +func (c *Client) doAction(ctx context.Context, method, endpoint string, params url.Values) error { + req, err := http.NewRequestWithContext(ctx, method, c.baseURL+endpoint+"?"+params.Encode(), nil) + if err != nil { + return fmt.Errorf("plex: %s: %w", strings.TrimPrefix(endpoint, "/:/"), err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("X-Plex-Product", "cliamp") + req.Header.Set("X-Plex-Client-Identifier", "cliamp") + req.Header.Set("X-Plex-Token", c.token) + + resp, err := apiClient.Do(req) + if err != nil { + return fmt.Errorf("plex: %s: server unreachable: %w", strings.TrimPrefix(endpoint, "/:/"), netdiag.Explain(err)) + } + defer resp.Body.Close() + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxResponseBody)) + + if resp.StatusCode == http.StatusUnauthorized { + return fmt.Errorf("plex: token invalid or expired") + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return fmt.Errorf("plex: %s: HTTP %s", strings.TrimPrefix(endpoint, "/:/"), resp.Status) + } + return nil +} + // Ping checks that the server is reachable and the token is valid. // Returns a descriptive error on failure. func (c *Client) Ping() error { @@ -348,6 +390,23 @@ func (c *Client) Tracks(albumRatingKey string) ([]Track, error) { return tracks, nil } +// Track returns one track by its Plex ratingKey. It restores the stream-part +// mapping for a logical Plex URI after cliamp restarts. +func (c *Client) Track(ratingKey string) (Track, error) { + var result struct { + MediaContainer struct { + Metadata []trackJSON `json:"Metadata"` + } `json:"MediaContainer"` + } + if err := c.get("/library/metadata/"+ratingKey, nil, &result); err != nil { + return Track{}, err + } + if len(result.MediaContainer.Metadata) == 0 { + return Track{}, fmt.Errorf("plex: track %s not found", ratingKey) + } + return trackFromJSON(result.MediaContainer.Metadata[0]), nil +} + // Search searches the music library for tracks matching query. // Returns nil without making an HTTP call when query is empty. func (c *Client) Search(query string) ([]Track, error) { diff --git a/external/plex/client_test.go b/external/plex/client_test.go index 2c9cf224c..ecbd6ce9f 100644 --- a/external/plex/client_test.go +++ b/external/plex/client_test.go @@ -1,6 +1,7 @@ package plex import ( + "context" "errors" "fmt" "net/http" @@ -13,6 +14,33 @@ import ( "github.com/bjarneo/cliamp/internal/httpclient" ) +func TestSetRating(t *testing.T) { + for _, rating := range []float64{10, 0} { + t.Run(fmt.Sprintf("rating_%g", rating), func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPut || r.URL.Path != "/:/rate" { + t.Fatalf("request = %s %s, want PUT /:/rate", r.Method, r.URL.Path) + } + if got := r.URL.Query().Get("key"); got != "track-42" { + t.Errorf("key = %q, want track-42", got) + } + if got := r.URL.Query().Get("identifier"); got != "com.plexapp.plugins.library" { + t.Errorf("identifier = %q", got) + } + if got := r.Header.Get("X-Plex-Token"); got != "test-token" { + t.Errorf("X-Plex-Token = %q", got) + } + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() + + if err := newTestClient(srv).SetRating(context.Background(), "track-42", rating); err != nil { + t.Fatalf("SetRating(%g): %v", rating, err) + } + }) + } +} + // newTestClient returns a Client pointed at the given test server. func newTestClient(srv *httptest.Server) *Client { return NewClient(srv.URL, "test-token") @@ -636,6 +664,25 @@ func TestStreamURL_TokenEncoded(t *testing.T) { } } +func TestTrackLoadsOneMetadataItem(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/library/metadata/42" { + t.Fatalf("path = %q, want /library/metadata/42", r.URL.Path) + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"MediaContainer":{"Metadata":[{"ratingKey":"42","title":"Song","Media":[{"Part":[{"key":"/library/parts/4/file.flac"}]}]}]}}`)) + })) + defer srv.Close() + + track, err := newTestClient(srv).Track("42") + if err != nil { + t.Fatalf("Track: %v", err) + } + if track.RatingKey != "42" || track.PartKey != "/library/parts/4/file.flac" { + t.Fatalf("Track = %+v", track) + } +} + func TestSearch_SendsCorrectParams(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Query().Get("query") != "Miles Davis" { diff --git a/external/plex/provider.go b/external/plex/provider.go index ad5c60220..a26551e73 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -16,6 +16,9 @@ import ( // the browse view. Playlist IDs are prefixed so they can be told apart from // album ratingKeys (both live in the same server-side metadata key space). const ( + // TrackURIPrefix is the token-free path stored in queues, history, + // favorites, playlists, resume state, and IPC responses. + TrackURIPrefix = "plex:track:" prefixPlaylist = "pl:" sectionAlbums = "Albums" sectionPlaylists = "Playlists" @@ -25,6 +28,7 @@ const ( var ( _ provider.Searcher = (*Provider)(nil) _ provider.AlbumTrackLoader = (*Provider)(nil) + _ provider.TrackFavoriter = (*Provider)(nil) ) // Provider implements playlist.Provider for a Plex Media Server. @@ -37,6 +41,7 @@ type Provider struct { mu sync.Mutex playlistCache []playlist.PlaylistInfo trackCache map[string][]playlist.Track + partKeys map[string]string } // newProvider returns a Provider backed by the given Client. @@ -129,9 +134,10 @@ func (p *Provider) Refresh() { // Tracks returns the tracks for the playlist or album identified by // playlistID. Playlist IDs (prefixed "pl:") load via the server playlists -// endpoint; album IDs load via the album children endpoint. Each track's Path -// is a complete authenticated HTTP URL ready for the player. Tracks with no -// streamable part (missing Media/Part data) are silently skipped. Album tracks +// endpoint; album IDs load via the album children endpoint. Tracks with no +// ratingKey or streamable part are silently skipped. Track paths are token-free +// logical URIs; ResolveSource creates the authenticated URL only when playback +// starts. Album tracks // are cached per album ID; playlist tracks are intentionally not cached so // smart playlists always reflect their current server contents. func (p *Provider) Tracks(playlistID string) ([]playlist.Track, error) { @@ -188,11 +194,17 @@ func (p *Provider) SearchTracks(_ context.Context, query string, limit int) ([]p func (p *Provider) convertTracks(plexTracks []Track, limit int) []playlist.Track { tracks := make([]playlist.Track, 0, len(plexTracks)) for _, t := range plexTracks { - if t.PartKey == "" { + if t.RatingKey == "" || t.PartKey == "" { continue } + p.mu.Lock() + if p.partKeys == nil { + p.partKeys = make(map[string]string) + } + p.partKeys[t.RatingKey] = t.PartKey + p.mu.Unlock() tracks = append(tracks, playlist.Track{ - Path: p.client.StreamURL(t.PartKey), + Path: TrackURIPrefix + t.RatingKey, Title: t.Title, Artist: t.ArtistName, Album: t.AlbumName, @@ -200,6 +212,7 @@ func (p *Provider) convertTracks(plexTracks []Track, limit int) []playlist.Track TrackNumber: t.TrackNumber, DurationSecs: t.Duration / 1000, Stream: true, + ProviderMeta: map[string]string{provider.MetaPlexID: t.RatingKey}, }) if limit > 0 && len(tracks) >= limit { break @@ -208,6 +221,83 @@ func (p *Provider) convertTracks(plexTracks []Track, limit int) []playlist.Track return tracks } +// ResolveSource turns a token-free Plex track URI into an authenticated +// stream URL at play time. A restored entry fetches its part metadata when +// the in-memory mapping is absent after a restart. +func (p *Provider) ResolveSource(uri string) (string, error) { + id, ok := trackIDFromPath(uri) + if !ok { + return "", fmt.Errorf("plex: invalid track uri %q", uri) + } + p.mu.Lock() + partKey := p.partKeys[id] + p.mu.Unlock() + if partKey == "" { + track, err := p.client.Track(id) + if err != nil { + return "", fmt.Errorf("plex: resolve track %s: %w", id, err) + } + if track.PartKey == "" { + return "", fmt.Errorf("plex: track %s has no streamable part", id) + } + partKey = track.PartKey + p.mu.Lock() + if p.partKeys == nil { + p.partKeys = make(map[string]string) + } + p.partKeys[id] = partKey + p.mu.Unlock() + } + return p.client.StreamURL(partKey), nil +} + +func trackIDFromPath(path string) (string, bool) { + id, ok := strings.CutPrefix(path, TrackURIPrefix) + if !ok || !validRatingKey(id) { + return "", false + } + return id, true +} + +func validRatingKey(id string) bool { + if id == "" { + return false + } + for _, r := range id { + if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && + (r < '0' || r > '9') && r != '-' && r != '_' { + return false + } + } + return true +} + +// CanFavoriteTrack reports whether track came from this Plex provider. +func (p *Provider) CanFavoriteTrack(track playlist.Track) bool { + return plexTrackID(track) != "" +} + +// SetTrackFavorite copies cliamp's local favorite state to Plex. +func (p *Provider) SetTrackFavorite(ctx context.Context, track playlist.Track, favorite bool) error { + id := plexTrackID(track) + if id == "" { + return fmt.Errorf("plex: track has no rating key") + } + rating := float64(0) + if favorite { + rating = 10 + } + return p.client.SetRating(ctx, id, rating) +} + +func plexTrackID(track playlist.Track) string { + if id := track.Meta(provider.MetaPlexID); id != "" { + return id + } + id, _ := trackIDFromPath(track.Path) + return id +} + // AlbumTracks returns the tracks for the given album (ratingKey). // Implements provider.AlbumTrackLoader. func (p *Provider) AlbumTracks(albumID string) ([]playlist.Track, error) { diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index 466e97a17..59a69efab 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -1,12 +1,15 @@ package plex import ( + "context" "net/http" "net/http/httptest" "strings" "testing" "github.com/bjarneo/cliamp/config" + "github.com/bjarneo/cliamp/playlist" + "github.com/bjarneo/cliamp/provider" ) // sectionsHandler returns a handler that serves a single music section @@ -220,14 +223,11 @@ func TestProvider_Tracks(t *testing.T) { if !tr.Stream { t.Error("Stream = false, want true") } - if !strings.HasPrefix(tr.Path, srv.URL) { - t.Errorf("Path %q does not start with server URL", tr.Path) + if tr.Path != TrackURIPrefix+"200" { + t.Errorf("Path = %q, want token-free Plex URI", tr.Path) } - if !strings.Contains(tr.Path, "X-Plex-Token=tok") { - t.Errorf("Path %q missing X-Plex-Token", tr.Path) - } - if !strings.Contains(tr.Path, "/library/parts/1/111/SoWhat.flac") { - t.Errorf("Path %q missing part key", tr.Path) + if tr.Meta(provider.MetaPlexID) != "200" { + t.Errorf("Plex metadata ID = %q, want 200", tr.Meta(provider.MetaPlexID)) } } @@ -264,11 +264,53 @@ func TestProvider_Tracks_Playlist(t *testing.T) { if !tr.Stream { t.Error("Stream = false, want true") } - if !strings.Contains(tr.Path, "X-Plex-Token=tok") { - t.Errorf("Path %q missing X-Plex-Token", tr.Path) + if tr.Path != TrackURIPrefix+"300" { + t.Errorf("Path = %q, want token-free Plex URI", tr.Path) + } +} + +func TestProviderResolveSourceRestoresAfterRestart(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/library/metadata/200" { + t.Fatalf("path = %q, want metadata lookup", r.URL.Path) + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"MediaContainer":{"Metadata":[{"ratingKey":"200","Media":[{"Part":[{"key":"/library/parts/1/111/file.flac"}]}]}]}}`)) + })) + defer srv.Close() + + p := newProvider(NewClient(srv.URL, "tok")) + got, err := p.ResolveSource(TrackURIPrefix + "200") + if err != nil { + t.Fatalf("ResolveSource: %v", err) + } + want := srv.URL + "/library/parts/1/111/file.flac?X-Plex-Token=tok" + if got != want { + t.Fatalf("ResolveSource = %q, want %q", got, want) + } +} + +func TestProviderFavorites(t *testing.T) { + var gotRating string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/:/rate" { + t.Fatalf("path = %q, want /:/rate", r.URL.Path) + } + gotRating = r.URL.Query().Get("rating") + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() + + p := newProvider(NewClient(srv.URL, "tok")) + track := playlist.Track{Path: TrackURIPrefix + "200"} + if !p.CanFavoriteTrack(track) { + t.Fatal("CanFavoriteTrack = false") + } + if err := p.SetTrackFavorite(context.Background(), track, true); err != nil { + t.Fatalf("SetTrackFavorite: %v", err) } - if !strings.Contains(tr.Path, "/library/parts/3/333/HighwayToHell.flac") { - t.Errorf("Path %q missing part key", tr.Path) + if gotRating != "10" { + t.Fatalf("rating = %q, want 10", gotRating) } } diff --git a/provider/types.go b/provider/types.go index 4d5a31143..cdb1d0232 100644 --- a/provider/types.go +++ b/provider/types.go @@ -72,6 +72,7 @@ func YearFromDate(date string) int { // ProviderMeta key constants used across providers and the UI. const ( MetaNavidromeID = "navidrome.id" + MetaPlexID = "plex.id" MetaJellyfinID = "jellyfin.id" MetaEmbyID = "emby.id" MetaNetEaseID = "netease.id" diff --git a/providers.go b/providers.go index 60f3140e6..9bba91807 100644 --- a/providers.go +++ b/providers.go @@ -369,6 +369,16 @@ func (s *providerSet) registerPlayerHooks(p *player.Player) { } } switch prov := e.Provider.(type) { + case *plex.Provider: + // Persist only a logical ratingKey and add the Plex token in memory + // when playback starts. + p.RegisterSourceResolver(plex.TrackURIPrefix, func(uri string) (player.ResolvedSource, error) { + u, err := prov.ResolveSource(uri) + if err != nil { + return player.ResolvedSource{}, fmt.Errorf("resolve Plex source: %w", err) + } + return player.ResolvedSource{URL: u, Buffered: true}, nil + }) case *yandex.Provider: // Yandex tracks carry yandex:track: URIs; the provider resolves them // to a fresh signed stream URL when playback starts. diff --git a/providers_test.go b/providers_test.go index d2f4c4d48..96fa62752 100644 --- a/providers_test.go +++ b/providers_test.go @@ -18,6 +18,7 @@ import ( "github.com/bjarneo/cliamp/external/emby" "github.com/bjarneo/cliamp/external/jellyfin" "github.com/bjarneo/cliamp/external/navidrome" + "github.com/bjarneo/cliamp/external/plex" "github.com/bjarneo/cliamp/favorites" "github.com/bjarneo/cliamp/history" "github.com/bjarneo/cliamp/internal/resume" @@ -209,6 +210,16 @@ func TestProviderSetUsesCapabilities(t *testing.T) { } } +func TestProviderSetRegistersPlexSourceResolver(t *testing.T) { + prov := plex.NewFromConfig(config.PlexConfig{URL: "http://127.0.0.1:1", Token: "token"}) + set := &providerSet{entries: []provider.Entry{{Key: "plex", Name: "Plex", Provider: prov}}} + engine := &player.Player{} + set.registerPlayerHooks(engine) + if !engine.HasSourceResolver(plex.TrackURIPrefix + "42") { + t.Fatal("Plex source resolver was not registered") + } +} + // A page URL that playlist.IsYTDL accepts opens through yt-dlp, also when a // Jellyfin server registers a source resolver for every https URL. func TestPlayerHooksSendYTDLPagesToYTDLP(t *testing.T) { diff --git a/site/index.html b/site/index.html index d480de71c..3f37a2775 100644 --- a/site/index.html +++ b/site/index.html @@ -659,7 +659,7 @@

Close the tab. Play the music.

{name:"Telegram",kind:"streaming",note:"MTProto · phone login"}, {name:"Bandcamp",kind:"streaming",note:"your purchases · Subsonic API"}, {name:"Bilibili",kind:"streaming",note:"video audio · yt-dlp"}, - {name:"Plex",kind:"self-hosted",note:"server token"}, + {name:"Plex",kind:"self-hosted",note:"token-safe streams · synced likes"}, {name:"Jellyfin",kind:"self-hosted",note:"API key / password, gapless, resume"}, {name:"Emby",kind:"self-hosted",note:"API key / password, resume"}, {name:"Navidrome",kind:"self-hosted",note:"Subsonic API · lyrics"}, From ecca2c7de518aac043e9833e5d4bcb8828eb8d60 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 25 Oct 2026 08:23:40 +0100 Subject: [PATCH 02/32] feat(plex): report playback progress Plex playback previously left no timeline or play-history updates on the server. Report playing and stopped positions, scrobble tracks that pass cliamp's playback threshold, and document the headless behavior. Verified with: mise x go@1.26 -- go test ./external/plex ./ui/model . --- docs/headless.md | 2 +- docs/plex.md | 3 ++- external/plex/client.go | 27 +++++++++++++++++++++ external/plex/client_test.go | 44 ++++++++++++++++++++++++++++++++++ external/plex/provider.go | 44 ++++++++++++++++++++++++++++++++++ external/plex/provider_test.go | 39 ++++++++++++++++++++++++++++++ site/index.html | 2 +- 7 files changed, 158 insertions(+), 3 deletions(-) diff --git a/docs/headless.md b/docs/headless.md index a38079088..22d14ccb3 100644 --- a/docs/headless.md +++ b/docs/headless.md @@ -44,7 +44,7 @@ Headless mode runs the same player as the TUI. These features work the same way in both modes: - Lua plugins load from `~/.config/cliamp/plugins/`. Their hooks see playback events. -- Navidrome, Jellyfin, Emby, Audiobookshelf, and Yandex Music get now-playing and scrobble reports. Plex gets none. +- Navidrome, Plex, Jellyfin, Emby, Audiobookshelf, and Yandex Music get now-playing and scrobble reports. - A track enters Recently Played when it starts. See [Recently Played](history.md). - The IPC `save` operation, for example `cliamp remote call save --wait`, writes to the `[downloads]` directory. See [configuration.md](configuration.md#download-directory). - The next track preloads, so playback is gapless. diff --git a/docs/plex.md b/docs/plex.md index b7ab71d2c..11c95b2d8 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -59,6 +59,8 @@ Select a playlist or album to load its tracks. Smart playlists are included. The Press `f` on a Plex track to add or remove it from cliamp Favorites. The same change is copied to Plex and appears in Plexamp and other Plex clients. +While a Plex track plays, cliamp reports its timeline position about every 15 seconds. After at least half of a known-duration track has played, leaving the track records one Plex play and updates Plex history. Short skips do not increment the play count. + Start cliamp with Plex as the default provider: ```bash @@ -91,7 +93,6 @@ Fix: Open **System Settings > Privacy & Security > Local Network**. Enable acces ## Known limitations -- **No scrobbling**: cliamp does not report play counts to Plex. - **No playlist write-back**: cliamp cannot create or change Plex playlists. - **Token is long-lived**: Store it safely. It gives full access to the Plex account. - **Album list is flat**: Artist drill-down is not available. Search by scrolling or with cliamp search. diff --git a/external/plex/client.go b/external/plex/client.go index 79c72a0f5..2c331c72f 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -123,6 +123,33 @@ func (c *Client) SetRating(ctx context.Context, ratingKey string, rating float64 return c.doAction(ctx, http.MethodPut, "/:/rate", params) } +// ReportTimeline updates Plex's view of the current playback position. +func (c *Client) ReportTimeline(ctx context.Context, ratingKey, state string, position, duration time.Duration) error { + if ratingKey == "" { + return fmt.Errorf("plex: timeline: missing rating key") + } + params := url.Values{ + "key": {"/library/metadata/" + ratingKey}, + "ratingKey": {ratingKey}, + "state": {state}, + "time": {strconv.FormatInt(max(position.Milliseconds(), 0), 10)}, + "duration": {strconv.FormatInt(max(duration.Milliseconds(), 0), 10)}, + } + return c.doAction(ctx, http.MethodPost, "/:/timeline", params) +} + +// Scrobble records one completed play in Plex. +func (c *Client) Scrobble(ctx context.Context, ratingKey string) error { + if ratingKey == "" { + return fmt.Errorf("plex: scrobble: missing rating key") + } + params := url.Values{ + "identifier": {"com.plexapp.plugins.library"}, + "key": {ratingKey}, + } + return c.doAction(ctx, http.MethodPut, "/:/scrobble", params) +} + func (c *Client) doAction(ctx context.Context, method, endpoint string, params url.Values) error { req, err := http.NewRequestWithContext(ctx, method, c.baseURL+endpoint+"?"+params.Encode(), nil) if err != nil { diff --git a/external/plex/client_test.go b/external/plex/client_test.go index ecbd6ce9f..fe9a6bf3c 100644 --- a/external/plex/client_test.go +++ b/external/plex/client_test.go @@ -10,6 +10,7 @@ import ( "strconv" "strings" "testing" + "time" "github.com/bjarneo/cliamp/internal/httpclient" ) @@ -41,6 +42,49 @@ func TestSetRating(t *testing.T) { } } +func TestReportTimeline(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/:/timeline" { + t.Fatalf("request = %s %s, want POST /:/timeline", r.Method, r.URL.Path) + } + want := map[string]string{ + "key": "/library/metadata/track-42", + "ratingKey": "track-42", + "state": "playing", + "time": "1234", + "duration": "180000", + } + for key, value := range want { + if got := r.URL.Query().Get(key); got != value { + t.Errorf("%s = %q, want %q", key, got, value) + } + } + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() + + if err := newTestClient(srv).ReportTimeline(t.Context(), "track-42", "playing", 1234*time.Millisecond, 3*time.Minute); err != nil { + t.Fatalf("ReportTimeline: %v", err) + } +} + +func TestScrobble(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPut || r.URL.Path != "/:/scrobble" { + t.Fatalf("request = %s %s, want PUT /:/scrobble", r.Method, r.URL.Path) + } + if got := r.URL.Query().Get("key"); got != "track-42" { + t.Errorf("key = %q, want track-42", got) + } + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() + + if err := newTestClient(srv).Scrobble(t.Context(), "track-42"); err != nil { + t.Fatalf("Scrobble: %v", err) + } +} + // newTestClient returns a Client pointed at the given test server. func newTestClient(srv *httptest.Server) *Client { return NewClient(srv.URL, "test-token") diff --git a/external/plex/provider.go b/external/plex/provider.go index a26551e73..fb15ed248 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -2,10 +2,12 @@ package plex import ( "context" + "errors" "fmt" "slices" "strings" "sync" + "time" "github.com/bjarneo/cliamp/config" "github.com/bjarneo/cliamp/playlist" @@ -29,6 +31,7 @@ var ( _ provider.Searcher = (*Provider)(nil) _ provider.AlbumTrackLoader = (*Provider)(nil) _ provider.TrackFavoriter = (*Provider)(nil) + _ provider.ProgressReporter = (*Provider)(nil) ) // Provider implements playlist.Provider for a Plex Media Server. @@ -298,6 +301,47 @@ func plexTrackID(track playlist.Track) string { return id } +func plexTrackDuration(track playlist.Track) time.Duration { + return time.Duration(track.DurationSecs) * time.Second +} + +// CanReportPlayback reports whether track belongs to this Plex server. +func (p *Provider) CanReportPlayback(track playlist.Track) bool { + return plexTrackID(track) != "" +} + +// ReportNowPlaying sends the initial playing timeline update to Plex. +func (p *Provider) ReportNowPlaying(track playlist.Track, position time.Duration, _ bool) error { + id := plexTrackID(track) + if id == "" { + return nil + } + return p.client.ReportTimeline(context.Background(), id, "playing", position, plexTrackDuration(track)) +} + +// ReportProgress sends an interim playing timeline update to Plex. +func (p *Provider) ReportProgress(track playlist.Track, position time.Duration) error { + id := plexTrackID(track) + if id == "" { + return nil + } + return p.client.ReportTimeline(context.Background(), id, "playing", position, plexTrackDuration(track)) +} + +// ReportScrobble sends a final stopped timeline and records one completed play. +func (p *Provider) ReportScrobble(track playlist.Track, elapsed, duration time.Duration, _ bool) error { + id := plexTrackID(track) + if id == "" { + return nil + } + if duration <= 0 { + duration = plexTrackDuration(track) + } + timelineErr := p.client.ReportTimeline(context.Background(), id, "stopped", elapsed, duration) + scrobbleErr := p.client.Scrobble(context.Background(), id) + return errors.Join(timelineErr, scrobbleErr) +} + // AlbumTracks returns the tracks for the given album (ratingKey). // Implements provider.AlbumTrackLoader. func (p *Provider) AlbumTracks(albumID string) ([]playlist.Track, error) { diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index 59a69efab..708351b32 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -6,6 +6,7 @@ import ( "net/http/httptest" "strings" "testing" + "time" "github.com/bjarneo/cliamp/config" "github.com/bjarneo/cliamp/playlist" @@ -314,6 +315,44 @@ func TestProviderFavorites(t *testing.T) { } } +func TestProviderPlaybackReporting(t *testing.T) { + var timelineStates []string + scrobbleCount := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/:/timeline": + timelineStates = append(timelineStates, r.URL.Query().Get("state")) + if got := r.URL.Query().Get("duration"); got != "120000" { + t.Errorf("timeline duration = %q, want 120000", got) + } + case "/:/scrobble": + scrobbleCount++ + default: + t.Fatalf("unexpected path %q", r.URL.Path) + } + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() + + p := newProvider(NewClient(srv.URL, "tok")) + track := playlist.Track{Path: TrackURIPrefix + "200", DurationSecs: 120} + if err := p.ReportNowPlaying(track, 2*time.Second, true); err != nil { + t.Fatalf("ReportNowPlaying: %v", err) + } + if err := p.ReportProgress(track, 30*time.Second); err != nil { + t.Fatalf("ReportProgress: %v", err) + } + if err := p.ReportScrobble(track, 70*time.Second, 2*time.Minute, true); err != nil { + t.Fatalf("ReportScrobble: %v", err) + } + if got := strings.Join(timelineStates, ","); got != "playing,playing,stopped" { + t.Fatalf("timeline states = %q", got) + } + if scrobbleCount != 1 { + t.Fatalf("scrobble count = %d, want 1", scrobbleCount) + } +} + func TestProvider_Tracks_Playlist_NotCached(t *testing.T) { callCount := 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/site/index.html b/site/index.html index 3f37a2775..8739baed8 100644 --- a/site/index.html +++ b/site/index.html @@ -659,7 +659,7 @@

Close the tab. Play the music.

{name:"Telegram",kind:"streaming",note:"MTProto · phone login"}, {name:"Bandcamp",kind:"streaming",note:"your purchases · Subsonic API"}, {name:"Bilibili",kind:"streaming",note:"video audio · yt-dlp"}, - {name:"Plex",kind:"self-hosted",note:"token-safe streams · synced likes"}, + {name:"Plex",kind:"self-hosted",note:"token-safe · likes · scrobbling"}, {name:"Jellyfin",kind:"self-hosted",note:"API key / password, gapless, resume"}, {name:"Emby",kind:"self-hosted",note:"API key / password, resume"}, {name:"Navidrome",kind:"self-hosted",note:"Subsonic API · lyrics"}, From 002822f8add2000ecc840e260b8d94a7d40eac88 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 25 Oct 2026 08:24:55 +0100 Subject: [PATCH 03/32] feat(plex): refresh open lists Plex albums stayed cached for the whole process and open lists could not be reloaded in place. Add stable-list refresh support, expire album tracks after five minutes, preserve fresh smart playlists, and document the behavior. Verified with: mise x go@1.26 -- go test ./external/plex ./ui/model . --- docs/plex.md | 4 ++ external/plex/provider.go | 43 ++++++++++++------ external/plex/provider_test.go | 83 ++++++++++++++++++++++++++++++++++ site/index.html | 2 +- 4 files changed, 118 insertions(+), 14 deletions(-) diff --git a/docs/plex.md b/docs/plex.md index 11c95b2d8..13944588d 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -56,6 +56,10 @@ Artist - Album Title (Year) Select a playlist or album to load its tracks. Smart playlists are included. They resolve to current server content. +Press `Ctrl+R` while an open Plex album or playlist is focused to reload it +and pick up server-side changes. Album contents are cached for up to five +minutes; Plex playlists are always loaded fresh so smart playlists stay current. + Press `f` on a Plex track to add or remove it from cliamp Favorites. The same change is copied to Plex and appears in Plexamp and other Plex clients. diff --git a/external/plex/provider.go b/external/plex/provider.go index fb15ed248..43c7409e1 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -24,14 +24,21 @@ const ( prefixPlaylist = "pl:" sectionAlbums = "Albums" sectionPlaylists = "Playlists" + albumCacheTTL = 5 * time.Minute ) +type trackCacheEntry struct { + tracks []playlist.Track + loadedAt time.Time +} + // Compile-time interface checks. var ( - _ provider.Searcher = (*Provider)(nil) - _ provider.AlbumTrackLoader = (*Provider)(nil) - _ provider.TrackFavoriter = (*Provider)(nil) - _ provider.ProgressReporter = (*Provider)(nil) + _ playlist.RefreshablePlaylist = (*Provider)(nil) + _ provider.Searcher = (*Provider)(nil) + _ provider.AlbumTrackLoader = (*Provider)(nil) + _ provider.TrackFavoriter = (*Provider)(nil) + _ provider.ProgressReporter = (*Provider)(nil) ) // Provider implements playlist.Provider for a Plex Media Server. @@ -43,13 +50,14 @@ type Provider struct { client *Client mu sync.Mutex playlistCache []playlist.PlaylistInfo - trackCache map[string][]playlist.Track + trackCache map[string]trackCacheEntry partKeys map[string]string + now func() time.Time } // newProvider returns a Provider backed by the given Client. func newProvider(client *Client) *Provider { - return &Provider{client: client} + return &Provider{client: client, now: time.Now} } // NewFromConfig returns a Provider from a PlexConfig, or nil if URL or Token is missing. @@ -132,26 +140,35 @@ func (p *Provider) Refresh() { p.mu.Lock() p.playlistCache = nil p.trackCache = nil + p.partKeys = nil p.mu.Unlock() } +// CanRefreshPlaylist reports whether id is a stable Plex album or playlist +// ratingKey that can be reloaded in place after Refresh. +func (p *Provider) CanRefreshPlaylist(id string) bool { + id = strings.TrimPrefix(id, prefixPlaylist) + return validRatingKey(id) +} + // Tracks returns the tracks for the playlist or album identified by // playlistID. Playlist IDs (prefixed "pl:") load via the server playlists // endpoint; album IDs load via the album children endpoint. Tracks with no // ratingKey or streamable part are silently skipped. Track paths are token-free // logical URIs; ResolveSource creates the authenticated URL only when playback -// starts. Album tracks -// are cached per album ID; playlist tracks are intentionally not cached so -// smart playlists always reflect their current server contents. +// starts. Album tracks are cached per album ID; playlist tracks are +// intentionally not cached so smart playlists always reflect current server +// contents. func (p *Provider) Tracks(playlistID string) ([]playlist.Track, error) { isPlaylist := strings.HasPrefix(playlistID, prefixPlaylist) p.mu.Lock() if !isPlaylist && p.trackCache != nil { - if cached, ok := p.trackCache[playlistID]; ok { + if cached, ok := p.trackCache[playlistID]; ok && p.now().Sub(cached.loadedAt) < albumCacheTTL { p.mu.Unlock() - return slices.Clone(cached), nil + return slices.Clone(cached.tracks), nil } + delete(p.trackCache, playlistID) } p.mu.Unlock() @@ -173,9 +190,9 @@ func (p *Provider) Tracks(playlistID string) ([]playlist.Track, error) { if !isPlaylist { p.mu.Lock() if p.trackCache == nil { - p.trackCache = make(map[string][]playlist.Track) + p.trackCache = make(map[string]trackCacheEntry) } - p.trackCache[playlistID] = tracks + p.trackCache[playlistID] = trackCacheEntry{tracks: tracks, loadedAt: p.now()} p.mu.Unlock() } diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index 708351b32..ca997a553 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -2,6 +2,7 @@ package plex import ( "context" + "fmt" "net/http" "net/http/httptest" "strings" @@ -429,6 +430,88 @@ func TestProvider_Tracks_Cached(t *testing.T) { } } +func TestProvider_Tracks_AlbumCacheTTL(t *testing.T) { + callCount := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + callCount++ + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"MediaContainer":{"Metadata":[{"ratingKey":"1","title":"T%d","Media":[{"Part":[{"key":"/p/1/f.mp3"}]}]}]}}`, callCount) + })) + defer srv.Close() + + now := time.Date(2026, 10, 24, 12, 0, 0, 0, time.UTC) + p := newProvider(NewClient(srv.URL, "tok")) + p.now = func() time.Time { return now } + if _, err := p.Tracks("99"); err != nil { + t.Fatalf("first Tracks: %v", err) + } + + now = now.Add(albumCacheTTL - time.Second) + if _, err := p.Tracks("99"); err != nil { + t.Fatalf("cached Tracks: %v", err) + } + if callCount != 1 { + t.Fatalf("request count before TTL = %d, want 1", callCount) + } + + now = now.Add(time.Second) + refreshed, err := p.Tracks("99") + if err != nil { + t.Fatalf("expired Tracks: %v", err) + } + if callCount != 2 { + t.Fatalf("request count after TTL = %d, want 2", callCount) + } + if got := refreshed[0].Title; got != "T2" { + t.Fatalf("title after TTL = %q, want T2", got) + } +} + +func TestProviderRefreshReloadsOpenList(t *testing.T) { + callCount := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + callCount++ + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"MediaContainer":{"Metadata":[{"ratingKey":"1","title":"T%d","Media":[{"Part":[{"key":"/p/1/f.mp3"}]}]}]}}`, callCount) + })) + defer srv.Close() + + p := newProvider(NewClient(srv.URL, "tok")) + if _, err := p.Tracks("99"); err != nil { + t.Fatalf("first Tracks: %v", err) + } + p.Refresh() + refreshed, err := p.Tracks("99") + if err != nil { + t.Fatalf("Tracks after Refresh: %v", err) + } + if callCount != 2 { + t.Fatalf("request count after Refresh = %d, want 2", callCount) + } + if got := refreshed[0].Title; got != "T2" { + t.Fatalf("title after Refresh = %q, want T2", got) + } +} + +func TestProviderCanRefreshPlaylist(t *testing.T) { + p := newProvider(NewClient("http://localhost:32400", "tok")) + for _, tt := range []struct { + id string + want bool + }{ + {id: "99", want: true}, + {id: "album_key-1", want: true}, + {id: "pl:24872", want: true}, + {id: "", want: false}, + {id: "pl:", want: false}, + {id: "browse/albums", want: false}, + } { + if got := p.CanRefreshPlaylist(tt.id); got != tt.want { + t.Errorf("CanRefreshPlaylist(%q) = %v, want %v", tt.id, got, tt.want) + } + } +} + func TestProvider_Tracks_ClientError(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUnauthorized) diff --git a/site/index.html b/site/index.html index 8739baed8..e6021b73f 100644 --- a/site/index.html +++ b/site/index.html @@ -659,7 +659,7 @@

Close the tab. Play the music.

{name:"Telegram",kind:"streaming",note:"MTProto · phone login"}, {name:"Bandcamp",kind:"streaming",note:"your purchases · Subsonic API"}, {name:"Bilibili",kind:"streaming",note:"video audio · yt-dlp"}, - {name:"Plex",kind:"self-hosted",note:"token-safe · likes · scrobbling"}, + {name:"Plex",kind:"self-hosted",note:"token-safe · favorites · refresh · scrobbles"}, {name:"Jellyfin",kind:"self-hosted",note:"API key / password, gapless, resume"}, {name:"Emby",kind:"self-hosted",note:"API key / password, resume"}, {name:"Navidrome",kind:"self-hosted",note:"Subsonic API · lyrics"}, From d81e433bac65b192d7e68d7e0c78377394baae85 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 25 Oct 2026 08:56:57 +0100 Subject: [PATCH 04/32] feat(plex): add browser account login Manual token setup could not discover Plex servers or follow a server between local and remote networks. Add browser PIN authorization, reachable server selection, stable device identity, and runtime connection rediscovery while retaining the manual URL-and-token path. Verified with: mise x go@1.26 -- make check Verified with: mise x go@1.26 -- go test -race ./cmd ./config ./external/plex --- cmd/setup.go | 212 +++++++++++++++++++++- cmd/setup_save_test.go | 7 + cmd/setup_test.go | 104 +++++++++++ config.toml.example | 4 + config/config.go | 16 +- config/config_golden_test.go | 8 +- config/config_test.go | 10 ++ docs/cli.md | 2 +- docs/configuration.md | 4 +- docs/plex.md | 41 ++++- external/plex/account.go | 319 +++++++++++++++++++++++++++++++++ external/plex/account_test.go | 178 ++++++++++++++++++ external/plex/client.go | 85 ++++++++- external/plex/client_test.go | 53 ++++++ external/plex/provider.go | 4 + external/plex/provider_test.go | 12 ++ site/index.html | 2 +- 17 files changed, 1032 insertions(+), 29 deletions(-) create mode 100644 external/plex/account.go create mode 100644 external/plex/account_test.go diff --git a/cmd/setup.go b/cmd/setup.go index d9fe11750..673aa6343 100644 --- a/cmd/setup.go +++ b/cmd/setup.go @@ -37,6 +37,7 @@ import ( "github.com/bjarneo/cliamp/external/netease" "github.com/bjarneo/cliamp/external/plex" "github.com/bjarneo/cliamp/external/telegram" + "github.com/bjarneo/cliamp/internal/browser" ) // Setup launches the interactive wizard. Returns nil on clean exit. @@ -140,6 +141,7 @@ type pickerOption struct { // leading underscore distinguishes them from TOML field names. const ( keyJellyfinAuth = "_auth" + keyPlexAuth = "_plex_auth" keyEmbyAuth = "_emby_auth" keyABSAuth = "_abs_auth" keyNetEaseBrowser = "_netease_browser" @@ -246,23 +248,42 @@ func providers() []providerSpec { name: "Plex Media Server", section: "plex", intro: []string{ - "Stream from your Plex server using an X-Plex-Token.", - "Find a token: https://support.plex.tv/articles/204059436", + "Sign in with Plex to discover local and remote servers automatically.", + "Manual URL and X-Plex-Token setup remains available.", + }, + picker: &pickerSpec{ + key: keyPlexAuth, + label: "Authentication", + options: []pickerOption{ + {value: "account", label: "Sign in with Plex in a browser (recommended)"}, + {value: "manual", label: "Enter a server URL and X-Plex-Token"}, + }, }, fields: []fieldSpec{ - {key: "url", label: "Server URL", help: "e.g. http://192.168.1.10:32400", required: true}, - {key: "token", label: "X-Plex-Token", required: true, secret: true}, + {key: "url", label: "Server URL", help: "e.g. http://192.168.1.10:32400", required: true, + onlyIf: func(v map[string]string) bool { return v[keyPlexAuth] == "manual" }}, + {key: "token", label: "X-Plex-Token", required: true, secret: true, + onlyIf: func(v map[string]string) bool { return v[keyPlexAuth] == "manual" }}, {key: "libraries", label: "Music libraries (optional)", help: "comma-separated names to include; blank loads every music library"}, }, validate: func(v map[string]string) error { + if v[keyPlexAuth] == "account" { + return nil + } return plex.NewClient(v["url"], v["token"]).Ping() }, - owned: []string{"url", "token", "libraries"}, + owned: []string{"url", "token", "client_id", "server_id", "libraries"}, body: func(v map[string]string) []config.KeyValue { kv := []config.KeyValue{ quotedKV("url", v["url"]), quotedKV("token", v["token"]), } + if v[keyPlexAuth] == "account" { + kv = append(kv, + quotedKV("client_id", v["client_id"]), + quotedKV("server_id", v["server_id"]), + ) + } if libraries := setupStringList(v["libraries"]); libraries != "" { kv = append(kv, rawKV("libraries", libraries)) } @@ -946,6 +967,13 @@ func setupStringList(value string) string { return "[" + strings.Join(quoted, ", ") + "]" } +func plexSetupClientID() (string, error) { + if cfg, err := config.Load(); err == nil && cfg.Plex.ClientID != "" { + return cfg.Plex.ClientID, nil + } + return plex.NewClientIdentifier() +} + // ----- Bubbletea model ---------------------------------------------------- type stage int @@ -957,9 +985,16 @@ const ( stageChats stageConfirm stageValidating + stagePlexServer stageResult ) +type plexServerChoice struct { + server plex.ReachableServer + token string + clientID string +} + type setupModel struct { provs []providerSpec w, h int @@ -992,6 +1027,11 @@ type setupModel struct { // validating spinFrame int + authURL string + + // Plex account server selection + plexServers []plexServerChoice + plexServerCursor int // result state resultErr error @@ -1036,6 +1076,20 @@ type validateDoneMsg struct { type spinTickMsg struct{} +type plexAuthStartedMsg struct { + api *plex.AccountAPI + session *plex.SignInSession + clientID string + err error +} + +type plexAuthDoneMsg struct { + clientID string + token string + servers []plex.ReachableServer + err error +} + func spinTickCmd() tea.Cmd { return tea.Tick(120*time.Millisecond, func(time.Time) tea.Msg { return spinTickMsg{} }) } @@ -1120,6 +1174,36 @@ func chatKey(id string) string { return parts[0] + ":" + parts[1] } +func beginPlexAuthCmd(clientID string) tea.Cmd { + return func() tea.Msg { + api := plex.NewAccountAPI() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + session, err := api.BeginSignIn(ctx, clientID) + return plexAuthStartedMsg{api: api, session: session, clientID: clientID, err: err} + } +} + +func waitPlexAuthCmd(api *plex.AccountAPI, session *plex.SignInSession, clientID string) tea.Cmd { + return func() tea.Msg { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + token, err := session.Wait(ctx) + if err != nil { + return plexAuthDoneMsg{err: err} + } + servers, err := api.ReachableServers(ctx, token, clientID) + return plexAuthDoneMsg{clientID: clientID, token: token, servers: servers, err: err} + } +} + +func openBrowserCmd(rawURL string) tea.Cmd { + return func() tea.Msg { + _ = browser.Open(rawURL) + return nil + } +} + // ----- Update ------------------------------------------------------------- func (m *setupModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { @@ -1163,6 +1247,29 @@ func (m *setupModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case validateDoneMsg: return m.onValidateDone(msg.err, msg.found) + + case plexAuthStartedMsg: + if msg.err != nil { + return m.onPlexAuthError(msg.err) + } + m.authURL = msg.session.URL() + return m, tea.Batch(openBrowserCmd(m.authURL), waitPlexAuthCmd(msg.api, msg.session, msg.clientID)) + + case plexAuthDoneMsg: + if msg.err != nil { + return m.onPlexAuthError(msg.err) + } + m.plexServers = make([]plexServerChoice, 0, len(msg.servers)) + for _, server := range msg.servers { + m.plexServers = append(m.plexServers, plexServerChoice{server: server, token: msg.token, clientID: msg.clientID}) + } + m.plexServerCursor = 0 + if len(m.plexServers) == 1 { + m.applyPlexServer(m.plexServers[0]) + return m, m.persistAndDone(false) + } + m.stage = stagePlexServer + return m, nil } return m, nil } @@ -1226,6 +1333,8 @@ func (m *setupModel) handleKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) { case stageValidating: // Ignore input while probing. return m, nil + case stagePlexServer: + return m.plexServerKey(msg) case stageResult: return m.resultKey(msg) } @@ -1270,6 +1379,9 @@ func (m *setupModel) startProvider(idx int) { m.chatItems, m.chatChecked, m.chatCursor, m.chatErr, m.chatWarn, m.chatLoading = nil, nil, 0, nil, nil, false m.chatTouched, m.chatNote = false, "" m.chatNames = nil + m.authURL = "" + m.plexServers = nil + m.plexServerCursor = 0 if m.provs[idx].picker != nil { m.stage = stagePicker @@ -1305,6 +1417,43 @@ func (m *setupModel) pickerKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) { return m, nil } +func (m *setupModel) plexServerKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) { + switch msg.String() { + case "esc": + m.stage = stageMenu + case "up", "k": + if m.plexServerCursor > 0 { + m.plexServerCursor-- + } + case "down", "j": + if m.plexServerCursor < len(m.plexServers)-1 { + m.plexServerCursor++ + } + case "enter": + if len(m.plexServers) == 0 { + return m, nil + } + m.applyPlexServer(m.plexServers[m.plexServerCursor]) + return m, m.persistAndDone(false) + } + return m, nil +} + +func (m *setupModel) applyPlexServer(choice plexServerChoice) { + m.values["url"] = choice.server.URL + m.values["token"] = choice.token + m.values["client_id"] = choice.clientID + m.values["server_id"] = choice.server.ClientIdentifier + m.values[keyPlexAuth] = "account" +} + +func (m *setupModel) onPlexAuthError(err error) (tea.Model, tea.Cmd) { + m.resultErr = err + m.awaitingSave = false + m.stage = stageResult + return m, nil +} + func (m *setupModel) formKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) { if len(m.visible) == 0 { // Defensive: shouldn't happen; submit anyway. @@ -1622,6 +1771,19 @@ func (m *setupModel) submitForm() (tea.Model, tea.Cmd) { } } + if spec.section == "plex" && m.values[keyPlexAuth] == "account" { + clientID, err := plexSetupClientID() + if err != nil { + m.resultErr = err + m.stage = stageResult + return m, nil + } + m.stage = stageValidating + m.spinFrame = 0 + m.authURL = "" + return m, tea.Batch(spinTickCmd(), beginPlexAuthCmd(clientID)) + } + // Light URL sanity check before any network call. A $NAME value stays // as typed, and the check reads the variable. if u, ok := m.values["url"]; ok && u != "" { @@ -1803,6 +1965,8 @@ func (m *setupModel) View() tea.View { body = m.viewConfirm() case stageValidating: body = m.viewValidating() + case stagePlexServer: + body = m.viewPlexServers() case stageResult: body = m.viewResult() } @@ -2026,11 +2190,43 @@ func (m *setupModel) viewChats() string { func (m *setupModel) viewValidating() string { frames := []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"} frame := frames[m.spinFrame%len(frames)] - body := accentStyle.Render(frame) + " " + - "Verifying connection to " + m.provs[m.pidx].name + "…" + message := "Verifying connection to " + m.provs[m.pidx].name + "…" + if m.provs[m.pidx].section == "plex" && m.values[keyPlexAuth] == "account" { + message = "Waiting for Plex browser sign-in…" + if m.authURL != "" { + message += "\n\nIf the browser did not open, visit:\n" + m.authURL + } + } + body := accentStyle.Render(frame) + " " + message return cardStyle.Width(min(maxCardWidth, m.viewWidth())).Render(body) } +func (m *setupModel) viewPlexServers() string { + var b strings.Builder + b.WriteString(accentStyle.Render("Select a Plex Media Server")) + b.WriteString("\n\n") + for i, choice := range m.plexServers { + marker := " " + label := choice.server.Name + if choice.server.Owned { + label += " (owned)" + } else { + label += " (shared)" + } + if i == m.plexServerCursor { + marker = accentStyle.Render("▸ ") + label = accentStyle.Render(label) + } + b.WriteString(marker) + b.WriteString(label) + b.WriteString("\n") + b.WriteString(" ") + b.WriteString(dimStyle.Render(choice.server.URL)) + b.WriteString("\n") + } + return m.card(strings.TrimRight(b.String(), "\n")) +} + func (m *setupModel) viewResult() string { spec := m.provs[m.pidx] var b strings.Builder @@ -2108,6 +2304,8 @@ func (m *setupModel) viewFooter() string { keys = "y save n discard esc keep editing" case stageValidating: keys = "ctrl+c cancel" + case stagePlexServer: + keys = "↑/↓ pick enter select esc cancel" case stageResult: switch { case m.awaitingSave: diff --git a/cmd/setup_save_test.go b/cmd/setup_save_test.go index df0ae98b8..844c1836e 100644 --- a/cmd/setup_save_test.go +++ b/cmd/setup_save_test.go @@ -73,6 +73,13 @@ func TestSetupRewriteKeepsUserLines(t *testing.T) { initial: "[spotify]\nenabled = false\nclient_id = \"old\"\nbitrate = 160\n", want: "[spotify]\nbitrate = 320\n", }, + { + name: "plex manual setup drops account discovery fields", + section: "plex", + values: map[string]string{keyPlexAuth: "manual", "url": "http://plex.local:32400", "token": "manual-token"}, + initial: "[plex]\nurl = \"https://old.plex.direct:32400\"\ntoken = \"account-token\"\nclient_id = \"client-1\"\nserver_id = \"server-1\"\n", + want: "[plex]\nurl = \"http://plex.local:32400\"\ntoken = \"manual-token\"\n", + }, { name: "no config file", section: "qobuz", diff --git a/cmd/setup_test.go b/cmd/setup_test.go index cbfaf21bb..e82d15eb7 100644 --- a/cmd/setup_test.go +++ b/cmd/setup_test.go @@ -10,6 +10,7 @@ import ( tea "charm.land/bubbletea/v2" "github.com/bjarneo/cliamp/config" + "github.com/bjarneo/cliamp/external/plex" ) // keyPress builds a synthetic key event matching what the runtime sends. @@ -100,6 +101,109 @@ func TestPickerSelectionFiltersFields(t *testing.T) { } } +func TestPlexPickerSelectionFiltersFields(t *testing.T) { + m := newSetupModel() + plexIdx := -1 + for i, p := range m.provs { + if p.section == "plex" { + plexIdx = i + break + } + } + if plexIdx < 0 { + t.Fatal("plex spec missing") + } + + m.startProvider(plexIdx) + m.pickerCursor = 0 + m.handleKey(keyPress(tea.KeyEnter, "")) + if m.stage != stageForm || len(m.visible) != 1 || m.provs[plexIdx].fields[m.visible[0]].key != "libraries" { + t.Fatalf("account mode visible fields = %v", m.visible) + } + + m.stage = stagePicker + m.values = map[string]string{} + m.pickerCursor = 1 + m.handleKey(keyPress(tea.KeyEnter, "")) + var keys []string + for _, idx := range m.visible { + keys = append(keys, m.provs[plexIdx].fields[idx].key) + } + if got := strings.Join(keys, ","); got != "url,token,libraries" { + t.Fatalf("manual mode visible fields = %q", got) + } +} + +func TestPlexAuthServerSelectionSavesAccountConfig(t *testing.T) { + dir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", dir) + m := newSetupModel() + for i, p := range m.provs { + if p.section == "plex" { + m.pidx = i + break + } + } + m.values = map[string]string{keyPlexAuth: "account", "libraries": "Music"} + m.stage = stageValidating + + m.Update(plexAuthDoneMsg{ + clientID: "client-1", + token: "account-token", + servers: []plex.ReachableServer{ + {Name: "Home", ClientIdentifier: "home", URL: "https://home.plex.direct:32400", Owned: true}, + {Name: "Shared", ClientIdentifier: "shared", URL: "https://shared.plex.direct:32400"}, + }, + }) + if m.stage != stagePlexServer { + t.Fatalf("stage = %v, want stagePlexServer", m.stage) + } + m.handleKey(keyPress(tea.KeyDown, "")) + m.handleKey(keyPress(tea.KeyEnter, "")) + + cfg, err := config.Load() + if err != nil { + t.Fatalf("Load: %v", err) + } + if cfg.Plex.URL != "https://shared.plex.direct:32400" || cfg.Plex.Token != "account-token" || + cfg.Plex.ClientID != "client-1" || cfg.Plex.ServerID != "shared" { + t.Fatalf("saved Plex config = %+v", cfg.Plex) + } + if got := strings.Join(cfg.Plex.Libraries, ","); got != "Music" { + t.Fatalf("libraries = %q", got) + } +} + +func TestPlexAuthErrorCannotSaveIncompleteConfig(t *testing.T) { + m := newSetupModel() + for i, p := range m.provs { + if p.section == "plex" { + m.pidx = i + break + } + } + m.stage = stageValidating + m.Update(plexAuthDoneMsg{err: errors.New("sign in failed")}) + if m.stage != stageResult || m.awaitingSave { + t.Fatalf("stage = %v, awaitingSave = %v", m.stage, m.awaitingSave) + } +} + +func TestPlexSetupReusesClientIdentifier(t *testing.T) { + dir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", dir) + if err := os.WriteFile(filepath.Join(dir, "config.toml"), []byte("[plex]\nurl = \"https://plex\"\ntoken = \"token\"\nclient_id = \"existing-client\"\nserver_id = \"server\"\n"), 0o600); err != nil { + t.Fatal(err) + } + got, err := plexSetupClientID() + if err != nil { + t.Fatal(err) + } + if got != "existing-client" { + t.Fatalf("client ID = %q, want existing-client", got) + } +} + // TestEmbyPickerSelectionFiltersFields mirrors TestPickerSelectionFiltersFields // for the Emby provider, which uses the same token/password picker shape. func TestEmbyPickerSelectionFiltersFields(t *testing.T) { diff --git a/config.toml.example b/config.toml.example index 305ddacb4..a493ba05d 100644 --- a/config.toml.example +++ b/config.toml.example @@ -306,6 +306,10 @@ eq = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # [plex] # url = "http://192.168.1.10:32400" # token = "xxxxxxxxxxxxxxxxxxxx" +# Browser sign-in through `cliamp setup` also writes these fields. They let +# cliamp rediscover the selected server when its local or remote address changes. +# client_id = "generated-per-installation-id" +# server_id = "selected-server-id" # # Restrict to specific music libraries (comma-separated, case-insensitive). # When omitted or empty, all music libraries are loaded. diff --git a/config/config.go b/config/config.go index efb142d86..d74fa8544 100644 --- a/config/config.go +++ b/config/config.go @@ -663,18 +663,22 @@ func (y *YandexConfig) set(key, val string) { } } -// PlexConfig holds credentials for a Plex Media Server. -// Both URL and Token must be non-empty for a client to be constructed. +// PlexConfig holds credentials for a Plex Media Server. ClientID and ServerID +// identify browser-authorized account setups; configs without them retain the +// manual URL-and-token behavior. // Enable rule: credentials. type PlexConfig struct { URL string // e.g. "http://192.168.1.10:32400" Token string // X-Plex-Token + ClientID string // stable identifier of this cliamp installation + ServerID string // selected Plex Media Server clientIdentifier Libraries []string // optional: restrict to these music library names } -// IsSet reports whether both Plex credentials are present. +// IsSet reports whether a manual URL or an account-discovery server is +// configured together with a token. func (p PlexConfig) IsSet() bool { - return p.URL != "" && p.Token != "" + return p.Token != "" && (p.URL != "" || (p.ClientID != "" && p.ServerID != "")) } // set applies one key of the [plex] section. @@ -684,6 +688,10 @@ func (p *PlexConfig) set(key, val string) { p.URL = parseString(val) case "token": p.Token = parseString(val) + case "client_id": + p.ClientID = parseString(val) + case "server_id": + p.ServerID = parseString(val) case "libraries": p.Libraries = parseStringSlice(val) } diff --git a/config/config_golden_test.go b/config/config_golden_test.go index b37974a10..705f4721f 100644 --- a/config/config_golden_test.go +++ b/config/config_golden_test.go @@ -379,7 +379,13 @@ func TestLoadGolden(t *testing.T) { UserID: "optional-account-user-id", } allWant.Yandex = YandexConfig{Enabled: true, Token: "y0_YourPersonalOAuthToken"} - allWant.Plex = PlexConfig{URL: "http://192.168.1.10:32400", Token: "xxxxxxxxxxxxxxxxxxxx", Libraries: []string{"Music", "Jazz"}} + allWant.Plex = PlexConfig{ + URL: "http://192.168.1.10:32400", + Token: "xxxxxxxxxxxxxxxxxxxx", + ClientID: "generated-per-installation-id", + ServerID: "selected-server-id", + Libraries: []string{"Music", "Jazz"}, + } allWant.Jellyfin = JellyfinConfig{ URL: "https://jellyfin.example.com", Token: "optional-api-token", diff --git a/config/config_test.go b/config/config_test.go index 96d6ea4f2..7e7562943 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -716,6 +716,7 @@ func TestPlexIsSet(t *testing.T) { want bool }{ {"both set", PlexConfig{URL: "http://x", Token: "t"}, true}, + {"account discovery", PlexConfig{Token: "t", ClientID: "client", ServerID: "server"}, true}, {"no URL", PlexConfig{Token: "t"}, false}, {"no token", PlexConfig{URL: "http://x"}, false}, {"empty", PlexConfig{}, false}, @@ -729,6 +730,15 @@ func TestPlexIsSet(t *testing.T) { } } +func TestPlexAccountFields(t *testing.T) { + var cfg PlexConfig + cfg.set("client_id", `"client-1"`) + cfg.set("server_id", `"server-1"`) + if cfg.ClientID != "client-1" || cfg.ServerID != "server-1" { + t.Fatalf("Plex account fields = %+v", cfg) + } +} + func TestJellyfinIsSet(t *testing.T) { tests := []struct { name string diff --git a/docs/cli.md b/docs/cli.md index eec6b4a37..eaa364132 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -163,7 +163,7 @@ CLI flags override config file values for the current session only. Persisted bo ## Setup wizard -Configure remote providers through a small TUI. Supported providers are Navidrome, Lyrion, Plex, Jellyfin, Emby, Spotify, Qobuz, Tidal, Bandcamp, Mixcloud, NetEase, Audiobookshelf, YouTube Music, and Telegram. Each provider page links to its required credentials. The wizard writes the provider keys into the `[provider]` section of `~/.config/cliamp/config.toml` and leaves the rest of the file unchanged. For YouTube Music, it edits an existing `[youtube]` or `[yt]` section. It checks the server connection during setup for Navidrome, Lyrion, Plex, Jellyfin, Emby, and Audiobookshelf, the Subsonic credentials for Bandcamp, and the browser session for NetEase. OAuth providers (Spotify, Qobuz, Tidal) authenticate later in the player. Setup does not check Mixcloud credentials. Telegram asks for the login code in the pane when the session is missing, or right after saving in setup. +Configure remote providers through a small TUI. Supported providers are Navidrome, Lyrion, Plex, Jellyfin, Emby, Spotify, Qobuz, Tidal, Bandcamp, Mixcloud, NetEase, Audiobookshelf, YouTube Music, and Telegram. Each provider page links to its required credentials. The wizard writes the provider keys into the `[provider]` section of `~/.config/cliamp/config.toml` and leaves the rest of the file unchanged. For YouTube Music, it edits an existing `[youtube]` or `[yt]` section. Plex supports browser sign-in, automatic server discovery, and server selection as well as manual URL-and-token setup. It checks the server connection during setup for Navidrome, Lyrion, Plex, Jellyfin, Emby, and Audiobookshelf, the Subsonic credentials for Bandcamp, and the browser session for NetEase. OAuth providers (Spotify, Qobuz, Tidal) authenticate later in the player. Setup does not check Mixcloud credentials. Telegram asks for the login code in the pane when the session is missing, or right after saving in setup. ```sh cliamp setup diff --git a/docs/configuration.md b/docs/configuration.md index 3b5a2e905..3e09cf298 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -8,7 +8,7 @@ cliamp setup The wizard writes the provider keys into their section. It keeps your other keys and comments, and it leaves the rest of your config unchanged. The wizard drops the comment at the end of a key line that it rewrites. -The wizard checks the server connection during setup for Navidrome, Lyrion, Plex, Jellyfin, Emby, and Audiobookshelf. For Bandcamp, it checks the Subsonic credentials with an authenticated call. For NetEase, it checks the browser session. OAuth providers such as Spotify, Qobuz, and Tidal sign in later in the player. Tidal uses a `link.tidal.com` device code. The wizard does not check Mixcloud credentials. See [cli.md](cli.md#setup-wizard) for details. +The wizard checks the server connection during setup for Navidrome, Lyrion, Plex, Jellyfin, Emby, and Audiobookshelf. Plex can sign in through the browser, discover local and remote servers, and let you select one; fixed URL-and-token setup remains available. For Bandcamp, it checks the Subsonic credentials with an authenticated call. For NetEase, it checks the browser session. OAuth providers such as Spotify, Qobuz, and Tidal sign in later in the player. Tidal uses a `link.tidal.com` device code. The wizard does not check Mixcloud credentials. See [cli.md](cli.md#setup-wizard) for details. ## Config directory @@ -369,7 +369,7 @@ Each provider section turns on its provider in one of three ways: | Rule | Providers | The provider starts when | | --- | --- | --- | -| Credentials | Navidrome, Lyrion, Bandcamp, Plex, Jellyfin, Emby, Audiobookshelf, Telegram | The section holds the required credentials. Lyrion needs only `url`. Bandcamp needs `user` and `password` (its `url` is optional); Telegram needs `api_id` and `api_hash`. | +| Credentials | Navidrome, Lyrion, Bandcamp, Plex, Jellyfin, Emby, Audiobookshelf, Telegram | The section holds the required credentials. Plex browser sign-in writes its discovered server and token; manual URL-and-token setup is also supported. Lyrion needs only `url`. Bandcamp needs `user` and `password` (its `url` is optional); Telegram needs `api_id` and `api_hash`. | | Section | Spotify, Qobuz, Tidal, YouTube Music | The section header exists. Set `enabled = false` to turn the provider off. | | Opt-in | SoundCloud, Mixcloud, NetEase, Yandex | The section sets `enabled = true`. Yandex also needs `token`. | diff --git a/docs/plex.md b/docs/plex.md index 13944588d..b5a54fcf5 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -2,15 +2,40 @@ Use cliamp to stream music from Plex Media Server, including any library served by PlexAmp. Streaming uses the Plex HTTP API. You do not need extra software. -> **Quick start:** Run `cliamp setup`. Enter the server URL and `X-Plex-Token`, and optionally a comma-separated list of music libraries to include. The TUI checks the token and writes the `[plex]` block. Manual steps follow. +> **Quick start:** Run `cliamp setup`, select **Sign in with Plex**, approve +> cliamp in the browser, and select a server. cliamp discovers and verifies +> local, remote, and relay connections automatically. Manual setup remains +> available. ## Prerequisites -- Plex Media Server running and reachable on your network (or remotely) +- Plex Media Server running and signed in to your Plex account - At least one music library configured in Plex -- Your `X-Plex-Token` (see below) -## Finding your X-Plex-Token +For access away from home, enable Plex Remote Access. Plex Relay is used as a +fallback when the account advertises no reachable direct connection. + +## Browser sign-in + +Run `cliamp setup`, select **Plex Media Server**, and keep the recommended +browser sign-in option. cliamp opens the Plex-hosted authorization page and +waits for approval. If more than one server is available, select one in the +wizard. The chosen server and a stable identifier for this cliamp installation +are saved in `[plex]`. + +On every start, cliamp asks Plex for the selected server's current connection +addresses. It prefers a reachable local address, then a secure direct remote +address, and finally a secure relay. Public plain-HTTP addresses are never +selected. Pressing `Ctrl+R` also repeats connection discovery. + +This means the same configuration can move between home and work without +hard-coding a `192.168.x.x` address. Remote playback still requires the Plex +server to advertise a reachable remote or relay connection. + +## Manual token setup + +To configure a fixed server URL instead, select the manual option in setup or +find an `X-Plex-Token`: 1. Open Plex Web in a browser and sign in. 2. Browse to an item in the music library. @@ -27,6 +52,8 @@ Add a `[plex]` section to `~/.config/cliamp/config.toml`: [plex] url = "http://192.168.1.10:32400" token = "xxxxxxxxxxxxxxxxxxxx" +client_id = "generated-per-installation-id" +server_id = "selected-server-id" libraries = ["Music", "Jazz"] ``` @@ -34,9 +61,13 @@ libraries = ["Music", "Jazz"] |-----|-------------| | `url` | Plex Media Server base URL, including port (default `32400`) | | `token` | `X-Plex-Token` for authentication | +| `client_id` | Stable cliamp installation ID written by browser sign-in | +| `server_id` | Selected Plex Media Server ID written by browser sign-in | | `libraries` | Optional comma-separated music library names to load. If omitted, cliamp loads all music libraries. Name matching is case-insensitive. | -If you access Plex remotely through `app.plex.tv`, use a direct server URL when remote access is enabled. You can also use the server `plex.direct` URL from the Plex Web address bar. +`client_id` and `server_id` enable account discovery. Omit both for a fixed +manual URL. Do not copy them between installations; rerun browser sign-in on +the other computer so Plex lists it as a separate authorized device. ## Usage diff --git a/external/plex/account.go b/external/plex/account.go new file mode 100644 index 000000000..f02cfd3de --- /dev/null +++ b/external/plex/account.go @@ -0,0 +1,319 @@ +package plex + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "io" + "net/http" + "net/url" + "slices" + "strings" + "time" + + "github.com/bjarneo/cliamp/internal/httpclient" +) + +const ( + accountBaseURL = "https://plex.tv" + accountProduct = "cliamp" + accountPollInterval = time.Second + connectionProbeTimeout = 4 * time.Second +) + +// AccountAPI implements Plex browser sign-in and server discovery. +type AccountAPI struct { + baseURL string + client *http.Client + pollInterval time.Duration +} + +// NewAccountAPI returns an account client for plex.tv. +func NewAccountAPI() *AccountAPI { + return &AccountAPI{ + baseURL: accountBaseURL, + client: httpclient.NewAPI(30 * time.Second), + pollInterval: accountPollInterval, + } +} + +// NewClientIdentifier returns a stable identifier suitable for one cliamp +// installation. Callers must persist it and reuse it for later sign-ins. +func NewClientIdentifier() (string, error) { + var value [16]byte + if _, err := rand.Read(value[:]); err != nil { + return "", fmt.Errorf("plex: create client identifier: %w", err) + } + return hex.EncodeToString(value[:]), nil +} + +// SignInSession is one pending Plex browser sign-in. +type SignInSession struct { + api *AccountAPI + id int64 + code string + clientID string +} + +// BeginSignIn creates a strong Plex PIN for browser authorization. +func (a *AccountAPI) BeginSignIn(ctx context.Context, clientID string) (*SignInSession, error) { + if strings.TrimSpace(clientID) == "" { + return nil, fmt.Errorf("plex: sign in: missing client identifier") + } + var pin struct { + ID int64 `json:"id"` + Code string `json:"code"` + } + if err := a.doJSON(ctx, http.MethodPost, "/api/v2/pins?strong=true", clientID, "", &pin); err != nil { + return nil, fmt.Errorf("plex: start sign in: %w", err) + } + if pin.ID == 0 || pin.Code == "" { + return nil, fmt.Errorf("plex: start sign in: incomplete PIN response") + } + return &SignInSession{api: a, id: pin.ID, code: pin.Code, clientID: clientID}, nil +} + +// URL returns the Plex-hosted page where the user approves this sign-in. +func (s *SignInSession) URL() string { + params := url.Values{ + "clientID": {s.clientID}, + "code": {s.code}, + "context[device][product]": {accountProduct}, + } + return "https://app.plex.tv/auth#?" + params.Encode() +} + +// Wait polls Plex until the browser sign-in is approved or ctx ends. +func (s *SignInSession) Wait(ctx context.Context) (string, error) { + path := fmt.Sprintf("/api/v2/pins/%d?code=%s", s.id, url.QueryEscape(s.code)) + for { + var pin struct { + AuthToken string `json:"authToken"` + } + if err := s.api.doJSON(ctx, http.MethodGet, path, s.clientID, "", &pin); err != nil { + return "", fmt.Errorf("plex: wait for sign in: %w", err) + } + if pin.AuthToken != "" { + return pin.AuthToken, nil + } + timer := time.NewTimer(s.api.pollInterval) + select { + case <-ctx.Done(): + timer.Stop() + return "", fmt.Errorf("plex: wait for sign in: %w", ctx.Err()) + case <-timer.C: + } + } +} + +// AccountServer is one Plex Media Server available to the signed-in account. +type AccountServer struct { + Name string `json:"name"` + ClientIdentifier string `json:"clientIdentifier"` + Provides string `json:"provides"` + AccessToken string `json:"accessToken"` + Owned bool `json:"owned"` + Connections []AccountConnection `json:"connections"` +} + +// AccountConnection is one advertised route to a Plex Media Server. +type AccountConnection struct { + URI string `json:"uri"` + Protocol string `json:"protocol"` + Local bool `json:"local"` + Relay bool `json:"relay"` +} + +// ReachableServer pairs a server with the best connection reachable now. +type ReachableServer struct { + Name string + ClientIdentifier string + URL string + AccessToken string + Owned bool +} + +// Servers returns the Plex Media Servers available to the account. +func (a *AccountAPI) Servers(ctx context.Context, accountToken, clientID string) ([]AccountServer, error) { + var resources []AccountServer + path := "/api/v2/resources?includeHttps=1&includeRelay=1&includeIPv6=0" + if err := a.doJSON(ctx, http.MethodGet, path, clientID, accountToken, &resources); err != nil { + return nil, fmt.Errorf("plex: discover servers: %w", err) + } + servers := resources[:0] + for _, resource := range resources { + if resource.ClientIdentifier != "" && providesServer(resource.Provides) { + servers = append(servers, resource) + } + } + slices.SortFunc(servers, func(a, b AccountServer) int { + if a.Owned != b.Owned { + if a.Owned { + return -1 + } + return 1 + } + return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name)) + }) + return servers, nil +} + +func providesServer(provides string) bool { + for _, capability := range strings.Split(provides, ",") { + if strings.TrimSpace(capability) == "server" { + return true + } + } + return false +} + +// ReachableServers returns servers with at least one connection that answers. +func (a *AccountAPI) ReachableServers(ctx context.Context, accountToken, clientID string) ([]ReachableServer, error) { + servers, err := a.Servers(ctx, accountToken, clientID) + if err != nil { + return nil, err + } + var reachable []ReachableServer + for _, server := range servers { + connection, token, err := a.ReachableConnection(ctx, server, accountToken, clientID) + if err != nil { + continue + } + reachable = append(reachable, ReachableServer{ + Name: server.Name, + ClientIdentifier: server.ClientIdentifier, + URL: connection.URI, + AccessToken: token, + Owned: server.Owned, + }) + } + if len(reachable) == 0 { + if len(servers) == 0 { + return nil, fmt.Errorf("plex: no Plex Media Servers are available to this account") + } + return nil, fmt.Errorf("plex: none of the account's Plex Media Servers are reachable") + } + return reachable, nil +} + +// ConnectServer rediscovers one selected server and resolves its best current +// connection. This lets a saved account configuration follow address changes +// and move between local and remote networks. +func (a *AccountAPI) ConnectServer(ctx context.Context, accountToken, clientID, serverID string) (ReachableServer, error) { + servers, err := a.Servers(ctx, accountToken, clientID) + if err != nil { + return ReachableServer{}, err + } + for _, server := range servers { + if server.ClientIdentifier != serverID { + continue + } + connection, token, err := a.ReachableConnection(ctx, server, accountToken, clientID) + if err != nil { + return ReachableServer{}, err + } + return ReachableServer{ + Name: server.Name, + ClientIdentifier: server.ClientIdentifier, + URL: connection.URI, + AccessToken: token, + Owned: server.Owned, + }, nil + } + return ReachableServer{}, fmt.Errorf("plex: selected server is no longer available to this account") +} + +// ReachableConnection returns the best currently reachable connection for a server. +func (a *AccountAPI) ReachableConnection(ctx context.Context, server AccountServer, accountToken, clientID string) (AccountConnection, string, error) { + token := server.AccessToken + if token == "" { + token = accountToken + } + candidates := slices.Clone(server.Connections) + slices.SortStableFunc(candidates, func(a, b AccountConnection) int { + return connectionRank(a) - connectionRank(b) + }) + for _, connection := range candidates { + connection.URI = strings.TrimRight(connection.URI, "/") + if connectionRank(connection) >= 100 || !looksLikeServerURL(connection.URI) { + continue + } + probeCtx, cancel := context.WithTimeout(ctx, connectionProbeTimeout) + err := a.probe(probeCtx, connection.URI, token, clientID) + cancel() + if err == nil { + return connection, token, nil + } + } + return AccountConnection{}, "", fmt.Errorf("plex: server %q has no reachable secure connection", server.Name) +} + +func connectionRank(connection AccountConnection) int { + secure := strings.EqualFold(connection.Protocol, "https") || strings.HasPrefix(connection.URI, "https://") + switch { + case secure && connection.Local: + return 0 + case connection.Local && !connection.Relay: + return 1 // plain HTTP is acceptable only inside the LAN + case secure && !connection.Relay: + return 2 // direct remote connection + case secure && connection.Relay: + return 3 // Plex Relay may be bandwidth-limited + default: + return 100 // never send a Plex token over public plain HTTP + } +} + +func looksLikeServerURL(raw string) bool { + u, err := url.Parse(raw) + return err == nil && u.Host != "" && (u.Scheme == "http" || u.Scheme == "https") +} + +func (a *AccountAPI) probe(ctx context.Context, baseURL, token, clientID string) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/identity", nil) + if err != nil { + return err + } + setAccountHeaders(req, clientID, token) + resp, err := a.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxResponseBody)) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return fmt.Errorf("HTTP %s", resp.Status) + } + return nil +} + +func (a *AccountAPI) doJSON(ctx context.Context, method, path, clientID, token string, result any) error { + req, err := http.NewRequestWithContext(ctx, method, a.baseURL+path, nil) + if err != nil { + return err + } + setAccountHeaders(req, clientID, token) + resp, err := a.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxResponseBody)) + return fmt.Errorf("HTTP %s", resp.Status) + } + if err := httpclient.ReadJSON(resp.Body, maxResponseBody, result); err != nil { + return err + } + return nil +} + +func setAccountHeaders(req *http.Request, clientID, token string) { + req.Header.Set("Accept", "application/json") + req.Header.Set("X-Plex-Product", accountProduct) + req.Header.Set("X-Plex-Client-Identifier", clientID) + if token != "" { + req.Header.Set("X-Plex-Token", token) + } +} diff --git a/external/plex/account_test.go b/external/plex/account_test.go new file mode 100644 index 000000000..92c7b2f44 --- /dev/null +++ b/external/plex/account_test.go @@ -0,0 +1,178 @@ +package plex + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestAccountSignIn(t *testing.T) { + polls := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("X-Plex-Client-Identifier"); got != "client-1" { + t.Errorf("client identifier = %q, want client-1", got) + } + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodPost && r.URL.Path == "/api/v2/pins": + if got := r.URL.Query().Get("strong"); got != "true" { + t.Errorf("strong = %q, want true", got) + } + w.Write([]byte(`{"id":42,"code":"long-code"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v2/pins/42": + polls++ + if got := r.URL.Query().Get("code"); got != "long-code" { + t.Errorf("code = %q, want long-code", got) + } + if polls == 1 { + w.Write([]byte(`{"authToken":null}`)) + } else { + w.Write([]byte(`{"authToken":"account-token"}`)) + } + default: + t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) + } + })) + defer srv.Close() + + api := &AccountAPI{baseURL: srv.URL, client: srv.Client(), pollInterval: time.Millisecond} + session, err := api.BeginSignIn(t.Context(), "client-1") + if err != nil { + t.Fatalf("BeginSignIn: %v", err) + } + if got := session.URL(); !strings.Contains(got, "clientID=client-1") || !strings.Contains(got, "code=long-code") { + t.Fatalf("sign-in URL = %q", got) + } + token, err := session.Wait(t.Context()) + if err != nil { + t.Fatalf("Wait: %v", err) + } + if token != "account-token" { + t.Fatalf("token = %q, want account-token", token) + } +} + +func TestAccountServersFiltersAndSorts(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/v2/resources" { + t.Fatalf("path = %q", r.URL.Path) + } + if got := r.Header.Get("X-Plex-Token"); got != "account-token" { + t.Errorf("token = %q, want account-token", got) + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode([]AccountServer{ + {Name: "Shared", ClientIdentifier: "shared", Provides: "server", Owned: false}, + {Name: "Player", ClientIdentifier: "player", Provides: "player", Owned: true}, + {Name: "Home", ClientIdentifier: "home", Provides: "server,player", Owned: true}, + }) + })) + defer srv.Close() + + api := &AccountAPI{baseURL: srv.URL, client: srv.Client(), pollInterval: time.Millisecond} + servers, err := api.Servers(t.Context(), "account-token", "client-1") + if err != nil { + t.Fatalf("Servers: %v", err) + } + if len(servers) != 2 || servers[0].Name != "Home" || servers[1].Name != "Shared" { + t.Fatalf("servers = %+v", servers) + } +} + +func TestReachableConnectionPrefersLocal(t *testing.T) { + secure := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Fatal("remote connection should not be probed after local succeeds") + })) + defer secure.Close() + + local := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + })) + defer local.Close() + + api := &AccountAPI{baseURL: "unused", client: secure.Client(), pollInterval: time.Millisecond} + server := AccountServer{ + Name: "Home", + AccessToken: "server-token", + Connections: []AccountConnection{ + {URI: local.URL, Protocol: "http", Local: true}, + {URI: secure.URL, Protocol: "https"}, + }, + } + connection, token, err := api.ReachableConnection(t.Context(), server, "account-token", "client-1") + if err != nil { + t.Fatalf("ReachableConnection: %v", err) + } + if connection.URI != local.URL || token != "server-token" { + t.Fatalf("connection = %+v, token = %q", connection, token) + } +} + +func TestReachableConnectionFallsBackToRemoteHTTPS(t *testing.T) { + secure := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("X-Plex-Token"); got != "server-token" { + t.Errorf("token = %q, want server-token", got) + } + if got := r.Header.Get("X-Plex-Client-Identifier"); got != "client-1" { + t.Errorf("client identifier = %q, want client-1", got) + } + w.WriteHeader(http.StatusOK) + })) + defer secure.Close() + + local := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusServiceUnavailable) + })) + defer local.Close() + + api := &AccountAPI{baseURL: "unused", client: secure.Client(), pollInterval: time.Millisecond} + server := AccountServer{ + Name: "Home", + AccessToken: "server-token", + Connections: []AccountConnection{ + {URI: local.URL, Protocol: "http", Local: true}, + {URI: secure.URL, Protocol: "https"}, + }, + } + connection, _, err := api.ReachableConnection(t.Context(), server, "account-token", "client-1") + if err != nil { + t.Fatalf("ReachableConnection: %v", err) + } + if connection.URI != secure.URL { + t.Fatalf("connection URI = %q, want %q", connection.URI, secure.URL) + } +} + +func TestReachableConnectionRejectsPublicHTTP(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() + + api := &AccountAPI{baseURL: "unused", client: srv.Client(), pollInterval: time.Millisecond} + _, _, err := api.ReachableConnection(context.Background(), AccountServer{ + Name: "Unsafe", + Connections: []AccountConnection{{URI: srv.URL, Protocol: "http"}}, + }, "account-token", "client-1") + if err == nil || !strings.Contains(err.Error(), "no reachable secure connection") { + t.Fatalf("error = %v", err) + } +} + +func TestNewClientIdentifier(t *testing.T) { + a, err := NewClientIdentifier() + if err != nil { + t.Fatal(err) + } + b, err := NewClientIdentifier() + if err != nil { + t.Fatal(err) + } + if len(a) != 32 || a == b { + t.Fatalf("identifiers = %q, %q", a, b) + } +} diff --git a/external/plex/client.go b/external/plex/client.go index 2c331c72f..1084f1128 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -9,6 +9,7 @@ import ( "net/url" "strconv" "strings" + "sync" "time" "github.com/bjarneo/cliamp/internal/httpclient" @@ -24,16 +25,74 @@ var apiClient = httpclient.NewAPI(30 * time.Second) // Client speaks to a Plex Media Server over its HTTP API. type Client struct { + mu sync.Mutex baseURL string // e.g. "http://192.168.1.10:32400" - token string // X-Plex-Token + token string // X-Plex-Token used with the current server + clientID string // stable device identity sent with Plex requests libraries []string // if non-empty, MusicSections filters to these titles (case-insensitive) + account *accountBinding +} + +type accountBinding struct { + api *AccountAPI + token string + clientID string + serverID string + connected bool } // NewClient returns a Client for the given server URL and authentication token. // libraries is an optional list of music library names to restrict MusicSections to. // When not provided, all music libraries will be loaded func NewClient(baseURL, token string, libraries ...string) *Client { - return &Client{baseURL: baseURL, token: token, libraries: libraries} + return &Client{baseURL: baseURL, token: token, clientID: accountProduct, libraries: libraries} +} + +// NewAccountClient returns a client that rediscovers the selected Plex server +// through plex.tv before its first request. baseURL is retained for display and +// as the last known connection in config; discovery supplies the live route. +func NewAccountClient(baseURL, accountToken, clientID, serverID string, libraries ...string) *Client { + return newAccountClient(baseURL, accountToken, clientID, serverID, NewAccountAPI(), libraries...) +} + +func newAccountClient(baseURL, accountToken, clientID, serverID string, api *AccountAPI, libraries ...string) *Client { + return &Client{ + baseURL: baseURL, + token: accountToken, + clientID: clientID, + libraries: libraries, + account: &accountBinding{ + api: api, + token: accountToken, + clientID: clientID, + serverID: serverID, + }, + } +} + +func (c *Client) endpoint(ctx context.Context) (string, string, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.account != nil && !c.account.connected { + server, err := c.account.api.ConnectServer(ctx, c.account.token, c.account.clientID, c.account.serverID) + if err != nil { + return "", "", err + } + c.baseURL = server.URL + c.token = server.AccessToken + c.account.connected = true + } + return c.baseURL, c.token, nil +} + +// RefreshConnection makes an account-backed client rediscover its route on +// the next request. Manual clients keep their configured URL unchanged. +func (c *Client) RefreshConnection() { + c.mu.Lock() + if c.account != nil { + c.account.connected = false + } + c.mu.Unlock() } // Section represents a Plex library section (e.g. a music library). @@ -75,18 +134,22 @@ type Playlist struct { // get issues an authenticated GET request and decodes the JSON response into result. func (c *Client) get(path string, params url.Values, result any) error { + baseURL, token, err := c.endpoint(context.Background()) + if err != nil { + return fmt.Errorf("plex: connect account server: %w", err) + } if params == nil { params = url.Values{} } - params.Set("X-Plex-Token", c.token) + params.Set("X-Plex-Token", token) - req, err := http.NewRequest(http.MethodGet, c.baseURL+path+"?"+params.Encode(), nil) + req, err := http.NewRequest(http.MethodGet, baseURL+path+"?"+params.Encode(), nil) if err != nil { return fmt.Errorf("plex: %s: %w", path, err) } req.Header.Set("Accept", "application/json") req.Header.Set("X-Plex-Product", "cliamp") - req.Header.Set("X-Plex-Client-Identifier", "cliamp") + req.Header.Set("X-Plex-Client-Identifier", c.clientID) resp, err := apiClient.Do(req) if err != nil { @@ -151,14 +214,18 @@ func (c *Client) Scrobble(ctx context.Context, ratingKey string) error { } func (c *Client) doAction(ctx context.Context, method, endpoint string, params url.Values) error { - req, err := http.NewRequestWithContext(ctx, method, c.baseURL+endpoint+"?"+params.Encode(), nil) + baseURL, token, err := c.endpoint(ctx) + if err != nil { + return fmt.Errorf("plex: connect account server: %w", err) + } + req, err := http.NewRequestWithContext(ctx, method, baseURL+endpoint+"?"+params.Encode(), nil) if err != nil { return fmt.Errorf("plex: %s: %w", strings.TrimPrefix(endpoint, "/:/"), err) } req.Header.Set("Accept", "application/json") req.Header.Set("X-Plex-Product", "cliamp") - req.Header.Set("X-Plex-Client-Identifier", "cliamp") - req.Header.Set("X-Plex-Token", c.token) + req.Header.Set("X-Plex-Client-Identifier", c.clientID) + req.Header.Set("X-Plex-Token", token) resp, err := apiClient.Do(req) if err != nil { @@ -464,6 +531,8 @@ func (c *Client) Search(query string) ([]Track, error) { // partKey is the relative path from the Part element, e.g. "/library/parts/…/file.flac". // The token is appended as a query parameter; Plex accepts it in either header or query form. func (c *Client) StreamURL(partKey string) string { + c.mu.Lock() + defer c.mu.Unlock() return c.baseURL + partKey + "?X-Plex-Token=" + url.QueryEscape(c.token) } diff --git a/external/plex/client_test.go b/external/plex/client_test.go index fe9a6bf3c..59918e9eb 100644 --- a/external/plex/client_test.go +++ b/external/plex/client_test.go @@ -785,6 +785,59 @@ func TestRequestHeaders(t *testing.T) { _ = newTestClient(srv).Ping() } +func TestAccountClientRediscoversSelectedServer(t *testing.T) { + serverRequests := 0 + media := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + serverRequests++ + if got := r.Header.Get("X-Plex-Client-Identifier"); got != "client-1" { + t.Errorf("server client identifier = %q, want client-1", got) + } + if r.URL.Path == "/identity" { + if got := r.Header.Get("X-Plex-Token"); got != "server-token" { + t.Errorf("probe token = %q, want server-token", got) + } + w.WriteHeader(http.StatusOK) + return + } + if got := r.URL.Query().Get("X-Plex-Token"); got != "server-token" { + t.Errorf("request token = %q, want server-token", got) + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"MediaContainer":{"friendlyName":"Home"}}`)) + })) + defer media.Close() + + discoveries := 0 + account := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + discoveries++ + if got := r.Header.Get("X-Plex-Client-Identifier"); got != "client-1" { + t.Errorf("account client identifier = %q, want client-1", got) + } + if got := r.Header.Get("X-Plex-Token"); got != "account-token" { + t.Errorf("account token = %q, want account-token", got) + } + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `[{"name":"Home","clientIdentifier":"server-1","provides":"server","owned":true,"accessToken":"server-token","connections":[{"uri":%q,"protocol":"http","local":true}]}]`, media.URL) + })) + defer account.Close() + + api := &AccountAPI{baseURL: account.URL, client: account.Client(), pollInterval: time.Millisecond} + client := newAccountClient("http://stale.invalid", "account-token", "client-1", "server-1", api) + if err := client.Ping(); err != nil { + t.Fatalf("first Ping: %v", err) + } + client.RefreshConnection() + if err := client.Ping(); err != nil { + t.Fatalf("second Ping: %v", err) + } + if discoveries != 2 { + t.Fatalf("resource discoveries = %d, want 2", discoveries) + } + if serverRequests != 4 { + t.Fatalf("server requests = %d, want 4", serverRequests) + } +} + func TestClientSendsUserAgent(t *testing.T) { var got string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/external/plex/provider.go b/external/plex/provider.go index 43c7409e1..9b03e90a8 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -65,6 +65,9 @@ func NewFromConfig(cfg config.PlexConfig) *Provider { if !cfg.IsSet() { return nil } + if cfg.ClientID != "" && cfg.ServerID != "" { + return newProvider(NewAccountClient(cfg.URL, cfg.Token, cfg.ClientID, cfg.ServerID, cfg.Libraries...)) + } return newProvider(NewClient(cfg.URL, cfg.Token, cfg.Libraries...)) } @@ -142,6 +145,7 @@ func (p *Provider) Refresh() { p.trackCache = nil p.partKeys = nil p.mu.Unlock() + p.client.RefreshConnection() } // CanRefreshPlaylist reports whether id is a stable Plex album or playlist diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index ca997a553..91dcbd3a4 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -550,6 +550,18 @@ func TestNewFromConfig_OK(t *testing.T) { } } +func TestNewFromConfig_Account(t *testing.T) { + cfg := config.PlexConfig{ + URL: "https://old.plex.direct:32400", + Token: "account-token", + ClientID: "client-1", + ServerID: "server-1", + } + if p := NewFromConfig(cfg); p == nil || p.client.account == nil { + t.Fatal("NewFromConfig() did not create an account-backed client") + } +} + func TestNewFromConfig_LibrariesWired(t *testing.T) { tests := []struct { name string diff --git a/site/index.html b/site/index.html index e6021b73f..8f1586098 100644 --- a/site/index.html +++ b/site/index.html @@ -659,7 +659,7 @@

Close the tab. Play the music.

{name:"Telegram",kind:"streaming",note:"MTProto · phone login"}, {name:"Bandcamp",kind:"streaming",note:"your purchases · Subsonic API"}, {name:"Bilibili",kind:"streaming",note:"video audio · yt-dlp"}, - {name:"Plex",kind:"self-hosted",note:"token-safe · favorites · refresh · scrobbles"}, + {name:"Plex",kind:"self-hosted",note:"browser login · remote discovery · scrobbles"}, {name:"Jellyfin",kind:"self-hosted",note:"API key / password, gapless, resume"}, {name:"Emby",kind:"self-hosted",note:"API key / password, resume"}, {name:"Navidrome",kind:"self-hosted",note:"Subsonic API · lyrics"}, From 6ace0d7bcd13ec2e8f70cd1a4804c9030fd2fdb3 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 25 Oct 2026 09:11:29 +0100 Subject: [PATCH 05/32] fix(plex): speed discovery and sync likes Plex connection probes ran sequentially, making browser setup and first provider load wait through every stale address. Track ratings were also written to Plex but never read back for row hearts. Probe server routes concurrently with a short preference window, expose the post-login discovery phase, and use Plex userRating as the authoritative loaded favorite state. Verified with make check and race tests for the Plex, setup, and UI packages. --- cmd/setup.go | 39 +++++++++++--- cmd/setup_test.go | 21 ++++++++ docs/plex.md | 6 ++- external/plex/account.go | 99 +++++++++++++++++++++++++++++----- external/plex/account_test.go | 33 +++++++++++- external/plex/client.go | 19 ++++--- external/plex/client_test.go | 4 ++ external/plex/provider.go | 32 ++++++++++- external/plex/provider_test.go | 15 +++++- provider/interfaces.go | 13 +++-- site/index.html | 2 +- ui/model/favorites.go | 32 +++++++---- ui/model/favorites_test.go | 64 ++++++++++++++++++++++ ui/model/keys_radio.go | 6 +++ 14 files changed, 338 insertions(+), 47 deletions(-) diff --git a/cmd/setup.go b/cmd/setup.go index 673aa6343..69fe9f349 100644 --- a/cmd/setup.go +++ b/cmd/setup.go @@ -1026,8 +1026,9 @@ type setupModel struct { chatNames map[string]string // peer key -> title, for the form summary // validating - spinFrame int - authURL string + spinFrame int + authURL string + authStatus string // Plex account server selection plexServers []plexServerChoice @@ -1090,6 +1091,13 @@ type plexAuthDoneMsg struct { err error } +type plexAuthApprovedMsg struct { + api *plex.AccountAPI + clientID string + token string + err error +} + func spinTickCmd() tea.Cmd { return tea.Tick(120*time.Millisecond, func(time.Time) tea.Msg { return spinTickMsg{} }) } @@ -1189,9 +1197,14 @@ func waitPlexAuthCmd(api *plex.AccountAPI, session *plex.SignInSession, clientID ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() token, err := session.Wait(ctx) - if err != nil { - return plexAuthDoneMsg{err: err} - } + return plexAuthApprovedMsg{api: api, clientID: clientID, token: token, err: err} + } +} + +func discoverPlexServersCmd(api *plex.AccountAPI, token, clientID string) tea.Cmd { + return func() tea.Msg { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() servers, err := api.ReachableServers(ctx, token, clientID) return plexAuthDoneMsg{clientID: clientID, token: token, servers: servers, err: err} } @@ -1253,8 +1266,17 @@ func (m *setupModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m.onPlexAuthError(msg.err) } m.authURL = msg.session.URL() + m.authStatus = "Waiting for Plex browser sign-in…" return m, tea.Batch(openBrowserCmd(m.authURL), waitPlexAuthCmd(msg.api, msg.session, msg.clientID)) + case plexAuthApprovedMsg: + if msg.err != nil { + return m.onPlexAuthError(msg.err) + } + m.authURL = "" + m.authStatus = "Finding reachable Plex servers…" + return m, discoverPlexServersCmd(msg.api, msg.token, msg.clientID) + case plexAuthDoneMsg: if msg.err != nil { return m.onPlexAuthError(msg.err) @@ -1380,6 +1402,7 @@ func (m *setupModel) startProvider(idx int) { m.chatTouched, m.chatNote = false, "" m.chatNames = nil m.authURL = "" + m.authStatus = "" m.plexServers = nil m.plexServerCursor = 0 @@ -1781,6 +1804,7 @@ func (m *setupModel) submitForm() (tea.Model, tea.Cmd) { m.stage = stageValidating m.spinFrame = 0 m.authURL = "" + m.authStatus = "Starting Plex sign-in…" return m, tea.Batch(spinTickCmd(), beginPlexAuthCmd(clientID)) } @@ -2192,7 +2216,10 @@ func (m *setupModel) viewValidating() string { frame := frames[m.spinFrame%len(frames)] message := "Verifying connection to " + m.provs[m.pidx].name + "…" if m.provs[m.pidx].section == "plex" && m.values[keyPlexAuth] == "account" { - message = "Waiting for Plex browser sign-in…" + message = m.authStatus + if message == "" { + message = "Starting Plex sign-in…" + } if m.authURL != "" { message += "\n\nIf the browser did not open, visit:\n" + m.authURL } diff --git a/cmd/setup_test.go b/cmd/setup_test.go index e82d15eb7..0b7369de6 100644 --- a/cmd/setup_test.go +++ b/cmd/setup_test.go @@ -189,6 +189,27 @@ func TestPlexAuthErrorCannotSaveIncompleteConfig(t *testing.T) { } } +func TestPlexAuthApprovalShowsServerDiscovery(t *testing.T) { + m := newSetupModel() + for i, p := range m.provs { + if p.section == "plex" { + m.pidx = i + break + } + } + m.values = map[string]string{keyPlexAuth: "account"} + m.stage = stageValidating + m.authURL = "https://app.plex.tv/auth" + + _, cmd := m.Update(plexAuthApprovedMsg{api: plex.NewAccountAPI(), clientID: "client-1", token: "token"}) + if cmd == nil || m.authURL != "" || m.authStatus != "Finding reachable Plex servers…" { + t.Fatalf("cmd = %v, authURL = %q, status = %q", cmd != nil, m.authURL, m.authStatus) + } + if view := m.viewValidating(); !strings.Contains(view, "Finding reachable Plex servers") { + t.Fatalf("view = %q", view) + } +} + func TestPlexSetupReusesClientIdentifier(t *testing.T) { dir := t.TempDir() t.Setenv("CLIAMP_CONFIG_DIR", dir) diff --git a/docs/plex.md b/docs/plex.md index b5a54fcf5..f8ed35418 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -91,8 +91,10 @@ Press `Ctrl+R` while an open Plex album or playlist is focused to reload it and pick up server-side changes. Album contents are cached for up to five minutes; Plex playlists are always loaded fresh so smart playlists stay current. -Press `f` on a Plex track to add or remove it from cliamp Favorites. The same -change is copied to Plex and appears in Plexamp and other Plex clients. +Plex likes are shown as hearts in cliamp. Press `f` on a Plex track to add or +remove it from cliamp Favorites and Plex together; the change appears in +Plexamp and other Plex clients. Press `Ctrl+R` to pick up likes changed in +another client while the list is open. While a Plex track plays, cliamp reports its timeline position about every 15 seconds. After at least half of a known-duration track has played, leaving the track records one Plex play and updates Plex history. Short skips do not increment the play count. diff --git a/external/plex/account.go b/external/plex/account.go index f02cfd3de..02ef0afde 100644 --- a/external/plex/account.go +++ b/external/plex/account.go @@ -20,6 +20,7 @@ const ( accountProduct = "cliamp" accountPollInterval = time.Second connectionProbeTimeout = 4 * time.Second + connectionSelectGrace = 100 * time.Millisecond ) // AccountAPI implements Plex browser sign-in and server discovery. @@ -174,19 +175,39 @@ func (a *AccountAPI) ReachableServers(ctx context.Context, accountToken, clientI if err != nil { return nil, err } - var reachable []ReachableServer - for _, server := range servers { - connection, token, err := a.ReachableConnection(ctx, server, accountToken, clientID) - if err != nil { + type probeResult struct { + index int + connection AccountConnection + token string + err error + } + results := make(chan probeResult, len(servers)) + for i, server := range servers { + go func() { + connection, token, err := a.ReachableConnection(ctx, server, accountToken, clientID) + results <- probeResult{index: i, connection: connection, token: token, err: err} + }() + } + reachableByIndex := make([]*ReachableServer, len(servers)) + for range servers { + result := <-results + if result.err != nil { continue } - reachable = append(reachable, ReachableServer{ + server := servers[result.index] + reachableByIndex[result.index] = &ReachableServer{ Name: server.Name, ClientIdentifier: server.ClientIdentifier, - URL: connection.URI, - AccessToken: token, + URL: result.connection.URI, + AccessToken: result.token, Owned: server.Owned, - }) + } + } + reachable := make([]ReachableServer, 0, len(servers)) + for _, server := range reachableByIndex { + if server != nil { + reachable = append(reachable, *server) + } } if len(reachable) == 0 { if len(servers) == 0 { @@ -234,18 +255,70 @@ func (a *AccountAPI) ReachableConnection(ctx context.Context, server AccountServ slices.SortStableFunc(candidates, func(a, b AccountConnection) int { return connectionRank(a) - connectionRank(b) }) + valid := candidates[:0] for _, connection := range candidates { connection.URI = strings.TrimRight(connection.URI, "/") if connectionRank(connection) >= 100 || !looksLikeServerURL(connection.URI) { continue } - probeCtx, cancel := context.WithTimeout(ctx, connectionProbeTimeout) - err := a.probe(probeCtx, connection.URI, token, clientID) - cancel() - if err == nil { - return connection, token, nil + valid = append(valid, connection) + } + if len(valid) == 0 { + return AccountConnection{}, "", fmt.Errorf("plex: server %q has no reachable secure connection", server.Name) + } + + type probeResult struct { + connection AccountConnection + rank int + err error + } + probeCtx, cancel := context.WithCancel(ctx) + defer cancel() + results := make(chan probeResult, len(valid)) + for _, connection := range valid { + go func() { + requestCtx, requestCancel := context.WithTimeout(probeCtx, connectionProbeTimeout) + defer requestCancel() + results <- probeResult{ + connection: connection, + rank: connectionRank(connection), + err: a.probe(requestCtx, connection.URI, token, clientID), + } + }() + } + + var ( + best AccountConnection + bestRank = 101 + grace *time.Timer + graceTimer <-chan time.Time + ) + for range valid { + select { + case <-ctx.Done(): + return AccountConnection{}, "", fmt.Errorf("plex: probe server %q: %w", server.Name, ctx.Err()) + case <-graceTimer: + return best, token, nil + case result := <-results: + if result.err != nil { + continue + } + if result.rank < bestRank { + best, bestRank = result.connection, result.rank + } + if bestRank == 0 { + return best, token, nil + } + if grace == nil { + grace = time.NewTimer(connectionSelectGrace) + defer grace.Stop() + graceTimer = grace.C + } } } + if bestRank < 101 { + return best, token, nil + } return AccountConnection{}, "", fmt.Errorf("plex: server %q has no reachable secure connection", server.Name) } diff --git a/external/plex/account_test.go b/external/plex/account_test.go index 92c7b2f44..47c5360b5 100644 --- a/external/plex/account_test.go +++ b/external/plex/account_test.go @@ -85,7 +85,7 @@ func TestAccountServersFiltersAndSorts(t *testing.T) { func TestReachableConnectionPrefersLocal(t *testing.T) { secure := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - t.Fatal("remote connection should not be probed after local succeeds") + w.WriteHeader(http.StatusOK) })) defer secure.Close() @@ -112,6 +112,37 @@ func TestReachableConnectionPrefersLocal(t *testing.T) { } } +func TestReachableConnectionDoesNotWaitForSlowLocalAddress(t *testing.T) { + local := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + <-r.Context().Done() + })) + defer local.Close() + + remote := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + })) + defer remote.Close() + + api := &AccountAPI{baseURL: "unused", client: remote.Client(), pollInterval: time.Millisecond} + started := time.Now() + connection, _, err := api.ReachableConnection(t.Context(), AccountServer{ + Name: "Home", + Connections: []AccountConnection{ + {URI: local.URL, Protocol: "http", Local: true}, + {URI: remote.URL, Protocol: "https"}, + }, + }, "account-token", "client-1") + if err != nil { + t.Fatalf("ReachableConnection: %v", err) + } + if connection.URI != remote.URL { + t.Fatalf("connection URI = %q, want %q", connection.URI, remote.URL) + } + if elapsed := time.Since(started); elapsed >= time.Second { + t.Fatalf("probe took %s; slow local address blocked remote fallback", elapsed) + } +} + func TestReachableConnectionFallsBackToRemoteHTTPS(t *testing.T) { secure := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if got := r.Header.Get("X-Plex-Token"); got != "server-token" { diff --git a/external/plex/client.go b/external/plex/client.go index 1084f1128..4c8a09b70 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -121,6 +121,7 @@ type Track struct { TrackNumber int // index field in Plex API Duration int // milliseconds PartKey string // relative path, e.g. "/library/parts/67890/1234567890/file.flac" + UserRating float64 } // Playlist represents a Plex playlist (smart or user-created) of audio tracks. @@ -549,14 +550,15 @@ func IsStreamURL(urlStr string) bool { // trackJSON is the shared JSON structure for track responses (children and search). type trackJSON struct { - RatingKey string `json:"ratingKey"` - Title string `json:"title"` - GrandparentTitle string `json:"grandparentTitle"` // artist - ParentTitle string `json:"parentTitle"` // album - Year int `json:"year"` - ParentYear int `json:"parentYear"` // album year; tracks rarely carry their own - Index int `json:"index"` // track number within album - Duration int `json:"duration"` // milliseconds + RatingKey string `json:"ratingKey"` + Title string `json:"title"` + GrandparentTitle string `json:"grandparentTitle"` // artist + ParentTitle string `json:"parentTitle"` // album + Year int `json:"year"` + ParentYear int `json:"parentYear"` // album year; tracks rarely carry their own + Index int `json:"index"` // track number within album + Duration int `json:"duration"` // milliseconds + UserRating float64 `json:"userRating"` Media []struct { Part []struct { Key string `json:"key"` @@ -582,5 +584,6 @@ func trackFromJSON(m trackJSON) Track { TrackNumber: m.Index, Duration: m.Duration, PartKey: partKey, + UserRating: m.UserRating, } } diff --git a/external/plex/client_test.go b/external/plex/client_test.go index 59918e9eb..605fcd6fd 100644 --- a/external/plex/client_test.go +++ b/external/plex/client_test.go @@ -614,6 +614,7 @@ func TestTracks_MapsAllFields(t *testing.T) { "year": 1959, "index": 1, "duration": 565000, + "userRating": 10, "Media": [{"Part": [{"key": "/library/parts/100/111/So_What.flac"}]}] }, { @@ -661,6 +662,9 @@ func TestTracks_MapsAllFields(t *testing.T) { if tr.Duration != 565000 { t.Errorf("Duration: got %d, want 565000", tr.Duration) } + if tr.UserRating != 10 { + t.Errorf("UserRating: got %g, want 10", tr.UserRating) + } if tr.PartKey != "/library/parts/100/111/So_What.flac" { t.Errorf("PartKey: got %q, want /library/parts/100/111/So_What.flac", tr.PartKey) } diff --git a/external/plex/provider.go b/external/plex/provider.go index 9b03e90a8..77cadc9ac 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -38,6 +38,7 @@ var ( _ provider.Searcher = (*Provider)(nil) _ provider.AlbumTrackLoader = (*Provider)(nil) _ provider.TrackFavoriter = (*Provider)(nil) + _ provider.TrackFavoriteState = (*Provider)(nil) _ provider.ProgressReporter = (*Provider)(nil) ) @@ -52,6 +53,7 @@ type Provider struct { playlistCache []playlist.PlaylistInfo trackCache map[string]trackCacheEntry partKeys map[string]string + favorites map[string]bool now func() time.Time } @@ -144,6 +146,7 @@ func (p *Provider) Refresh() { p.playlistCache = nil p.trackCache = nil p.partKeys = nil + p.favorites = nil p.mu.Unlock() p.client.RefreshConnection() } @@ -226,6 +229,10 @@ func (p *Provider) convertTracks(plexTracks []Track, limit int) []playlist.Track p.partKeys = make(map[string]string) } p.partKeys[t.RatingKey] = t.PartKey + if p.favorites == nil { + p.favorites = make(map[string]bool) + } + p.favorites[t.RatingKey] = t.UserRating >= 10 p.mu.Unlock() tracks = append(tracks, playlist.Track{ Path: TrackURIPrefix + t.RatingKey, @@ -301,7 +308,19 @@ func (p *Provider) CanFavoriteTrack(track playlist.Track) bool { return plexTrackID(track) != "" } -// SetTrackFavorite copies cliamp's local favorite state to Plex. +// FavoriteState reports the rating returned with the latest Plex metadata. +func (p *Provider) FavoriteState(track playlist.Track) (favorite, known bool) { + id := plexTrackID(track) + p.mu.Lock() + defer p.mu.Unlock() + if id == "" { + return false, false + } + favorite, known = p.favorites[id] + return favorite, known +} + +// SetTrackFavorite updates the current user's favorite state in Plex. func (p *Provider) SetTrackFavorite(ctx context.Context, track playlist.Track, favorite bool) error { id := plexTrackID(track) if id == "" { @@ -311,7 +330,16 @@ func (p *Provider) SetTrackFavorite(ctx context.Context, track playlist.Track, f if favorite { rating = 10 } - return p.client.SetRating(ctx, id, rating) + if err := p.client.SetRating(ctx, id, rating); err != nil { + return err + } + p.mu.Lock() + if p.favorites == nil { + p.favorites = make(map[string]bool) + } + p.favorites[id] = favorite + p.mu.Unlock() + return nil } func plexTrackID(track playlist.Track) string { diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index 91dcbd3a4..2082d209b 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -27,7 +27,7 @@ func sectionsHandler(t *testing.T) http.HandlerFunc { "Metadata": [ { "ratingKey":"300","title":"Highway to Hell","grandparentTitle":"AC/DC", - "parentTitle":"Highway to Hell","parentYear":1979,"index":1,"duration":208000, + "parentTitle":"Highway to Hell","parentYear":1979,"index":1,"duration":208000,"userRating":10, "Media":[{"Part":[{"key":"/library/parts/3/333/HighwayToHell.flac"}]}] } ] @@ -269,6 +269,9 @@ func TestProvider_Tracks_Playlist(t *testing.T) { if tr.Path != TrackURIPrefix+"300" { t.Errorf("Path = %q, want token-free Plex URI", tr.Path) } + if favorite, known := p.FavoriteState(tr); !favorite || !known { + t.Error("Plex userRating=10 was not exposed as a favorite") + } } func TestProviderResolveSourceRestoresAfterRestart(t *testing.T) { @@ -314,6 +317,16 @@ func TestProviderFavorites(t *testing.T) { if gotRating != "10" { t.Fatalf("rating = %q, want 10", gotRating) } + if favorite, known := p.FavoriteState(track); !favorite || !known { + t.Fatal("successful rating did not update the in-memory favorite state") + } + if err := p.SetTrackFavorite(context.Background(), track, false); err != nil { + t.Fatalf("SetTrackFavorite(false): %v", err) + } + favorite, known := p.FavoriteState(track) + if gotRating != "0" || favorite || !known { + t.Fatalf("cleared rating = %q, state = (%v, %v); want 0, false, true", gotRating, favorite, known) + } } func TestProviderPlaybackReporting(t *testing.T) { diff --git a/provider/interfaces.go b/provider/interfaces.go index 38b9e85ab..932bae57a 100644 --- a/provider/interfaces.go +++ b/provider/interfaces.go @@ -331,9 +331,8 @@ type ArtworkProvider interface { } // TrackFavoriter is implemented by providers that keep a favorite state for -// tracks on their own service, such as liked or starred songs. The local -// favorites store stays the source of truth. The UI copies each change to the -// provider that owns the track. +// tracks on their own service, such as liked or starred songs. The UI copies +// each change to the provider that owns the track. type TrackFavoriter interface { // CanFavoriteTrack reports whether track belongs to this provider. It must // not do I/O because the UI calls it on the Update goroutine. @@ -354,6 +353,14 @@ type TrackRater interface { SetTrackRating(ctx context.Context, track playlist.Track, rating int) error } +// TrackFavoriteState is implemented by providers that return favorite state +// with their track metadata. Its methods must not do I/O because list rows and +// IPC snapshots call them on the Update goroutine. +type TrackFavoriteState interface { + CanFavoriteTrack(track playlist.Track) bool + FavoriteState(track playlist.Track) (favorite, known bool) +} + // FavoriteToggler is implemented by providers that support marking items // as favorites (e.g. radio station favorites). type FavoriteToggler interface { diff --git a/site/index.html b/site/index.html index 8f1586098..15556d187 100644 --- a/site/index.html +++ b/site/index.html @@ -659,7 +659,7 @@

Close the tab. Play the music.

{name:"Telegram",kind:"streaming",note:"MTProto · phone login"}, {name:"Bandcamp",kind:"streaming",note:"your purchases · Subsonic API"}, {name:"Bilibili",kind:"streaming",note:"video audio · yt-dlp"}, - {name:"Plex",kind:"self-hosted",note:"browser login · remote discovery · scrobbles"}, + {name:"Plex",kind:"self-hosted",note:"browser login · synced likes · remote discovery"}, {name:"Jellyfin",kind:"self-hosted",note:"API key / password, gapless, resume"}, {name:"Emby",kind:"self-hosted",note:"API key / password, resume"}, {name:"Navidrome",kind:"self-hosted",note:"Subsonic API · lyrics"}, diff --git a/ui/model/favorites.go b/ui/model/favorites.go index 0ca0eac6a..f7cb43518 100644 --- a/ui/model/favorites.go +++ b/ui/model/favorites.go @@ -39,26 +39,30 @@ func (m *Model) favoriteTrackKey(track playlist.Track) tea.Cmd { return cmd } -// toggleTrackFavorite toggles the ♥ favorite for track in the local store, -// which stays the source of truth. The returned command copies the change to -// the provider that owns the track and refreshes the provider pane counts. +// toggleTrackFavorite toggles the displayed ♥ state. The local store and a +// provider-owned state are updated together when they apply to the track. func (m *Model) toggleTrackFavorite(track playlist.Track) (tea.Cmd, error) { if m.favStore == nil { return nil, errFavoritesUnavailable } - favorite, err := m.favStore.Toggle(track) - if err != nil { - return nil, err + favorite := !m.playlistTrackFavorited(track) + _, localFavorite := m.favSet[track.Path] + var refresh tea.Cmd + if localFavorite != favorite { + if _, err := m.favStore.Toggle(track); err != nil { + return nil, err + } + m.refreshFavSet() + // The Local pane renders Favorites counts from Playlists(). The + // manager list refreshes itself on open. + refresh = m.refreshPaneAfterLocalWrite() } - m.refreshFavSet() if favorite { m.status.Showf(statusTTLMedium, "Favorited: %s", track.DisplayName()) } else { m.status.Showf(statusTTLMedium, "Unfavorited: %s", track.DisplayName()) } - // The Local pane renders Favorites counts from Playlists(). The - // manager list refreshes itself on open. - return tea.Batch(m.syncTrackFavoriteCmd(track, favorite), m.refreshPaneAfterLocalWrite()), nil + return tea.Batch(m.syncTrackFavoriteCmd(track, favorite), refresh), nil } // findTrackFavoriter returns the first registered provider that owns track @@ -67,6 +71,14 @@ func (m *Model) findTrackFavoriter(track playlist.Track) (provider.TrackFavorite return findCapable(m, func(f provider.TrackFavoriter) bool { return f.CanFavoriteTrack(track) }) } +func (m *Model) providerTrackFavoriteState(track playlist.Track) (favorite, known bool) { + state, _ := findCapable(m, func(s provider.TrackFavoriteState) bool { return s.CanFavoriteTrack(track) }) + if state == nil { + return false, false + } + return state.FavoriteState(track) +} + // syncTrackFavoriteCmd copies a favorite change to the provider that owns // track. It returns nil when no provider keeps its own favorite state. The // network call runs in the command, never in Update. The sync queue keeps diff --git a/ui/model/favorites_test.go b/ui/model/favorites_test.go index fd45a5fb4..21d08836d 100644 --- a/ui/model/favorites_test.go +++ b/ui/model/favorites_test.go @@ -25,6 +25,7 @@ type fakeTrackFavoriter struct { mu sync.Mutex calls []string + liked map[string]bool } func (p *fakeTrackFavoriter) CanFavoriteTrack(track playlist.Track) bool { @@ -39,9 +40,22 @@ func (p *fakeTrackFavoriter) SetTrackFavorite(_ context.Context, track playlist. state = "add" } p.calls = append(p.calls, state+" "+track.Path) + if p.err == nil { + if p.liked == nil { + p.liked = make(map[string]bool) + } + p.liked[track.Path] = favorite + } return p.err } +func (p *fakeTrackFavoriter) FavoriteState(track playlist.Track) (favorite, known bool) { + p.mu.Lock() + defer p.mu.Unlock() + favorite, known = p.liked[track.Path] + return favorite, known +} + func (p *fakeTrackFavoriter) recorded() []string { p.mu.Lock() defer p.mu.Unlock() @@ -304,6 +318,56 @@ func TestTrackFavoriteSyncRouting(t *testing.T) { } } +func TestProviderFavoriteStateIsDisplayedAndToggled(t *testing.T) { + m, store := favoriteKeyTestModel(t) + track := playlist.Track{Path: "fake:track:liked", Title: "Liked"} + fake := &fakeTrackFavoriter{ + commandsTestProvider: commandsTestProvider{name: "Fake"}, + prefix: "fake:", + liked: map[string]bool{track.Path: true}, + } + m.provider = fake + m.providers = append(m.providers, provider.Entry{Key: "fake", Name: "Fake", Provider: fake}) + + if !m.playlistTrackFavorited(track) { + t.Fatal("provider favorite is not displayed") + } + cmd, err := m.toggleTrackFavorite(track) + if err != nil { + t.Fatal(err) + } + if store.IsFavorited(track.Path) { + t.Fatal("removing a provider-only favorite added it to the local store") + } + runCmd(cmd) + if m.playlistTrackFavorited(track) { + t.Fatal("provider favorite stayed displayed after removal") + } + if got := fake.recorded(); len(got) != 1 || got[0] != "remove "+track.Path { + t.Fatalf("provider calls = %v, want one removal", got) + } +} + +func TestProviderFavoriteStateOverridesStaleLocalState(t *testing.T) { + m, store := favoriteKeyTestModel(t) + track := playlist.Track{Path: "fake:track:unliked", Title: "Unliked"} + if _, err := store.Toggle(track); err != nil { + t.Fatal(err) + } + m.refreshFavSet() + fake := &fakeTrackFavoriter{ + commandsTestProvider: commandsTestProvider{name: "Fake"}, + prefix: "fake:", + liked: map[string]bool{track.Path: false}, + } + m.provider = fake + m.providers = append(m.providers, provider.Entry{Key: "fake", Name: "Fake", Provider: fake}) + + if m.playlistTrackFavorited(track) { + t.Fatal("stale local favorite overrode the state returned by the provider") + } +} + // A second toggle made before the first provider call runs wins, so the // provider ends with the local state. func TestTrackFavoriteSyncKeepsLastState(t *testing.T) { diff --git a/ui/model/keys_radio.go b/ui/model/keys_radio.go index c2d05d951..c1a84c01d 100644 --- a/ui/model/keys_radio.go +++ b/ui/model/keys_radio.go @@ -191,6 +191,9 @@ func (m *Model) togglePlaylistTrackFavorite(track playlist.Track, savedPlaylist // shows the state that f toggles. The render path calls it, so it must not do // I/O. func (m Model) playlistTrackFavorited(track playlist.Track) bool { + if favorite, known := m.providerTrackFavoriteState(track); known { + return favorite + } return trackFavorited(track, m.favSet, m.radioFavorites, m.loadedPlaylist != "") } @@ -202,6 +205,9 @@ func (m Model) trackFavoriteLookup(playback bool) func(playlist.Track) bool { favSet, stations := m.favSet, m.radioFavorites saved := playback && m.loadedPlaylist != "" return func(track playlist.Track) bool { + if favorite, known := m.providerTrackFavoriteState(track); known { + return favorite + } return trackFavorited(track, favSet, stations, saved) } } From 1ee4bfd57fae47cf441552fdf9367da8f142bf26 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 25 Oct 2026 19:05:16 +0100 Subject: [PATCH 06/32] fix(plex): use server likes only Plex track hearts previously mixed the server rating with cliamp's local favorites store, so stale local entries could drive the displayed and toggled state. Treat Plex favorite metadata as authoritative, keep provider-only changes out of favorites.toml, preserve old local entries without using them, and track optimistic updates safely across rapid toggles. Refresh restored-track rating state and document the provider-specific behavior. Verified with targeted favorite tests, docs/site checks, gofmt, go vet, and a local build. Full make check could not run because the sandbox blocks httptest listener sockets; staticcheck is not installed. --- docs/keybindings.md | 2 +- docs/playlists.md | 7 +- docs/plex.md | 11 ++- docs/provider-development.md | 1 + docs/remote-control.md | 5 +- external/plex/provider.go | 6 ++ external/plex/provider_test.go | 6 +- provider/interfaces.go | 5 +- site/index.html | 2 +- ui/model/favorites.go | 58 +++++++++++--- ui/model/favorites_test.go | 142 +++++++++++++++++++++++++++++++-- ui/model/keys_radio.go | 4 +- ui/model/model.go | 4 + 13 files changed, 222 insertions(+), 31 deletions(-) diff --git a/docs/keybindings.md b/docs/keybindings.md index 1dc5032bc..96f7ac791 100644 --- a/docs/keybindings.md +++ b/docs/keybindings.md @@ -123,7 +123,7 @@ and `Esc` clears it. | Key | Action | |---|---| -| `f` | Toggle the favorite ♥ on the selected track. Favorites appear in the "Favorites" virtual playlist, and cliamp also saves them on Spotify and Navidrome. For directory radio stations outside saved local playlists, toggle Radio Favorites from the browser or playback playlist, including country and genre results. In the country browser, pin the selected country or region. On a podcast show, subscribe or unsubscribe. | +| `f` | Toggle the favorite ♥ on the selected track. Favorites appear in the "Favorites" virtual playlist, and cliamp also saves them on Spotify and Navidrome. Plex tracks use only the server-side like and ignore local favorites. For directory radio stations outside saved local playlists, toggle Radio Favorites from the browser or playback playlist, including country and genre results. In the country browser, pin the selected country or region. On a podcast show, subscribe or unsubscribe. | | `*` then `0`-`5` | Set the selected Navidrome track's rating. `0` clears it. The playing track shows `★N`, and Linux MPRIS reports the normalized rating. | | `Ctrl+F` | Search with the active provider (Podcasts, Spotify, Qobuz, Tidal, Bandcamp, Navidrome, Lyrion, Jellyfin, Emby, Plex, Audiobookshelf, Mixcloud, NetEase, SoundCloud, Yandex Music, Local), or search YouTube. Available in playlist and provider-browser views. The search line names the source. See [Search and filter modes](#search-and-filter-modes). | | `u` | Load URL (stream/playlist) | diff --git a/docs/playlists.md b/docs/playlists.md index f20d247df..617a20865 100644 --- a/docs/playlists.md +++ b/docs/playlists.md @@ -491,6 +491,11 @@ song. The local file stays the source of truth. If the service call fails, the local favorite stays and the status bar shows a warning with the provider name. See [spotify.md](spotify.md) and [navidrome.md](navidrome.md). +Plex tracks are different: the heart and `f` use only the like stored on the +Plex server. A local `favorites.toml` entry for a Plex track does not control +that heart and is not changed. Existing entries remain in the file so +upgrading does not discard data. See [plex.md](plex.md). + On a radio station, `f` toggles the station favorite. On a podcast show, `f` subscribes or unsubscribes. In the country browser, `f` pins a country. @@ -509,7 +514,7 @@ contain `bookmark = true` still load. `cliamp playlist bookmark` and `cliamp playlist bookmarks` still work. They are aliases of `cliamp playlist favorite` and `cliamp playlist favorites`. These CLI commands change only the local favorites. They do not call Spotify -or Navidrome: +or Navidrome, and they do not change server-side Plex likes: ```sh cliamp playlist favorite "gym" --index 3 diff --git a/docs/plex.md b/docs/plex.md index f8ed35418..5a48be16a 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -91,10 +91,13 @@ Press `Ctrl+R` while an open Plex album or playlist is focused to reload it and pick up server-side changes. Album contents are cached for up to five minutes; Plex playlists are always loaded fresh so smart playlists stay current. -Plex likes are shown as hearts in cliamp. Press `f` on a Plex track to add or -remove it from cliamp Favorites and Plex together; the change appears in -Plexamp and other Plex clients. Press `Ctrl+R` to pick up likes changed in -another client while the list is open. +Plex likes are shown as hearts in cliamp. Press `f` on a Plex track to change +its rating on the Plex server; the change appears in Plexamp and other Plex +clients. Plex is the source of truth for these hearts. cliamp neither reads nor +writes its local `favorites.toml` entry when it draws or toggles a Plex heart. +Existing local Plex favorites are left intact but do not control that heart, so +the change does not discard old data. Press `Ctrl+R` to pick up likes changed +in another client while the list is open. While a Plex track plays, cliamp reports its timeline position about every 15 seconds. After at least half of a known-duration track has played, leaving the track records one Plex play and updates Plex history. Short skips do not increment the play count. diff --git a/docs/provider-development.md b/docs/provider-development.md index f6c765d63..700f78381 100644 --- a/docs/provider-development.md +++ b/docs/provider-development.md @@ -204,6 +204,7 @@ are in `provider/interfaces.go`. | `FavoriteToggler` | Favorite toggling for provider list items, such as stations and shows | `ToggleFavorite(id)` | | `TrackFavoriter` | Copy the ♥ favorite of a track to the service, such as liked or starred songs. The UI calls it in a `tea.Cmd` and keeps the local favorite when it fails | `CanFavoriteTrack(track)`, `SetTrackFavorite(ctx, track, favorite) error` | | `TrackRater` | Set or clear a provider-owned numeric track rating | `CanRateTrack(track)`, `SetTrackRating(ctx, track, rating) error` | +| `TrackFavoriteState` | Make provider metadata authoritative for a track's ♥ state. Local favorites are ignored for tracks claimed by this interface | `CanFavoriteTrack(track)`, `FavoriteState(track)` | | `CatalogLoader` | Lazy paging of a large catalog | `LoadCatalogPage(offset, limit)` | | `CatalogSearcher` | Server-side catalog search that fills the pane | `SearchCatalog(query)`, `ClearSearch()`, `IsSearching()` | | `LocationConsenter` | Ask before the provider uses the location of the listener | `NeedsLocationConsent()`, `LocationConsentID()`, `LocationPrompt()`, `SetLocationConsent(allowed)` | diff --git a/docs/remote-control.md b/docs/remote-control.md index d701d7302..8b42b88d3 100644 --- a/docs/remote-control.md +++ b/docs/remote-control.md @@ -184,8 +184,9 @@ other name fails the job with `invalid_params` and changes nothing. does not change the playlist. A radio station toggles its station favorite, and its `bookmark` field in provider lists changes too. A station that is a row of a loaded saved playlist toggles the favorites store instead. -The `bookmark` field of that row in `queue.list` changes. cliamp matches the -row by path. +The `bookmark` field of that row in `queue.list` changes. Plex tracks always +toggle the server-side like and ignore the local favorites store. cliamp +matches the row by path. Use IDs returned by `provider.playlists` for subsequent provider operations. Radio favorite IDs are stable `f:` values, not positional diff --git a/external/plex/provider.go b/external/plex/provider.go index 77cadc9ac..5d6d5ac40 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -277,6 +277,10 @@ func (p *Provider) ResolveSource(uri string) (string, error) { p.partKeys = make(map[string]string) } p.partKeys[id] = partKey + if p.favorites == nil { + p.favorites = make(map[string]bool) + } + p.favorites[id] = track.UserRating >= 10 p.mu.Unlock() } return p.client.StreamURL(partKey), nil @@ -309,6 +313,8 @@ func (p *Provider) CanFavoriteTrack(track playlist.Track) bool { } // FavoriteState reports the rating returned with the latest Plex metadata. +// Plex is authoritative even when known is false; the UI must not fall back +// to cliamp's local favorites for this track. func (p *Provider) FavoriteState(track playlist.Track) (favorite, known bool) { id := plexTrackID(track) p.mu.Lock() diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index 2082d209b..ce95093a1 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -280,7 +280,7 @@ func TestProviderResolveSourceRestoresAfterRestart(t *testing.T) { t.Fatalf("path = %q, want metadata lookup", r.URL.Path) } w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"MediaContainer":{"Metadata":[{"ratingKey":"200","Media":[{"Part":[{"key":"/library/parts/1/111/file.flac"}]}]}]}}`)) + w.Write([]byte(`{"MediaContainer":{"Metadata":[{"ratingKey":"200","userRating":10,"Media":[{"Part":[{"key":"/library/parts/1/111/file.flac"}]}]}]}}`)) })) defer srv.Close() @@ -293,6 +293,10 @@ func TestProviderResolveSourceRestoresAfterRestart(t *testing.T) { if got != want { t.Fatalf("ResolveSource = %q, want %q", got, want) } + track := playlist.Track{Path: TrackURIPrefix + "200"} + if favorite, known := p.FavoriteState(track); !favorite || !known { + t.Fatalf("restored favorite = (%v, %v), want true, true", favorite, known) + } } func TestProviderFavorites(t *testing.T) { diff --git a/provider/interfaces.go b/provider/interfaces.go index 932bae57a..d3564ac3e 100644 --- a/provider/interfaces.go +++ b/provider/interfaces.go @@ -353,8 +353,9 @@ type TrackRater interface { SetTrackRating(ctx context.Context, track playlist.Track, rating int) error } -// TrackFavoriteState is implemented by providers that return favorite state -// with their track metadata. Its methods must not do I/O because list rows and +// TrackFavoriteState is implemented by providers whose own favorite state is +// authoritative for their tracks. Local favorites are ignored for a track +// claimed by this interface. Its methods must not do I/O because list rows and // IPC snapshots call them on the Update goroutine. type TrackFavoriteState interface { CanFavoriteTrack(track playlist.Track) bool diff --git a/site/index.html b/site/index.html index 15556d187..1ac2da644 100644 --- a/site/index.html +++ b/site/index.html @@ -659,7 +659,7 @@

Close the tab. Play the music.

{name:"Telegram",kind:"streaming",note:"MTProto · phone login"}, {name:"Bandcamp",kind:"streaming",note:"your purchases · Subsonic API"}, {name:"Bilibili",kind:"streaming",note:"video audio · yt-dlp"}, - {name:"Plex",kind:"self-hosted",note:"browser login · synced likes · remote discovery"}, + {name:"Plex",kind:"self-hosted",note:"browser login · server-side likes · remote discovery"}, {name:"Jellyfin",kind:"self-hosted",note:"API key / password, gapless, resume"}, {name:"Emby",kind:"self-hosted",note:"API key / password, resume"}, {name:"Navidrome",kind:"self-hosted",note:"Subsonic API · lyrics"}, diff --git a/ui/model/favorites.go b/ui/model/favorites.go index f7cb43518..640c28941 100644 --- a/ui/model/favorites.go +++ b/ui/model/favorites.go @@ -3,6 +3,7 @@ package model import ( "context" "errors" + "maps" "time" tea "charm.land/bubbletea/v2" @@ -21,14 +22,16 @@ var errFavoritesUnavailable = errors.New("favorites are not available") // trackFavoriteSyncedMsg reports the result of a provider favorite sync. type trackFavoriteSyncedMsg struct { provider string + path string + favorite bool err error } // favoriteTrackKey toggles the ♥ favorite for a track that a key selected. -// It does nothing without a favorites store, and shows an error in the status -// bar when the store fails. +// It does nothing without a favorites store unless the track's provider owns +// the favorite state, and shows an error in the status bar when a save fails. func (m *Model) favoriteTrackKey(track playlist.Track) tea.Cmd { - if m.favStore == nil { + if _, providerOwned := m.providerTrackFavoriteState(track); m.favStore == nil && !providerOwned { return nil } cmd, err := m.toggleTrackFavorite(track) @@ -39,9 +42,25 @@ func (m *Model) favoriteTrackKey(track playlist.Track) tea.Cmd { return cmd } -// toggleTrackFavorite toggles the displayed ♥ state. The local store and a -// provider-owned state are updated together when they apply to the track. +// toggleTrackFavorite toggles the displayed ♥ state. A provider that exposes +// authoritative state is changed without reading or writing the local store. +// Other providers receive a copy of the local favorite change. func (m *Model) toggleTrackFavorite(track playlist.Track) (tea.Cmd, error) { + if current, providerOwned := m.providerTrackFavoriteState(track); providerOwned { + favorite := !current + cmd := m.syncTrackFavoriteCmd(track, favorite) + if cmd == nil { + return nil, errFavoritesUnavailable + } + pending := maps.Clone(m.pendingTrackFavorites) + if pending == nil { + pending = make(map[string]bool) + } + pending[track.Path] = favorite + m.pendingTrackFavorites = pending + m.showTrackFavoriteStatus(track, favorite) + return cmd, nil + } if m.favStore == nil { return nil, errFavoritesUnavailable } @@ -57,12 +76,16 @@ func (m *Model) toggleTrackFavorite(track playlist.Track) (tea.Cmd, error) { // manager list refreshes itself on open. refresh = m.refreshPaneAfterLocalWrite() } + m.showTrackFavoriteStatus(track, favorite) + return tea.Batch(m.syncTrackFavoriteCmd(track, favorite), refresh), nil +} + +func (m *Model) showTrackFavoriteStatus(track playlist.Track, favorite bool) { if favorite { m.status.Showf(statusTTLMedium, "Favorited: %s", track.DisplayName()) } else { m.status.Showf(statusTTLMedium, "Unfavorited: %s", track.DisplayName()) } - return tea.Batch(m.syncTrackFavoriteCmd(track, favorite), refresh), nil } // findTrackFavoriter returns the first registered provider that owns track @@ -71,12 +94,19 @@ func (m *Model) findTrackFavoriter(track playlist.Track) (provider.TrackFavorite return findCapable(m, func(f provider.TrackFavoriter) bool { return f.CanFavoriteTrack(track) }) } -func (m *Model) providerTrackFavoriteState(track playlist.Track) (favorite, known bool) { +func (m *Model) providerTrackFavoriteState(track playlist.Track) (favorite, providerOwned bool) { state, _ := findCapable(m, func(s provider.TrackFavoriteState) bool { return s.CanFavoriteTrack(track) }) if state == nil { return false, false } - return state.FavoriteState(track) + if favorite, ok := m.pendingTrackFavorites[track.Path]; ok { + return favorite, true + } + // The provider owns the state even when this particular track has not + // been fetched in this process. Treat an unknown state as clear instead + // of falling back to a stale entry in favorites.toml. + favorite, _ = state.FavoriteState(track) + return favorite, true } // syncTrackFavoriteCmd copies a favorite change to the provider that owns @@ -101,13 +131,19 @@ func (m *Model) syncTrackFavoriteCmd(track playlist.Track, favorite bool) tea.Cm if !ran { return nil } - return trackFavoriteSyncedMsg{provider: name, err: err} + return trackFavoriteSyncedMsg{provider: name, path: track.Path, favorite: favorite, err: err} } } -// handleTrackFavoriteSynced keeps the local favorite when the provider call -// fails and tells the user which provider did not accept the change. +// handleTrackFavoriteSynced drops the optimistic provider state after the +// provider cache has been updated, or rolls it back after a failure. Local +// favorites copied to Spotify and Navidrome are unaffected. func (m *Model) handleTrackFavoriteSynced(msg trackFavoriteSyncedMsg) { + if pending, ok := m.pendingTrackFavorites[msg.path]; ok && pending == msg.favorite { + next := maps.Clone(m.pendingTrackFavorites) + delete(next, msg.path) + m.pendingTrackFavorites = next + } if msg.err != nil { m.status.Warningf(statusTTLMedium, "%s did not save the favorite: %s", msg.provider, msg.err) } diff --git a/ui/model/favorites_test.go b/ui/model/favorites_test.go index 21d08836d..8735e6491 100644 --- a/ui/model/favorites_test.go +++ b/ui/model/favorites_test.go @@ -49,7 +49,13 @@ func (p *fakeTrackFavoriter) SetTrackFavorite(_ context.Context, track playlist. return p.err } -func (p *fakeTrackFavoriter) FavoriteState(track playlist.Track) (favorite, known bool) { +// fakeAuthoritativeFavoriter models Plex: provider state replaces local +// favorites instead of receiving a copy of them. +type fakeAuthoritativeFavoriter struct { + *fakeTrackFavoriter +} + +func (p *fakeAuthoritativeFavoriter) FavoriteState(track playlist.Track) (favorite, known bool) { p.mu.Lock() defer p.mu.Unlock() favorite, known = p.liked[track.Path] @@ -321,11 +327,11 @@ func TestTrackFavoriteSyncRouting(t *testing.T) { func TestProviderFavoriteStateIsDisplayedAndToggled(t *testing.T) { m, store := favoriteKeyTestModel(t) track := playlist.Track{Path: "fake:track:liked", Title: "Liked"} - fake := &fakeTrackFavoriter{ + fake := &fakeAuthoritativeFavoriter{fakeTrackFavoriter: &fakeTrackFavoriter{ commandsTestProvider: commandsTestProvider{name: "Fake"}, prefix: "fake:", liked: map[string]bool{track.Path: true}, - } + }} m.provider = fake m.providers = append(m.providers, provider.Entry{Key: "fake", Name: "Fake", Provider: fake}) @@ -339,7 +345,11 @@ func TestProviderFavoriteStateIsDisplayedAndToggled(t *testing.T) { if store.IsFavorited(track.Path) { t.Fatal("removing a provider-only favorite added it to the local store") } - runCmd(cmd) + for _, msg := range runCmd(cmd) { + if synced, ok := msg.(trackFavoriteSyncedMsg); ok { + m.handleTrackFavoriteSynced(synced) + } + } if m.playlistTrackFavorited(track) { t.Fatal("provider favorite stayed displayed after removal") } @@ -355,17 +365,137 @@ func TestProviderFavoriteStateOverridesStaleLocalState(t *testing.T) { t.Fatal(err) } m.refreshFavSet() - fake := &fakeTrackFavoriter{ + fake := &fakeAuthoritativeFavoriter{fakeTrackFavoriter: &fakeTrackFavoriter{ commandsTestProvider: commandsTestProvider{name: "Fake"}, prefix: "fake:", liked: map[string]bool{track.Path: false}, - } + }} m.provider = fake m.providers = append(m.providers, provider.Entry{Key: "fake", Name: "Fake", Provider: fake}) if m.playlistTrackFavorited(track) { t.Fatal("stale local favorite overrode the state returned by the provider") } + cmd, err := m.toggleTrackFavorite(track) + if err != nil { + t.Fatal(err) + } + if !store.IsFavorited(track.Path) { + t.Fatal("provider toggle removed the stale local entry") + } + for _, msg := range runCmd(cmd) { + if synced, ok := msg.(trackFavoriteSyncedMsg); ok { + m.handleTrackFavoriteSynced(synced) + } + } + if !m.playlistTrackFavorited(track) { + t.Fatal("provider favorite was not displayed after the server update") + } + if !store.IsFavorited(track.Path) { + t.Fatal("server update changed the stale local entry") + } +} + +func TestUnknownProviderFavoriteIgnoresLocalState(t *testing.T) { + m, store := favoriteKeyTestModel(t) + track := playlist.Track{Path: "fake:track:unknown", Title: "Unknown"} + if _, err := store.Toggle(track); err != nil { + t.Fatal(err) + } + m.refreshFavSet() + fake := &fakeAuthoritativeFavoriter{fakeTrackFavoriter: &fakeTrackFavoriter{ + commandsTestProvider: commandsTestProvider{name: "Fake"}, + prefix: "fake:", + }} + m.providers = append(m.providers, provider.Entry{Key: "fake", Name: "Fake", Provider: fake}) + + if m.playlistTrackFavorited(track) { + t.Fatal("unknown provider state fell back to the local favorite") + } +} + +func TestProviderFavoriteWorksWithoutLocalStore(t *testing.T) { + m, _ := favoriteKeyTestModel(t) + m.favStore = nil + track := playlist.Track{Path: "fake:track:1", Title: "Remote"} + fake := &fakeAuthoritativeFavoriter{fakeTrackFavoriter: &fakeTrackFavoriter{ + commandsTestProvider: commandsTestProvider{name: "Fake"}, + prefix: "fake:", + liked: map[string]bool{track.Path: false}, + }} + m.providers = append(m.providers, provider.Entry{Key: "fake", Name: "Fake", Provider: fake}) + + cmd := m.favoriteTrackKey(track) + if cmd == nil { + t.Fatal("provider favorite needed a local store") + } + runCmd(cmd) + if got := fake.recorded(); len(got) != 1 || got[0] != "add "+track.Path { + t.Fatalf("provider calls = %v, want one add", got) + } +} + +func TestProviderFavoritePendingStateKeepsLastToggle(t *testing.T) { + m, _ := favoriteKeyTestModel(t) + track := playlist.Track{Path: "fake:track:1", Title: "Remote"} + fake := &fakeAuthoritativeFavoriter{fakeTrackFavoriter: &fakeTrackFavoriter{ + commandsTestProvider: commandsTestProvider{name: "Fake"}, + prefix: "fake:", + liked: map[string]bool{track.Path: false}, + }} + m.providers = append(m.providers, provider.Entry{Key: "fake", Name: "Fake", Provider: fake}) + + first, err := m.toggleTrackFavorite(track) + if err != nil { + t.Fatal(err) + } + second, err := m.toggleTrackFavorite(track) + if err != nil { + t.Fatal(err) + } + runCmd(second) + runCmd(first) + if got := fake.recorded(); len(got) != 1 || got[0] != "remove "+track.Path { + t.Fatalf("provider calls = %v, want only the last state", got) + } +} + +func TestProviderFavoriteFailureRollsBackWithoutChangingLocalState(t *testing.T) { + m, store := favoriteKeyTestModel(t) + track := playlist.Track{Path: "fake:track:1", Title: "Remote"} + if _, err := store.Toggle(track); err != nil { + t.Fatal(err) + } + m.refreshFavSet() + fake := &fakeAuthoritativeFavoriter{fakeTrackFavoriter: &fakeTrackFavoriter{ + commandsTestProvider: commandsTestProvider{name: "Fake"}, + prefix: "fake:", + err: errors.New("offline"), + liked: map[string]bool{track.Path: false}, + }} + m.providers = append(m.providers, provider.Entry{Key: "fake", Name: "Fake", Provider: fake}) + + cmd, err := m.toggleTrackFavorite(track) + if err != nil { + t.Fatal(err) + } + if !m.playlistTrackFavorited(track) { + t.Fatal("pending provider favorite was not displayed") + } + for _, msg := range runCmd(cmd) { + if synced, ok := msg.(trackFavoriteSyncedMsg); ok { + m.handleTrackFavoriteSynced(synced) + } + } + if m.playlistTrackFavorited(track) { + t.Fatal("failed provider favorite did not roll back") + } + if !store.IsFavorited(track.Path) { + t.Fatal("failed provider favorite changed the stale local entry") + } + if m.status.kind != feedbackWarning || m.status.text != "Fake did not save the favorite: offline" { + t.Fatalf("status = %v %q", m.status.kind, m.status.text) + } } // A second toggle made before the first provider call runs wins, so the diff --git a/ui/model/keys_radio.go b/ui/model/keys_radio.go index c1a84c01d..a6ecccf95 100644 --- a/ui/model/keys_radio.go +++ b/ui/model/keys_radio.go @@ -191,7 +191,7 @@ func (m *Model) togglePlaylistTrackFavorite(track playlist.Track, savedPlaylist // shows the state that f toggles. The render path calls it, so it must not do // I/O. func (m Model) playlistTrackFavorited(track playlist.Track) bool { - if favorite, known := m.providerTrackFavoriteState(track); known { + if favorite, providerOwned := m.providerTrackFavoriteState(track); providerOwned { return favorite } return trackFavorited(track, m.favSet, m.radioFavorites, m.loadedPlaylist != "") @@ -205,7 +205,7 @@ func (m Model) trackFavoriteLookup(playback bool) func(playlist.Track) bool { favSet, stations := m.favSet, m.radioFavorites saved := playback && m.loadedPlaylist != "" return func(track playlist.Track) bool { - if favorite, known := m.providerTrackFavoriteState(track); known { + if favorite, providerOwned := m.providerTrackFavoriteState(track); providerOwned { return favorite } return trackFavorited(track, favSet, stations, saved) diff --git a/ui/model/model.go b/ui/model/model.go index ef254a628..5a0c695b7 100644 --- a/ui/model/model.go +++ b/ui/model/model.go @@ -540,6 +540,10 @@ type Model struct { // favSync orders the calls that copy favorite changes to providers. It // is created on first use and shared across Model value copies. favSync *favorites.SyncQueue + // pendingTrackFavorites holds optimistic states for providers whose own + // favorite state is authoritative. The map is replaced, never mutated, so + // commands can safely capture a Model copy while a request is in flight. + pendingTrackFavorites map[string]bool // reports orders the now-playing, progress and scrobble reports to // providers. It is shared across Model value copies. reports *reportQueue From b43b7bf5f1c0d8f7126b6a731b82fd8c5053153a Mon Sep 17 00:00:00 2001 From: Igor Maliavko Date: Tue, 27 Oct 2026 10:14:07 +0100 Subject: [PATCH 07/32] feat(plex): restore the play context after restart After a restart, Plex lost the album or playlist a track was played from and its position; only Jellyfin and Emby restored their context. Plex now implements RestoreTrack, which claims token-free plex:track paths, and the resume code works with a small contextServer interface instead of the Emby client type. When Plex is the default provider (config or --provider), cliamp saves the list, the track and the position while playing and at exit, and restores the list with the track selected on the next start. Credentials are added only when playback starts, so resume.json holds no token; a legacy token URL is not restored. Docs, site and CLAUDE.md mention Plex. Verified with make check (gofmt, go vet, go test ./...). Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 4 +-- docs/plex.md | 10 +++++++ external/plex/provider.go | 18 +++++++++++++ external/plex/provider_test.go | 36 +++++++++++++++++++++++++ jellyfin_restore_test.go | 49 ++++++++++++++++++++++++++++++++++ main.go | 27 ++++++++++--------- main_test.go | 33 ++++++++++++++++++----- providers.go | 21 ++++++++++----- providers_test.go | 2 +- site/index.html | 2 +- 10 files changed, 172 insertions(+), 30 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 5fdd1f190..ffc6ecd08 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -29,7 +29,7 @@ Package `main` at the repo root: | File | Responsibility | |------|----------------| | `main.go` | `run(...)` for the TUI and headless mode: config, player, playlist, Model, Bubbletea program, IPC server and exit save. It also holds the V2 dispatcher `newV2Dispatcher`, the operation set `v2Operations` and the plugin jobs | -| `providers.go` | `buildProviders` and the `providerKeys` table that `--provider` reads. The player hooks `registerPlayerHooks` and `isBufferedProviderURL`. The sign-in URL observers, the Jellyfin and Emby resume context and the yt-dlp install prompt | +| `providers.go` | `buildProviders` and the `providerKeys` table that `--provider` reads. The player hooks `registerPlayerHooks` and `isBufferedProviderURL`. The sign-in URL observers, the Jellyfin, Emby and Plex resume context and the yt-dlp install prompt | | `lua_wiring.go` | The Lua state, control and UI providers. `newLuaSender` queues the plugin messages for `prog.Send`, so a plugin never waits on the event loop | | `commands.go` | The root flags and every subcommand | | `ipc_client.go` | The V2 client of the subcommands, `cliamp open` and `cliamp remote`. Each call waits a bounded time | @@ -84,7 +84,7 @@ Other directories: `docs/` holds the user docs, one `.md` per feature. `site/` i `cliamp --daemon` or `cliamp -d` runs the same `model.Model` as the TUI. The program has no renderer and no input. `SetHeadless(true)` makes `View` return nothing and uses the low-power tick. Headless mode loads the Lua plugins, sends now-playing and scrobble reports, records history when a track starts and preloads the next track, as the TUI does. It differs from the TUI in these ways: -- It does not open the provider browser at start or restore a Jellyfin or Emby context. +- It does not open the provider browser at start or restore a Jellyfin, Emby or Plex context. - It never offers to install yt-dlp. - `v2Operations` removes the `theme` and `vis` operations. - It keeps the saved theme at exit. diff --git a/docs/plex.md b/docs/plex.md index 5a48be16a..48913fdd9 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -101,6 +101,16 @@ in another client while the list is open. While a Plex track plays, cliamp reports its timeline position about every 15 seconds. After at least half of a known-duration track has played, leaving the track records one Plex play and updates Plex history. Short skips do not increment the play count. +When Plex is the default provider (`provider = "plex"` or `--provider plex`), +cliamp remembers the most recently played Plex track, its playback position, +and the album or playlist it was chosen from. State is saved when a track +starts, every two seconds during confirmed playback, and during a normal exit. +On the next launch with no explicit files, URLs, or playlist, cliamp restores +that list with the last track selected. Press `Enter` to continue from the saved +position; `auto_play` is ignored for a restored list. The saved list keeps only +token-free `plex:track:` paths, and the current Plex credentials are added when +playback starts. This works as it does for [Jellyfin](jellyfin.md#usage). + Start cliamp with Plex as the default provider: ```bash diff --git a/external/plex/provider.go b/external/plex/provider.go index 5d6d5ac40..1bfcfd5b6 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -348,6 +348,24 @@ func (p *Provider) SetTrackFavorite(ctx context.Context, track playlist.Track, f return nil } +// RestoreTrack claims a saved Plex track for the resume context. The path is +// already the token-free plex:track URI, and ResolveSource adds the current +// credentials when playback starts, so the track is only checked and tagged. +func (p *Provider) RestoreTrack(track playlist.Track) (playlist.Track, bool) { + id, ok := trackIDFromPath(track.Path) + if !ok { + return playlist.Track{}, false + } + meta := make(map[string]string, len(track.ProviderMeta)+1) + for k, v := range track.ProviderMeta { + meta[k] = v + } + meta[provider.MetaPlexID] = id + track.ProviderMeta = meta + track.Stream = true + return track, true +} + func plexTrackID(track playlist.Track) string { if id := track.Meta(provider.MetaPlexID); id != "" { return id diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index ce95093a1..b13c51c5f 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -643,3 +643,39 @@ func TestNewFromConfig_LibrariesWired(t *testing.T) { }) } } + +func TestProviderRestoreTrack(t *testing.T) { + p := newProvider(NewClient("http://plex.example.com:32400", "token")) + tests := []struct { + name string + path string + want bool + }{ + {name: "plex track", path: TrackURIPrefix + "200", want: true}, + {name: "token URL", path: "http://plex.example.com:32400/library/parts/1/file.flac?X-Plex-Token=token"}, + {name: "local file", path: "/music/song.mp3"}, + {name: "bad rating key", path: TrackURIPrefix + "../200"}, + {name: "empty rating key", path: TrackURIPrefix}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + in := playlist.Track{Path: tt.path, Title: "Song", ProviderMeta: map[string]string{"other": "kept"}} + got, ok := p.RestoreTrack(in) + if ok != tt.want { + t.Fatalf("RestoreTrack ok = %v, want %v", ok, tt.want) + } + if !ok { + return + } + if got.Path != tt.path || got.Title != "Song" || !got.Stream { + t.Fatalf("restored track = %+v", got) + } + if got.Meta(provider.MetaPlexID) != "200" || got.Meta("other") != "kept" { + t.Fatalf("restored meta = %v", got.ProviderMeta) + } + if in.ProviderMeta[provider.MetaPlexID] != "" { + t.Fatal("RestoreTrack mutated the caller's metadata map") + } + }) + } +} diff --git a/jellyfin_restore_test.go b/jellyfin_restore_test.go index d26840e65..b2e6bd3b1 100644 --- a/jellyfin_restore_test.go +++ b/jellyfin_restore_test.go @@ -8,6 +8,7 @@ import ( "github.com/bjarneo/cliamp/config" "github.com/bjarneo/cliamp/external/emby" "github.com/bjarneo/cliamp/external/jellyfin" + "github.com/bjarneo/cliamp/external/plex" "github.com/bjarneo/cliamp/internal/resume" "github.com/bjarneo/cliamp/playlist" "github.com/bjarneo/cliamp/provider" @@ -131,3 +132,51 @@ func TestRestoreServerContextValidatesActiveEntry(t *testing.T) { }) } } + +// A Plex context keeps its token-free plex:track paths and restores only when +// the active track is a Plex track. +func TestRestoreServerContextRestoresPlexContext(t *testing.T) { + prov := plex.NewFromConfig(config.PlexConfig{URL: "http://plex.example.com:32400", Token: "token"}) + one, two := plex.TrackURIPrefix+"100", plex.TrackURIPrefix+"200" + tests := []struct { + name string + state resume.State + want bool + }{ + { + name: "album", + state: resume.State{Path: two, PositionSec: 42, ContextIndex: 1, + Context: []playlist.Track{{Path: one, Title: "One"}, {Path: two, Title: "Two"}}}, + want: true, + }, + { + name: "active track from another source", + state: resume.State{Path: "/music/two.mp3", PositionSec: 42, + Context: []playlist.Track{{Path: one}, {Path: "/music/two.mp3"}}}, + }, + { + name: "legacy token URL", + state: resume.State{Path: "http://plex.example.com:32400/library/parts/1/file.flac?X-Plex-Token=old", PositionSec: 42, + Context: []playlist.Track{{Path: "http://plex.example.com:32400/library/parts/1/file.flac?X-Plex-Token=old"}}}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tracks, index, activePath, ok := restoreServerContext(tt.state, prov) + if ok != tt.want { + t.Fatalf("restoreServerContext() ok = %v, want %v", ok, tt.want) + } + if !ok { + return + } + if index != 1 || activePath != two || tracks[index].Title != "Two" { + t.Fatalf("restored index=%d path=%q tracks=%+v", index, activePath, tracks) + } + for _, track := range tracks { + if !strings.HasPrefix(track.Path, plex.TrackURIPrefix) || track.Meta(provider.MetaPlexID) == "" || !track.Stream { + t.Fatalf("restored track %+v is not a tagged token-free Plex stream", track) + } + } + }) + } +} diff --git a/main.go b/main.go index bc9397391..474d7dca2 100644 --- a/main.go +++ b/main.go @@ -22,7 +22,6 @@ import ( "github.com/bjarneo/cliamp/external/radio" "github.com/bjarneo/cliamp/internal/appdir" "github.com/bjarneo/cliamp/internal/appmeta" - "github.com/bjarneo/cliamp/internal/embyapi" "github.com/bjarneo/cliamp/internal/playback" "github.com/bjarneo/cliamp/internal/resume" "github.com/bjarneo/cliamp/ipc" @@ -202,7 +201,7 @@ func run(overrides config.Overrides, positional []string, headless, visualizer60 configureModel(&m, cfg, headless, visualizer60FPS) if resumeState.Path != "" && resumeState.PositionSec > 0 { - // Jellyfin and Emby resume the restored context above. Mixcloud is also commonly + // Jellyfin, Emby and Plex resume the restored context above. Mixcloud is also commonly // opened from its provider browser rather than a positional URL; preserve // cliamp's existing positional-file behavior for other providers. switch { @@ -397,9 +396,9 @@ func startIPC(send func(tea.Msg), broker *ipc.Broker, plugins *luaplugin.Manager } // saveOnExit keeps the theme and the resume position of the final Model. -// When a Jellyfin or Emby server is the default provider, it also keeps the +// When a Jellyfin, Emby or Plex server is the default provider, it also keeps the // list that the track played from. -func saveOnExit(final tea.Model, headless bool, resumeServer *embyapi.Provider) { +func saveOnExit(final tea.Model, headless bool, resumeServer contextServer) { fm, ok := final.(model.Model) if !ok { return @@ -418,20 +417,22 @@ func saveOnExit(final tea.Model, headless bool, resumeServer *embyapi.Provider) } // saveExitResume saves the track and the position of the exit. When -// resumeServer is set and path is a Jellyfin or Emby stream, it also saves +// resumeServer is set and owns the track at path, it also saves // the list that resumeContext returns. A track with no position saves // nothing. -func saveExitResume(path string, secs int, playlistName string, resumeContext func() ([]playlist.Track, int), resumeServer *embyapi.Provider) { +func saveExitResume(path string, secs int, playlistName string, resumeContext func() ([]playlist.Track, int), resumeServer contextServer) { if path == "" || secs <= 0 { return } - if resumeServer != nil && embyapi.IsStreamURL(path) { - tracks, index := resumeContext() - resume.SaveState(resume.State{ - Path: path, PositionSec: secs, Playlist: playlistName, - Context: tracks, ContextIndex: index, - }) - return + if resumeServer != nil { + if _, ok := resumeServer.RestoreTrack(playlist.Track{Path: path}); ok { + tracks, index := resumeContext() + resume.SaveState(resume.State{ + Path: path, PositionSec: secs, Playlist: playlistName, + Context: tracks, ContextIndex: index, + }) + return + } } resume.Save(path, secs, playlistName) } diff --git a/main_test.go b/main_test.go index bf89d6720..dec8ed93f 100644 --- a/main_test.go +++ b/main_test.go @@ -9,7 +9,7 @@ import ( "github.com/bjarneo/cliamp/config" "github.com/bjarneo/cliamp/external/emby" - "github.com/bjarneo/cliamp/internal/embyapi" + "github.com/bjarneo/cliamp/external/plex" "github.com/bjarneo/cliamp/internal/resume" "github.com/bjarneo/cliamp/playlist" ) @@ -65,9 +65,9 @@ func TestCheckTerminalOutput(t *testing.T) { } } -// At exit, a Jellyfin or Emby stream saves the list it played from when such -// a server is the default provider. Any other track saves only its position, -// and a track with no position saves nothing. +// At exit, a Jellyfin, Emby or Plex track saves the list it played from when +// its server is the default provider. Any other track saves only its +// position, and a track with no position saves nothing. func TestSaveExitResume(t *testing.T) { server := emby.NewFromConfig(config.EmbyConfig{ URL: "https://emby.example.com", Token: "token", UserID: "user-1", @@ -77,18 +77,37 @@ func TestSaveExitResume(t *testing.T) { {Path: "https://emby.example.com/Items/one/Download?api_key=token", Title: "One"}, {Path: stream, Title: "Two"}, } + plexServer := plex.NewFromConfig(config.PlexConfig{URL: "http://plex.example.com:32400", Token: "token"}) + plexTrack := plex.TrackURIPrefix + "200" + plexTracks := []playlist.Track{ + {Path: plex.TrackURIPrefix + "100", Title: "One"}, + {Path: plexTrack, Title: "Two"}, + } for _, tt := range []struct { name string path string secs int - server *embyapi.Provider + server contextServer + tracks []playlist.Track want resume.State useContext bool }{ { - name: "server stream", path: stream, secs: 95, server: server.Provider, useContext: true, + name: "server stream", path: stream, secs: 95, server: server.Provider, tracks: tracks, useContext: true, want: resume.State{Path: stream, PositionSec: 95, Playlist: "Mix", Context: tracks, ContextIndex: 1}, }, + { + name: "plex track", path: plexTrack, secs: 95, server: plexServer, tracks: plexTracks, useContext: true, + want: resume.State{Path: plexTrack, PositionSec: 95, Playlist: "Mix", Context: plexTracks, ContextIndex: 1}, + }, + { + name: "emby stream with plex server", path: stream, secs: 95, server: plexServer, + want: resume.State{Path: stream, PositionSec: 95, Playlist: "Mix"}, + }, + { + name: "plex track with emby server", path: plexTrack, secs: 95, server: server.Provider, + want: resume.State{Path: plexTrack, PositionSec: 95, Playlist: "Mix"}, + }, { name: "stream without server", path: stream, secs: 95, want: resume.State{Path: stream, PositionSec: 95, Playlist: "Mix"}, @@ -104,7 +123,7 @@ func TestSaveExitResume(t *testing.T) { usedContext := false resumeContext := func() ([]playlist.Track, int) { usedContext = true - return tracks, 1 + return tt.tracks, 1 } saveExitResume(tt.path, tt.secs, "Mix", resumeContext, tt.server) if got := resume.Load(); !reflect.DeepEqual(got, tt.want) { diff --git a/providers.go b/providers.go index 9bba91807..7afe2f37c 100644 --- a/providers.go +++ b/providers.go @@ -339,11 +339,11 @@ func (s *providerSet) localPlaylists() playlist.Provider { return s.local } -// resumeServer returns the Jellyfin or Emby provider when key names one that +// resumeServer returns the Jellyfin, Emby or Plex provider when key names one that // is configured. When such a server is the default provider, cliamp saves // the list that a track was played from and restores it at the next start. // It returns nil for any other key. -func (s *providerSet) resumeServer(key string) *embyapi.Provider { +func (s *providerSet) resumeServer(key string) contextServer { for _, e := range s.entries { if e.Key != key { continue @@ -353,11 +353,20 @@ func (s *providerSet) resumeServer(key string) *embyapi.Provider { return p.Provider case *emby.Provider: return p.Provider + case *plex.Provider: + return p } } return nil } +// contextServer is a provider whose play context survives a restart: +// Jellyfin, Emby and Plex. RestoreTrack reports whether a saved track is +// its own and returns it ready to play with the current credentials. +type contextServer interface { + RestoreTrack(track playlist.Track) (playlist.Track, bool) +} + // registerPlayerHooks registers with p the stream factories and source // resolvers of the providers, and the rules that pick the pipeline of a URL. func (s *providerSet) registerPlayerHooks(p *player.Player) { @@ -495,7 +504,7 @@ func (s *providerSet) observeAuthURLs(send func(tea.Msg)) (restore func()) { // serverResumeSaver saves the play context of each track that server owns, // so the next start can restore it. -func serverResumeSaver(server *embyapi.Provider) model.ResumeSaver { +func serverResumeSaver(server contextServer) model.ResumeSaver { return func(track playlist.Track, positionSec int, context []playlist.Track, contextIndex int) { if _, ok := server.RestoreTrack(track); !ok { return @@ -507,10 +516,10 @@ func serverResumeSaver(server *embyapi.Provider) model.ResumeSaver { } } -// restoreServerContext rebuilds the saved play context of a Jellyfin or -// Emby server. It returns the tracks, the index and the path of the track +// restoreServerContext rebuilds the saved play context of a Jellyfin, Emby or +// Plex server. It returns the tracks, the index and the path of the track // that played. It fails when that track is not from this server. -func restoreServerContext(state resume.State, prov *embyapi.Provider) ([]playlist.Track, int, string, bool) { +func restoreServerContext(state resume.State, prov contextServer) ([]playlist.Track, int, string, bool) { if prov == nil || len(state.Context) == 0 { return nil, 0, "", false } diff --git a/providers_test.go b/providers_test.go index 96fa62752..013bdeab1 100644 --- a/providers_test.go +++ b/providers_test.go @@ -100,7 +100,7 @@ func TestBuildProviders(t *testing.T) { t.Fatal("the local provider and the radio favorites must be set") } for _, key := range []string{"jellyfin", "emby", "plex"} { - want := key != "plex" && slices.Contains(tt.want, key) + want := slices.Contains(tt.want, key) if got := set.resumeServer(key) != nil; got != want { t.Errorf("resumeServer(%q) set = %v, want %v", key, got, want) } diff --git a/site/index.html b/site/index.html index 1ac2da644..5a804ad50 100644 --- a/site/index.html +++ b/site/index.html @@ -659,7 +659,7 @@

Close the tab. Play the music.

{name:"Telegram",kind:"streaming",note:"MTProto · phone login"}, {name:"Bandcamp",kind:"streaming",note:"your purchases · Subsonic API"}, {name:"Bilibili",kind:"streaming",note:"video audio · yt-dlp"}, - {name:"Plex",kind:"self-hosted",note:"browser login · server-side likes · remote discovery"}, + {name:"Plex",kind:"self-hosted",note:"browser login · server-side likes · remote discovery · resume"}, {name:"Jellyfin",kind:"self-hosted",note:"API key / password, gapless, resume"}, {name:"Emby",kind:"self-hosted",note:"API key / password, resume"}, {name:"Navidrome",kind:"self-hosted",note:"Subsonic API · lyrics"}, From d9ce5acc25c525b4639855156f4f15ba8c9bc533 Mon Sep 17 00:00:00 2001 From: Igor Maliavko Date: Tue, 27 Oct 2026 10:14:27 +0100 Subject: [PATCH 08/32] fix(ui): show the resume position before playback A restored track waiting to resume showed 0:00 and an empty seek bar until playback reached the saved position, for every provider with resume (Jellyfin, Emby, Plex, Mixcloud and positional files). Until the engine plays the track, before Enter and while it buffers, the TUI clock shows the saved position and the track's duration. Media controls and IPC still report the engine position. Verified with make check (gofmt, go vet, go test ./...). Co-Authored-By: Claude Opus 5.5 --- docs/jellyfin.md | 2 +- docs/plex.md | 4 ++-- ui/model/tick.go | 22 ++++++++++++++++++++++ ui/model/tick_test.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 67 insertions(+), 3 deletions(-) diff --git a/docs/jellyfin.md b/docs/jellyfin.md index a4c571fed..e01878a71 100644 --- a/docs/jellyfin.md +++ b/docs/jellyfin.md @@ -52,7 +52,7 @@ Jellyfin opens directly in **By Artist / Album** mode. Artists are listed alphab When Jellyfin is the default provider, cliamp remembers the most recently played Jellyfin track, its playback position, and the complete album or track list it was chosen from. Queued tracks retain their own source context, including duplicate entries. State is saved when a track starts, every two seconds during confirmed playback, and during a normal exit. `q` and `Ctrl+C` save the current position; terminal closure or an abrupt exit restores the last checkpoint. Buffering and unfinished seeks do not overwrite it with an unconfirmed position. -On the next launch with no explicit files, URLs, or playlist, cliamp restores that context with the last track selected. Press `Enter` to continue from the saved position. An explicitly configured `auto_play` setting is ignored for restored context so reopening cliamp stays silent. Saved stream URLs use current authentication when playback or preloading starts, including username-and-password sessions, without waiting for authentication during restoration. +On the next launch with no explicit files, URLs, or playlist, cliamp restores that context with the last track selected; the time and seek bar already show the saved position. Press `Enter` to continue from it. An explicitly configured `auto_play` setting is ignored for restored context so reopening cliamp stays silent. Saved stream URLs use current authentication when playback or preloading starts, including username-and-password sessions, without waiting for authentication during restoration. Press `N` while browsing Jellyfin to temporarily switch to **By Album** or **By Artist**. These alternate modes apply only to the current session; the next launch without a remembered track returns to **By Artist / Album**. diff --git a/docs/plex.md b/docs/plex.md index 48913fdd9..13c36aa22 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -106,8 +106,8 @@ cliamp remembers the most recently played Plex track, its playback position, and the album or playlist it was chosen from. State is saved when a track starts, every two seconds during confirmed playback, and during a normal exit. On the next launch with no explicit files, URLs, or playlist, cliamp restores -that list with the last track selected. Press `Enter` to continue from the saved -position; `auto_play` is ignored for a restored list. The saved list keeps only +that list with the last track selected; the time and seek bar already show the +saved position. Press `Enter` to continue from it; `auto_play` is ignored for a restored list. The saved list keeps only token-free `plex:track:` paths, and the current Plex credentials are added when playback starts. This works as it does for [Jellyfin](jellyfin.md#usage). diff --git a/ui/model/tick.go b/ui/model/tick.go index 7f9b40662..515dc9818 100644 --- a/ui/model/tick.go +++ b/ui/model/tick.go @@ -374,10 +374,32 @@ func (m *Model) playbackClock() (time.Duration, time.Duration) { return m.player.PositionAndDuration() } +// pendingResumeClock is the TUI clock of a track that will resume at a saved +// position. Until playback reaches it, before Enter and while the track +// buffers, the time and seek bar show where playback continues instead of +// 0:00. The media controls and IPC keep reporting the engine position. +func (m *Model) pendingResumeClock() (time.Duration, time.Duration, bool) { + if m.resume.path == "" || m.resume.secs <= 0 || m.seek.active { + return 0, 0, false + } + if !m.buffering && m.player != nil && m.player.IsPlaying() { + return 0, 0, false + } + track, _ := m.currentPlaybackTrack() + if track.Path != m.resume.path { + return 0, 0, false + } + return time.Duration(m.resume.secs) * time.Second, time.Duration(track.DurationSecs) * time.Second, true +} + // tickSampleClock caches the position and duration once per tick, so that // the View render functions do not take speaker.Lock() several times. // PositionAndDuration() batches both reads under one speaker lock. func (m *Model) tickSampleClock() { + if pos, dur, ok := m.pendingResumeClock(); ok { + m.cachedPos, m.cachedDur = pos, dur + return + } if m.buffering { m.cachedPos, m.cachedDur = m.playbackClock() return diff --git a/ui/model/tick_test.go b/ui/model/tick_test.go index 37a3343ae..fcc1938a7 100644 --- a/ui/model/tick_test.go +++ b/ui/model/tick_test.go @@ -616,3 +616,45 @@ func TestTickReconnect(t *testing.T) { }) } } + +// Before Enter and while the restored track buffers, the TUI clock shows the +// saved resume position; once the track plays, it follows the engine. +func TestTickSampleClockShowsPendingResume(t *testing.T) { + saved := playlist.Track{Path: "plex:track:200", Title: "Saved", DurationSecs: 300} + other := playlist.Track{Path: "plex:track:100", Title: "Other", DurationSecs: 200} + tests := []struct { + name string + current int + playing bool + buffering bool + resume int + wantPos time.Duration + wantDur time.Duration + }{ + {name: "stopped on saved track", current: 1, resume: 95, wantPos: 95 * time.Second, wantDur: 300 * time.Second}, + {name: "buffering saved track", current: 1, buffering: true, resume: 95, wantPos: 95 * time.Second, wantDur: 300 * time.Second}, + {name: "another track selected", current: 0, resume: 95}, + {name: "no resume", current: 1}, + {name: "playing follows engine", current: 1, playing: true, resume: 95, wantPos: 10 * time.Second, wantDur: 300 * time.Second}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + engine := &playbackFakeEngine{playing: tt.playing, position: 10 * time.Second, duration: 300 * time.Second} + if !tt.playing { + engine.position, engine.duration = 0, 0 + } + pl := playlist.New() + pl.Replace([]playlist.Track{other, saved}) + pl.SetIndex(tt.current) + m := New(engine, pl, nil, "", nil, nil, nil, nil, nil, nil) + m.buffering = tt.buffering + if tt.resume > 0 { + m.SetResume(saved.Path, tt.resume) + } + m.tickSampleClock() + if m.cachedPos != tt.wantPos || m.cachedDur != tt.wantDur { + t.Fatalf("clock = %v / %v, want %v / %v", m.cachedPos, m.cachedDur, tt.wantPos, tt.wantDur) + } + }) + } +} From 8ab2c664005fbe50efe230df07d28e75e7ed5ee6 Mon Sep 17 00:00:00 2001 From: Igor Maliavko Date: Tue, 27 Oct 2026 10:59:25 +0100 Subject: [PATCH 09/32] feat(plex): sign out from cliamp setup There was no way to sign out of Plex: the token stayed in config.toml until it was deleted by hand, and it stayed valid at Plex. While [plex] holds a token, the Plex page of cliamp setup offers only "Sign out and remove saved credentials"; without one it offers the two sign-in modes. Sign-out of a browser sign-in asks plex.tv to revoke the token (DELETE /api/v2/users/signout) and checks that plex.tv then rejects it. A manual token belongs to a Plex Web session and is not revoked. Either way token, libraries and, for a browser sign-in, server_id and url are removed, even when the revoke fails, which is shown as a warning. client_id stays, so a new sign-in is the same device. Picker options can now be hidden per provider state. A Plex picker test read the real config.toml; it now uses a temporary config directory. Verified with make check (gofmt, go vet, go test ./...). Co-Authored-By: Claude Opus 5.5 --- cmd/setup.go | 129 +++++++++++++++++++++++++++++++--- cmd/setup_test.go | 119 +++++++++++++++++++++++++++++++ docs/cli.md | 2 +- docs/plex.md | 18 +++++ external/plex/account.go | 50 +++++++++++++ external/plex/account_test.go | 60 ++++++++++++++++ site/index.html | 2 +- 7 files changed, 369 insertions(+), 11 deletions(-) diff --git a/cmd/setup.go b/cmd/setup.go index 69fe9f349..79a63940d 100644 --- a/cmd/setup.go +++ b/cmd/setup.go @@ -135,6 +135,9 @@ type pickerSpec struct { type pickerOption struct { value string label string + // show, when non-nil, hides the option unless it returns true when the + // provider opens, such as Plex sign-out without saved credentials. + show func() bool } // Picker keys are stored in the values map alongside real field keys; the @@ -255,8 +258,11 @@ func providers() []providerSpec { key: keyPlexAuth, label: "Authentication", options: []pickerOption{ - {value: "account", label: "Sign in with Plex in a browser (recommended)"}, - {value: "manual", label: "Enter a server URL and X-Plex-Token"}, + // A saved token offers only sign-out; changing the server + // or the login type is a sign-out and a new sign-in. + {value: "account", label: "Sign in with Plex in a browser (recommended)", show: plexSignedOut}, + {value: "manual", label: "Enter a server URL and X-Plex-Token", show: plexSignedOut}, + {value: "signout", label: "Sign out and remove saved credentials", show: plexSignedIn}, }, }, fields: []fieldSpec{ @@ -264,7 +270,8 @@ func providers() []providerSpec { onlyIf: func(v map[string]string) bool { return v[keyPlexAuth] == "manual" }}, {key: "token", label: "X-Plex-Token", required: true, secret: true, onlyIf: func(v map[string]string) bool { return v[keyPlexAuth] == "manual" }}, - {key: "libraries", label: "Music libraries (optional)", help: "comma-separated names to include; blank loads every music library"}, + {key: "libraries", label: "Music libraries (optional)", help: "comma-separated names to include; blank loads every music library", + onlyIf: func(v map[string]string) bool { return v[keyPlexAuth] != "signout" }}, }, validate: func(v map[string]string) error { if v[keyPlexAuth] == "account" { @@ -967,6 +974,22 @@ func setupStringList(value string) string { return "[" + strings.Join(quoted, ", ") + "]" } +// plexSignedIn reports whether [plex] holds a token that sign-out can remove. +func plexSignedIn() bool { + cfg, err := config.Load() + return err == nil && cfg.Plex.Token != "" +} + +func plexSignedOut() bool { return !plexSignedIn() } + +// plexSignOut revokes an account token at plex.tv. Tests replace it. +var plexSignOut = func(ctx context.Context, token, clientID string) error { + return plex.NewAccountAPI().SignOut(ctx, token, clientID) +} + +// plexSignOutTimeout bounds the revoke and the check that follows it. +const plexSignOutTimeout = 30 * time.Second + func plexSetupClientID() (string, error) { if cfg, err := config.Load(); err == nil && cfg.Plex.ClientID != "" { return cfg.Plex.ClientID, nil @@ -1007,6 +1030,7 @@ type setupModel struct { // picker state (within a provider) pickerCursor int + pickerOpts []pickerOption // the picker options shown for this provider // form state values map[string]string @@ -1038,6 +1062,8 @@ type setupModel struct { resultErr error resultWarning bool // validation failed but config still valid resultText string // overall message (e.g. "Saved [navidrome] section.") + warnText string // replaces the default warning title when set + resultNote string // extra lines under the result title saveFailed error // io error writing config (rare; shown as error result) awaitingSave bool // true after a failed validate: waiting for y/n @@ -1210,6 +1236,27 @@ func discoverPlexServersCmd(api *plex.AccountAPI, token, clientID string) tea.Cm } } +// plexSignOutDoneMsg ends a Plex sign-out. account reports a browser +// sign-in, whose token cliamp revokes; err is the revoke failure, if any. +type plexSignOutDoneMsg struct { + account bool + err error +} + +// plexSignOutCmd revokes the token of a browser sign-in. A manual token was +// copied from Plex Web and belongs to that session, so it is only removed. +func plexSignOutCmd(cfg config.PlexConfig) tea.Cmd { + account := cfg.ClientID != "" && cfg.ServerID != "" + return func() tea.Msg { + if !account { + return plexSignOutDoneMsg{} + } + ctx, cancel := context.WithTimeout(context.Background(), plexSignOutTimeout) + defer cancel() + return plexSignOutDoneMsg{account: true, err: plexSignOut(ctx, cfg.Token, cfg.ClientID)} + } +} + func openBrowserCmd(rawURL string) tea.Cmd { return func() tea.Msg { _ = browser.Open(rawURL) @@ -1277,6 +1324,9 @@ func (m *setupModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.authStatus = "Finding reachable Plex servers…" return m, discoverPlexServersCmd(msg.api, msg.token, msg.clientID) + case plexSignOutDoneMsg: + return m.finishPlexSignOut(msg) + case plexAuthDoneMsg: if msg.err != nil { return m.onPlexAuthError(msg.err) @@ -1394,6 +1444,8 @@ func (m *setupModel) startProvider(idx int) { m.pickerCursor = 0 m.resultErr = nil m.resultText = "" + m.warnText = "" + m.resultNote = "" m.resultWarning = false m.awaitingSave = false m.saveFailed = nil @@ -1406,7 +1458,13 @@ func (m *setupModel) startProvider(idx int) { m.plexServers = nil m.plexServerCursor = 0 - if m.provs[idx].picker != nil { + if p := m.provs[idx].picker; p != nil { + m.pickerOpts = m.pickerOpts[:0] + for _, opt := range p.options { + if opt.show == nil || opt.show() { + m.pickerOpts = append(m.pickerOpts, opt) + } + } m.stage = stagePicker } else { m.refreshVisibleFields() @@ -1425,11 +1483,11 @@ func (m *setupModel) pickerKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) { m.pickerCursor-- } case "down", "j": - if m.pickerCursor < len(p.options)-1 { + if m.pickerCursor < len(m.pickerOpts)-1 { m.pickerCursor++ } case "enter": - m.values[p.key] = p.options[m.pickerCursor].value + m.values[p.key] = m.pickerOpts[m.pickerCursor].value // Pickers can short-circuit with no fields (e.g. ytmusic "default" / "off"). m.refreshVisibleFields() if len(m.visible) == 0 { @@ -1470,6 +1528,38 @@ func (m *setupModel) applyPlexServer(choice plexServerChoice) { m.values[keyPlexAuth] = "account" } +// finishPlexSignOut removes the saved credentials whether or not Plex +// revoked the token, so a failed revoke never leaves the token behind. The +// library filter goes too, since a new sign-in asks for it again. The +// client_id stays, so the next sign-in is the same Plex device. A browser +// sign-in also drops its server and found address. +func (m *setupModel) finishPlexSignOut(msg plexSignOutDoneMsg) (tea.Model, tea.Cmd) { + removed := []string{"token", "libraries"} + if msg.account { + removed = append(removed, "server_id", "url") + } + m.stage = stageResult + if err := config.SaveSection("plex", nil, removed); err != nil { + m.saveFailed = err + return m, nil + } + m.resultErr = nil + const restart = "Restart cliamp if it is running; it keeps the token in memory." + switch { + case !msg.account: + m.resultText = "Removed the token from [plex]." + m.resultNote = "A token copied from Plex Web stays valid there.\n" + restart + case msg.err == nil: + m.resultText = "Signed out of Plex." + m.resultNote = "Plex revoked the token, and it is removed from [plex].\n" + restart + default: + m.resultWarning = true + m.warnText = "Removed the token from [plex], but Plex did not revoke it" + m.resultNote = msg.err.Error() + "\nRemove this device under Authorized Devices in your Plex account.\n" + restart + } + return m, nil +} + func (m *setupModel) onPlexAuthError(err error) (tea.Model, tea.Cmd) { m.resultErr = err m.awaitingSave = false @@ -1794,6 +1884,19 @@ func (m *setupModel) submitForm() (tea.Model, tea.Cmd) { } } + if spec.section == "plex" && m.values[keyPlexAuth] == "signout" { + cfg, err := config.Load() + if err != nil { + m.resultErr = err + m.stage = stageResult + return m, nil + } + m.stage = stageValidating + m.spinFrame = 0 + m.authStatus = "Signing out of Plex…" + return m, tea.Batch(spinTickCmd(), plexSignOutCmd(cfg.Plex)) + } + if spec.section == "plex" && m.values[keyPlexAuth] == "account" { clientID, err := plexSetupClientID() if err != nil { @@ -2046,7 +2149,7 @@ func (m *setupModel) viewPicker() string { b.WriteString("\n") b.WriteString(accentStyle.Render(p.label)) b.WriteString("\n\n") - for i, opt := range p.options { + for i, opt := range m.pickerOpts { marker := " " text := opt.label if i == m.pickerCursor { @@ -2215,7 +2318,7 @@ func (m *setupModel) viewValidating() string { frames := []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"} frame := frames[m.spinFrame%len(frames)] message := "Verifying connection to " + m.provs[m.pidx].name + "…" - if m.provs[m.pidx].section == "plex" && m.values[keyPlexAuth] == "account" { + if m.provs[m.pidx].section == "plex" && (m.values[keyPlexAuth] == "account" || m.values[keyPlexAuth] == "signout") { message = m.authStatus if message == "" { message = "Starting Plex sign-in…" @@ -2289,11 +2392,19 @@ func (m *setupModel) viewResult() string { } if m.resultWarning { - b.WriteString(warnStyle.Render("⚠ Saved without verification")) + title := "Saved without verification" + if m.warnText != "" { + title = m.warnText + } + b.WriteString(warnStyle.Render("⚠ " + title)) } else { b.WriteString(okStyle.Render("✓ " + m.resultText)) } b.WriteString("\n\n") + if m.resultNote != "" { + b.WriteString(m.resultNote) + b.WriteString("\n\n") + } b.WriteString(dimStyle.Render(m.cfgPath)) b.WriteString("\n\n") if m.signInAction != nil { diff --git a/cmd/setup_test.go b/cmd/setup_test.go index 0b7369de6..d0afa100d 100644 --- a/cmd/setup_test.go +++ b/cmd/setup_test.go @@ -1,9 +1,11 @@ package cmd import ( + "context" "errors" "os" "path/filepath" + "slices" "strings" "testing" @@ -102,6 +104,8 @@ func TestPickerSelectionFiltersFields(t *testing.T) { } func TestPlexPickerSelectionFiltersFields(t *testing.T) { + // No saved token, so the picker offers the two sign-in modes. + t.Setenv("CLIAMP_CONFIG_DIR", t.TempDir()) m := newSetupModel() plexIdx := -1 for i, p := range m.provs { @@ -1113,3 +1117,118 @@ func TestYTMusicCustomModeIncludesOptionalCookies(t *testing.T) { checkBody(t, spec.body(values), map[string]string{"cookies_from": `"firefox"`}) } + +func plexSetupIndex(t *testing.T, m *setupModel) int { + t.Helper() + for i, p := range m.provs { + if p.section == "plex" { + return i + } + } + t.Fatal("plex spec missing") + return -1 +} + +func TestPlexPickerOffersSignInOrSignOut(t *testing.T) { + for _, tt := range []struct { + name string + config string + want bool + }{ + {name: "no config", want: false}, + {name: "signed in", config: "[plex]\nurl = \"https://plex\"\ntoken = \"t\"\n", want: true}, + {name: "signed out", config: "[plex]\nclient_id = \"c\"\nlibraries = [\"Music\"]\n", want: false}, + } { + t.Run(tt.name, func(t *testing.T) { + dir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", dir) + if tt.config != "" { + if err := os.WriteFile(filepath.Join(dir, "config.toml"), []byte(tt.config), 0o600); err != nil { + t.Fatal(err) + } + } + m := newSetupModel() + m.startProvider(plexSetupIndex(t, m)) + var got []string + for _, o := range m.pickerOpts { + got = append(got, o.value) + } + want := "account,manual" + if tt.want { + want = "signout" + } + if strings.Join(got, ",") != want { + t.Fatalf("picker options = %v, want %s", got, want) + } + }) + } +} + +func TestPlexSignOutRemovesCredentials(t *testing.T) { + const account = "[plex]\nurl = \"https://home.plex.direct:32400\"\ntoken = \"account-token\"\nclient_id = \"client-1\"\nserver_id = \"server-1\"\nlibraries = [\"Music\"]\n" + const manual = "[plex]\nurl = \"http://192.168.1.10:32400\"\ntoken = \"web-token\"\nlibraries = [\"Music\"]\n" + for _, tt := range []struct { + name string + config string + revokeErr error + wantRevoke bool + wantURL string + wantClient string + wantWarn bool + }{ + {name: "browser sign-in", config: account, wantRevoke: true, wantClient: "client-1"}, + {name: "revoke fails", config: account, revokeErr: errors.New("offline"), wantRevoke: true, wantClient: "client-1", wantWarn: true}, + {name: "manual token", config: manual, wantURL: "http://192.168.1.10:32400"}, + } { + t.Run(tt.name, func(t *testing.T) { + dir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", dir) + if err := os.WriteFile(filepath.Join(dir, "config.toml"), []byte(tt.config), 0o600); err != nil { + t.Fatal(err) + } + revoked := "" + orig := plexSignOut + plexSignOut = func(_ context.Context, token, clientID string) error { + revoked = token + "/" + clientID + return tt.revokeErr + } + t.Cleanup(func() { plexSignOut = orig }) + + m := newSetupModel() + m.startProvider(plexSetupIndex(t, m)) + m.pickerCursor = slices.IndexFunc(m.pickerOpts, func(o pickerOption) bool { return o.value == "signout" }) + _, cmd := m.handleKey(keyPress(tea.KeyEnter, "")) + if m.stage != stageValidating || cmd == nil { + t.Fatalf("stage = %v, want stageValidating; resultErr = %v", m.stage, m.resultErr) + } + for _, c := range cmd().(tea.BatchMsg) { + if msg, ok := c().(plexSignOutDoneMsg); ok { + m.Update(msg) + } + } + + if got := revoked != ""; got != tt.wantRevoke { + t.Fatalf("revoked = %q, want revoke %v", revoked, tt.wantRevoke) + } + if tt.wantRevoke && revoked != "account-token/client-1" { + t.Fatalf("revoked %q, want the saved token and client", revoked) + } + cfg, err := config.Load() + if err != nil { + t.Fatalf("Load: %v", err) + } + if cfg.Plex.Token != "" || cfg.Plex.ServerID != "" || cfg.Plex.URL != tt.wantURL || cfg.Plex.ClientID != tt.wantClient { + t.Fatalf("Plex config after sign-out = %+v", cfg.Plex) + } + if len(cfg.Plex.Libraries) != 0 { + t.Fatalf("libraries = %v, want removed", cfg.Plex.Libraries) + } + if m.stage != stageResult || m.resultWarning != tt.wantWarn || m.saveFailed != nil { + t.Fatalf("result stage=%v warning=%v saveFailed=%v", m.stage, m.resultWarning, m.saveFailed) + } + if view := m.viewResult(); !strings.Contains(view, "Restart cliamp") { + t.Fatalf("result does not mention the restart:\n%s", view) + } + }) + } +} diff --git a/docs/cli.md b/docs/cli.md index eaa364132..999fe25e8 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -163,7 +163,7 @@ CLI flags override config file values for the current session only. Persisted bo ## Setup wizard -Configure remote providers through a small TUI. Supported providers are Navidrome, Lyrion, Plex, Jellyfin, Emby, Spotify, Qobuz, Tidal, Bandcamp, Mixcloud, NetEase, Audiobookshelf, YouTube Music, and Telegram. Each provider page links to its required credentials. The wizard writes the provider keys into the `[provider]` section of `~/.config/cliamp/config.toml` and leaves the rest of the file unchanged. For YouTube Music, it edits an existing `[youtube]` or `[yt]` section. Plex supports browser sign-in, automatic server discovery, and server selection as well as manual URL-and-token setup. It checks the server connection during setup for Navidrome, Lyrion, Plex, Jellyfin, Emby, and Audiobookshelf, the Subsonic credentials for Bandcamp, and the browser session for NetEase. OAuth providers (Spotify, Qobuz, Tidal) authenticate later in the player. Setup does not check Mixcloud credentials. Telegram asks for the login code in the pane when the session is missing, or right after saving in setup. +Configure remote providers through a small TUI. Supported providers are Navidrome, Lyrion, Plex, Jellyfin, Emby, Spotify, Qobuz, Tidal, Bandcamp, Mixcloud, NetEase, Audiobookshelf, YouTube Music, and Telegram. Each provider page links to its required credentials. The wizard writes the provider keys into the `[provider]` section of `~/.config/cliamp/config.toml` and leaves the rest of the file unchanged. For YouTube Music, it edits an existing `[youtube]` or `[yt]` section. Plex supports browser sign-in, automatic server discovery, and server selection as well as manual URL-and-token setup, and sign-out, which revokes a browser sign-in token and removes the saved credentials. It checks the server connection during setup for Navidrome, Lyrion, Plex, Jellyfin, Emby, and Audiobookshelf, the Subsonic credentials for Bandcamp, and the browser session for NetEase. OAuth providers (Spotify, Qobuz, Tidal) authenticate later in the player. Setup does not check Mixcloud credentials. Telegram asks for the login code in the pane when the session is missing, or right after saving in setup. ```sh cliamp setup diff --git a/docs/plex.md b/docs/plex.md index 13c36aa22..26248e525 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -32,6 +32,24 @@ This means the same configuration can move between home and work without hard-coding a `192.168.x.x` address. Remote playback still requires the Plex server to advertise a reachable remote or relay connection. +## Sign out + +Run `cliamp setup`, select **Plex Media Server**, and choose **Sign out and +remove saved credentials**. While `[plex]` holds a token, this is the only +option: to change the server or the login type, sign out and sign in again. + +- After a browser sign-in, cliamp asks Plex to revoke the token, checks that + Plex no longer accepts it, and removes `token`, `server_id`, `url`, and + `libraries` from `[plex]`. +- A manual token was copied from Plex Web and belongs to that session, so + cliamp does not revoke it. It removes `token` and `libraries` and keeps the + server URL. + +`client_id` stays, so a later sign-in is the same Plex device. If Plex cannot be reached or still accepts the +token, cliamp removes it anyway and asks you to remove the device under +**Authorized Devices** in your Plex account. Restart a running cliamp, which +keeps the token in memory. + ## Manual token setup To configure a fixed server URL instead, select the manual option in setup or diff --git a/external/plex/account.go b/external/plex/account.go index 02ef0afde..aa7c459c5 100644 --- a/external/plex/account.go +++ b/external/plex/account.go @@ -4,6 +4,7 @@ import ( "context" "crypto/rand" "encoding/hex" + "errors" "fmt" "io" "net/http" @@ -361,6 +362,55 @@ func (a *AccountAPI) probe(ctx context.Context, baseURL, token, clientID string) return nil } +// ErrTokenStillAccepted reports that plex.tv still accepts a token after the +// sign-out request, so the token is not known to be revoked. +var ErrTokenStillAccepted = errors.New("plex: plex.tv still accepts the token after sign-out") + +// SignOut revokes accountToken at plex.tv and then checks that plex.tv +// rejects it. Only a token that cliamp obtained through browser sign-in may +// be revoked: a token copied from Plex Web belongs to that browser session. +func (a *AccountAPI) SignOut(ctx context.Context, accountToken, clientID string) error { + if strings.TrimSpace(accountToken) == "" { + return fmt.Errorf("plex: sign out: no token") + } + status, err := a.do(ctx, http.MethodDelete, "/api/v2/users/signout", clientID, accountToken) + if err != nil { + return fmt.Errorf("plex: sign out: %w", err) + } + // 401 means the token was already invalid, which is the goal. + if (status < 200 || status >= 300) && status != http.StatusUnauthorized { + return fmt.Errorf("plex: sign out: HTTP %d", status) + } + status, err = a.do(ctx, http.MethodGet, "/api/v2/user", clientID, accountToken) + if err != nil { + return fmt.Errorf("plex: check sign-out: %w", err) + } + switch { + case status == http.StatusUnauthorized: + return nil + case status >= 200 && status < 300: + return ErrTokenStillAccepted + } + return fmt.Errorf("plex: check sign-out: HTTP %d", status) +} + +// do sends a request without a body and returns the response status. The +// response body is drained and discarded. +func (a *AccountAPI) do(ctx context.Context, method, path, clientID, token string) (int, error) { + req, err := http.NewRequestWithContext(ctx, method, a.baseURL+path, nil) + if err != nil { + return 0, err + } + setAccountHeaders(req, clientID, token) + resp, err := a.client.Do(req) + if err != nil { + return 0, err + } + defer resp.Body.Close() + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxResponseBody)) + return resp.StatusCode, nil +} + func (a *AccountAPI) doJSON(ctx context.Context, method, path, clientID, token string, result any) error { req, err := http.NewRequestWithContext(ctx, method, a.baseURL+path, nil) if err != nil { diff --git a/external/plex/account_test.go b/external/plex/account_test.go index 47c5360b5..1190cb8f9 100644 --- a/external/plex/account_test.go +++ b/external/plex/account_test.go @@ -3,6 +3,7 @@ package plex import ( "context" "encoding/json" + "errors" "net/http" "net/http/httptest" "strings" @@ -207,3 +208,62 @@ func TestNewClientIdentifier(t *testing.T) { t.Fatalf("identifiers = %q, %q", a, b) } } + +func TestAccountSignOut(t *testing.T) { + tests := []struct { + name string + signout int + user int + wantErr bool + wantStill bool + wantChecks int + }{ + {name: "revoked", signout: http.StatusNoContent, user: http.StatusUnauthorized, wantChecks: 1}, + {name: "already invalid", signout: http.StatusUnauthorized, user: http.StatusUnauthorized, wantChecks: 1}, + {name: "still accepted", signout: http.StatusNoContent, user: http.StatusOK, wantErr: true, wantStill: true, wantChecks: 1}, + {name: "sign-out rejected", signout: http.StatusInternalServerError, wantErr: true}, + {name: "check fails", signout: http.StatusNoContent, user: http.StatusBadGateway, wantErr: true, wantChecks: 1}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + checks := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("X-Plex-Token"); got != "account-token" { + t.Errorf("token = %q", got) + } + if got := r.Header.Get("X-Plex-Client-Identifier"); got != "client-1" { + t.Errorf("client identifier = %q", got) + } + switch { + case r.Method == http.MethodDelete && r.URL.Path == "/api/v2/users/signout": + w.WriteHeader(tt.signout) + case r.Method == http.MethodGet && r.URL.Path == "/api/v2/user": + checks++ + w.WriteHeader(tt.user) + default: + t.Fatalf("unexpected request: %s %s", r.Method, r.URL) + } + })) + defer srv.Close() + api := &AccountAPI{baseURL: srv.URL, client: srv.Client(), pollInterval: time.Millisecond} + + err := api.SignOut(context.Background(), "account-token", "client-1") + if (err != nil) != tt.wantErr { + t.Fatalf("SignOut error = %v, want error %v", err, tt.wantErr) + } + if got := errors.Is(err, ErrTokenStillAccepted); got != tt.wantStill { + t.Fatalf("still accepted = %v, want %v (%v)", got, tt.wantStill, err) + } + if checks != tt.wantChecks { + t.Fatalf("token checks = %d, want %d", checks, tt.wantChecks) + } + }) + } +} + +func TestAccountSignOutNeedsToken(t *testing.T) { + api := &AccountAPI{baseURL: "unused", client: http.DefaultClient} + if err := api.SignOut(context.Background(), " ", "client-1"); err == nil { + t.Fatal("SignOut accepted an empty token") + } +} diff --git a/site/index.html b/site/index.html index 5a804ad50..936375a40 100644 --- a/site/index.html +++ b/site/index.html @@ -659,7 +659,7 @@

Close the tab. Play the music.

{name:"Telegram",kind:"streaming",note:"MTProto · phone login"}, {name:"Bandcamp",kind:"streaming",note:"your purchases · Subsonic API"}, {name:"Bilibili",kind:"streaming",note:"video audio · yt-dlp"}, - {name:"Plex",kind:"self-hosted",note:"browser login · server-side likes · remote discovery · resume"}, + {name:"Plex",kind:"self-hosted",note:"browser login and sign-out · server-side likes · remote discovery · resume"}, {name:"Jellyfin",kind:"self-hosted",note:"API key / password, gapless, resume"}, {name:"Emby",kind:"self-hosted",note:"API key / password, resume"}, {name:"Navidrome",kind:"self-hosted",note:"Subsonic API · lyrics"}, From c030dee537b39b94af02fb241483364982ffa6c4 Mon Sep 17 00:00:00 2001 From: Igor Maliavko Date: Tue, 27 Oct 2026 11:35:32 +0100 Subject: [PATCH 10/32] fix(plex): keep timeline position within duration Plex sometimes rejected progress reports with HTTP 400. Track durations are whole seconds (milliseconds / 1000, truncated) while the reported position has milliseconds, so in a track's last second the position passed the duration; the failing tracks all had a large fraction, such as 202945 ms known as 202 s. ReportTimeline now caps the position at a known duration. Verified with make check (gofmt, go vet, go test ./...), and against the real Plex durations of the three tracks in cliamp.log. Co-Authored-By: Claude Opus 5.5 --- external/plex/client.go | 6 ++++ external/plex/client_test.go | 57 +++++++++++++++++++++++------------- 2 files changed, 42 insertions(+), 21 deletions(-) diff --git a/external/plex/client.go b/external/plex/client.go index 4c8a09b70..03b7aeff1 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -192,6 +192,12 @@ func (c *Client) ReportTimeline(ctx context.Context, ratingKey, state string, po if ratingKey == "" { return fmt.Errorf("plex: timeline: missing rating key") } + // Track durations are whole seconds while the position has milliseconds, + // so in a track's last second the position can pass the duration. Plex + // rejects such a timeline with 400 Bad Request. + if duration > 0 { + position = min(position, duration) + } params := url.Values{ "key": {"/library/metadata/" + ratingKey}, "ratingKey": {ratingKey}, diff --git a/external/plex/client_test.go b/external/plex/client_test.go index 605fcd6fd..e965eccd3 100644 --- a/external/plex/client_test.go +++ b/external/plex/client_test.go @@ -43,28 +43,43 @@ func TestSetRating(t *testing.T) { } func TestReportTimeline(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost || r.URL.Path != "/:/timeline" { - t.Fatalf("request = %s %s, want POST /:/timeline", r.Method, r.URL.Path) - } - want := map[string]string{ - "key": "/library/metadata/track-42", - "ratingKey": "track-42", - "state": "playing", - "time": "1234", - "duration": "180000", - } - for key, value := range want { - if got := r.URL.Query().Get(key); got != value { - t.Errorf("%s = %q, want %q", key, got, value) - } - } - w.WriteHeader(http.StatusOK) - })) - defer srv.Close() + tests := []struct { + name string + position, duration time.Duration + wantTime, wantDur string + }{ + {name: "within track", position: 1234 * time.Millisecond, duration: 3 * time.Minute, wantTime: "1234", wantDur: "180000"}, + // A 202.945 s track is known as 202 s; its last second must not pass the end. + {name: "past whole-second duration", position: 202500 * time.Millisecond, duration: 202 * time.Second, wantTime: "202000", wantDur: "202000"}, + {name: "unknown duration", position: 5 * time.Second, wantTime: "5000", wantDur: "0"}, + {name: "negative position", position: -time.Second, duration: time.Minute, wantTime: "0", wantDur: "60000"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/:/timeline" { + t.Fatalf("request = %s %s, want POST /:/timeline", r.Method, r.URL.Path) + } + want := map[string]string{ + "key": "/library/metadata/track-42", + "ratingKey": "track-42", + "state": "playing", + "time": tt.wantTime, + "duration": tt.wantDur, + } + for key, value := range want { + if got := r.URL.Query().Get(key); got != value { + t.Errorf("%s = %q, want %q", key, got, value) + } + } + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() - if err := newTestClient(srv).ReportTimeline(t.Context(), "track-42", "playing", 1234*time.Millisecond, 3*time.Minute); err != nil { - t.Fatalf("ReportTimeline: %v", err) + if err := newTestClient(srv).ReportTimeline(t.Context(), "track-42", "playing", tt.position, tt.duration); err != nil { + t.Fatalf("ReportTimeline: %v", err) + } + }) } } From 13dea8229df5bc9f4cdad75f443358b444e7daf5 Mon Sep 17 00:00:00 2001 From: Igor Maliavko Date: Tue, 27 Oct 2026 13:59:56 +0100 Subject: [PATCH 11/32] feat(plex): play library radio stations Plex library radio (Library Radio, Random Album Radio and the others Plexamp offers) was not reachable from cliamp. The Plex browser now lists the stations of the selected libraries in a Radio section above the playlists. Enter starts a server play queue and loads 30 tracks; when the last loaded track starts, the next 30 of the same queue are appended through the new provider.QueueContinuer, so a station plays on without end. Ctrl+R on the open station starts a fresh queue. The [plex] stations setting picks and orders stations by name; it is unset by default (all stations) and [] hides the section. A section whose stations cannot be read is skipped. Verified with make check (gofmt, go vet, go test ./...) and by playing Random Album Radio past the first batch. Co-Authored-By: Claude Opus 5.5 --- config.toml.example | 6 + config/config.go | 5 + config/config_golden_test.go | 1 + config/config_test.go | 30 ++++ docs/plex.md | 17 ++- external/plex/client.go | 139 ++++++++++++++++++- external/plex/provider.go | 125 ++++++++++++++++- external/plex/provider_test.go | 235 ++++++++++++++++++++++++++++++++ provider/interfaces.go | 10 ++ site/index.html | 2 +- ui/model/playback.go | 2 +- ui/model/queue_continue.go | 54 ++++++++ ui/model/queue_continue_test.go | 78 +++++++++++ ui/model/update.go | 4 + 14 files changed, 701 insertions(+), 7 deletions(-) create mode 100644 ui/model/queue_continue.go create mode 100644 ui/model/queue_continue_test.go diff --git a/config.toml.example b/config.toml.example index a493ba05d..90818e707 100644 --- a/config.toml.example +++ b/config.toml.example @@ -314,6 +314,12 @@ eq = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # Restrict to specific music libraries (comma-separated, case-insensitive). # When omitted or empty, all music libraries are loaded. # libraries = ["Music", "Jazz"] +# +# Library radio stations shown in the Radio section of the Plex browser, by +# name and in this order. When omitted, every station the server offers is +# shown (Library Radio, Deep Cuts Radio, Time Travel Radio, Random Album +# Radio); an empty list hides the section. +# stations = ["Library Radio", "Random Album Radio"] # --- # Jellyfin server (optional) diff --git a/config/config.go b/config/config.go index d74fa8544..451013a1e 100644 --- a/config/config.go +++ b/config/config.go @@ -673,6 +673,9 @@ type PlexConfig struct { ClientID string // stable identifier of this cliamp installation ServerID string // selected Plex Media Server clientIdentifier Libraries []string // optional: restrict to these music library names + // Stations picks and orders the library radio stations shown in the + // browser by name. Nil shows every station; an empty list hides them. + Stations []string } // IsSet reports whether a manual URL or an account-discovery server is @@ -694,6 +697,8 @@ func (p *PlexConfig) set(key, val string) { p.ServerID = parseString(val) case "libraries": p.Libraries = parseStringSlice(val) + case "stations": + p.Stations = parseStringSlice(val) } } diff --git a/config/config_golden_test.go b/config/config_golden_test.go index 705f4721f..aeaab4f78 100644 --- a/config/config_golden_test.go +++ b/config/config_golden_test.go @@ -385,6 +385,7 @@ func TestLoadGolden(t *testing.T) { ClientID: "generated-per-installation-id", ServerID: "selected-server-id", Libraries: []string{"Music", "Jazz"}, + Stations: []string{"Library Radio", "Random Album Radio"}, } allWant.Jellyfin = JellyfinConfig{ URL: "https://jellyfin.example.com", diff --git a/config/config_test.go b/config/config_test.go index 7e7562943..95ea2975f 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -1124,3 +1124,33 @@ func TestLoadPluginKeysThatCliampReads(t *testing.T) { }) } } + +// A missing stations key shows every Plex station; an empty list hides them. +func TestPlexStationsSetting(t *testing.T) { + tests := []struct { + name string + section string + want []string + wantNil bool + }{ + {name: "missing", section: "[plex]\nurl = \"http://plex\"\ntoken = \"t\"\n", wantNil: true}, + {name: "empty", section: "[plex]\nstations = []\n", want: []string{}}, + {name: "picked", section: "[plex]\nstations = [\"Library Radio\", \"Random Album Radio\"]\n", want: []string{"Library Radio", "Random Album Radio"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", dir) + if err := os.WriteFile(filepath.Join(dir, "config.toml"), []byte(tt.section), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := Load() + if err != nil { + t.Fatalf("Load: %v", err) + } + if got := cfg.Plex.Stations; (got == nil) != tt.wantNil || (!tt.wantNil && !slices.Equal(got, tt.want)) { + t.Fatalf("stations = %#v, want %#v (nil %v)", got, tt.want, tt.wantNil) + } + }) + } +} diff --git a/docs/plex.md b/docs/plex.md index 26248e525..a6d9f2a67 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -73,6 +73,7 @@ token = "xxxxxxxxxxxxxxxxxxxx" client_id = "generated-per-installation-id" server_id = "selected-server-id" libraries = ["Music", "Jazz"] +stations = ["Library Radio", "Random Album Radio"] ``` | Key | Description | @@ -82,6 +83,7 @@ libraries = ["Music", "Jazz"] | `client_id` | Stable cliamp installation ID written by browser sign-in | | `server_id` | Selected Plex Media Server ID written by browser sign-in | | `libraries` | Optional comma-separated music library names to load. If omitted, cliamp loads all music libraries. Name matching is case-insensitive. | +| `stations` | Optional library radio stations to show under **Radio**, by name and in this order. Stations come from the libraries that `libraries` selects. If omitted, every station of those libraries is shown; `[]` hides the section. Name matching is case-insensitive. | `client_id` and `server_id` enable account discovery. Omit both for a fixed manual URL. Do not copy them between installations; rerun browser sign-in on @@ -91,9 +93,16 @@ the other computer so Plex lists it as a separate authorized device. After configuration, **Plex** appears in the cliamp provider list. -The provider shows audio playlists and the music library under two headers: +The provider shows the library radio stations, audio playlists, and the music +library under three headers: ```text +── Radio ── +Library Radio +Deep Cuts Radio +Time Travel Radio +Random Album Radio + ── Playlists ── GOOD All Music @@ -105,6 +114,12 @@ Artist - Album Title (Year) Select a playlist or album to load its tracks. Smart playlists are included. They resolve to current server content. +Selecting a station asks the server for a new play queue, as Plexamp does, and +loads it 30 tracks at a time: when the last loaded track starts, the next 30 +of the same queue are appended, so the station plays on without end. Press +`Ctrl+R` while the station is open for a fresh selection. The `stations` +setting picks which stations appear. + Press `Ctrl+R` while an open Plex album or playlist is focused to reload it and pick up server-side changes. Album contents are cached for up to five minutes; Plex playlists are always loaded fresh so smart playlists stay current. diff --git a/external/plex/client.go b/external/plex/client.go index 03b7aeff1..9aa57e125 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -31,6 +31,7 @@ type Client struct { clientID string // stable device identity sent with Plex requests libraries []string // if non-empty, MusicSections filters to these titles (case-insensitive) account *accountBinding + machineID string // server identifier for play queue URIs, read once } type accountBinding struct { @@ -124,6 +125,13 @@ type Track struct { UserRating float64 } +// Station is a radio station of a Plex music library, such as Library Radio +// or Random Album Radio. Playing one asks the server for a play queue. +type Station struct { + Key string // e.g. "/library/sections/3/stations/1" + Title string +} + // Playlist represents a Plex playlist (smart or user-created) of audio tracks. type Playlist struct { RatingKey string @@ -135,6 +143,12 @@ type Playlist struct { // get issues an authenticated GET request and decodes the JSON response into result. func (c *Client) get(path string, params url.Values, result any) error { + return c.request(http.MethodGet, path, params, result) +} + +// request issues an authenticated request and decodes the JSON response into +// result. +func (c *Client) request(method, path string, params url.Values, result any) error { baseURL, token, err := c.endpoint(context.Background()) if err != nil { return fmt.Errorf("plex: connect account server: %w", err) @@ -144,7 +158,7 @@ func (c *Client) get(path string, params url.Values, result any) error { } params.Set("X-Plex-Token", token) - req, err := http.NewRequest(http.MethodGet, baseURL+path+"?"+params.Encode(), nil) + req, err := http.NewRequest(method, baseURL+path+"?"+params.Encode(), nil) if err != nil { return fmt.Errorf("plex: %s: %w", path, err) } @@ -593,3 +607,126 @@ func trackFromJSON(m trackJSON) Track { UserRating: m.UserRating, } } + +// Stations returns the radio stations of a music section from its hubs. +func (c *Client) Stations(sectionKey string) ([]Station, error) { + var result struct { + MediaContainer struct { + Hub []struct { + Type string `json:"type"` + Metadata []struct { + Key string `json:"key"` + Title string `json:"title"` + } `json:"Metadata"` + } `json:"Hub"` + } `json:"MediaContainer"` + } + params := url.Values{"count": {"20"}, "includeStations": {"1"}} + if err := c.get("/hubs/sections/"+sectionKey, params, &result); err != nil { + return nil, fmt.Errorf("plex: section %s stations: %w", sectionKey, err) + } + var stations []Station + for _, hub := range result.MediaContainer.Hub { + if hub.Type != "station" { + continue + } + for _, m := range hub.Metadata { + if m.Key != "" && m.Title != "" { + stations = append(stations, Station{Key: m.Key, Title: m.Title}) + } + } + } + return stations, nil +} + +// PlayQueuePage is one window of a server play queue. LastItemID is the +// playQueueItemID of the last track, where the next window starts. +type PlayQueuePage struct { + QueueID int + LastItemID int + Tracks []Track +} + +// StationTracks starts a play queue for the station at stationKey and returns +// its first limit tracks. Each call starts a new queue, so it returns a fresh +// selection; QueueTracksAfter continues it. +func (c *Client) StationTracks(stationKey string, limit int) (PlayQueuePage, error) { + machineID, err := c.machineIdentifier() + if err != nil { + return PlayQueuePage{}, err + } + var created struct { + MediaContainer struct { + PlayQueueID int `json:"playQueueID"` + } `json:"MediaContainer"` + } + params := url.Values{ + "type": {"audio"}, + "uri": {"server://" + machineID + "/com.plexapp.plugins.library" + stationKey}, + } + if err := c.request(http.MethodPost, "/playQueues", params, &created); err != nil { + return PlayQueuePage{}, fmt.Errorf("plex: start station: %w", err) + } + if created.MediaContainer.PlayQueueID == 0 { + return PlayQueuePage{}, fmt.Errorf("plex: start station: no play queue") + } + // The window counts the selected first item as well. + return c.playQueuePage(created.MediaContainer.PlayQueueID, url.Values{"window": {strconv.Itoa(limit - 1)}}) +} + +// QueueTracksAfter returns up to limit tracks of a play queue after the item +// afterItemID. An empty page means the queue has ended. +func (c *Client) QueueTracksAfter(queueID, afterItemID, limit int) (PlayQueuePage, error) { + return c.playQueuePage(queueID, url.Values{ + "window": {strconv.Itoa(limit)}, + "center": {strconv.Itoa(afterItemID)}, + "includeBefore": {"0"}, + "includeAfter": {"1"}, + }) +} + +func (c *Client) playQueuePage(queueID int, params url.Values) (PlayQueuePage, error) { + var queue struct { + MediaContainer struct { + Metadata []struct { + trackJSON + PlayQueueItemID int `json:"playQueueItemID"` + } `json:"Metadata"` + } `json:"MediaContainer"` + } + if err := c.get("/playQueues/"+strconv.Itoa(queueID), params, &queue); err != nil { + return PlayQueuePage{}, fmt.Errorf("plex: play queue: %w", err) + } + page := PlayQueuePage{QueueID: queueID} + for _, m := range queue.MediaContainer.Metadata { + page.Tracks = append(page.Tracks, trackFromJSON(m.trackJSON)) + page.LastItemID = m.PlayQueueItemID + } + return page, nil +} + +// machineIdentifier returns the server's identifier, which play queue URIs +// name. It is read once from /identity. +func (c *Client) machineIdentifier() (string, error) { + c.mu.Lock() + id := c.machineID + c.mu.Unlock() + if id != "" { + return id, nil + } + var result struct { + MediaContainer struct { + MachineIdentifier string `json:"machineIdentifier"` + } `json:"MediaContainer"` + } + if err := c.get("/identity", nil, &result); err != nil { + return "", fmt.Errorf("plex: server identity: %w", err) + } + if result.MediaContainer.MachineIdentifier == "" { + return "", fmt.Errorf("plex: server identity: no machine identifier") + } + c.mu.Lock() + c.machineID = result.MediaContainer.MachineIdentifier + c.mu.Unlock() + return result.MediaContainer.MachineIdentifier, nil +} diff --git a/external/plex/provider.go b/external/plex/provider.go index 1bfcfd5b6..12a1954f1 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -9,6 +9,7 @@ import ( "sync" "time" + "github.com/bjarneo/cliamp/applog" "github.com/bjarneo/cliamp/config" "github.com/bjarneo/cliamp/playlist" "github.com/bjarneo/cliamp/provider" @@ -22,9 +23,16 @@ const ( // favorites, playlists, resume state, and IPC responses. TrackURIPrefix = "plex:track:" prefixPlaylist = "pl:" + prefixStation = "st:" sectionAlbums = "Albums" sectionPlaylists = "Playlists" - albumCacheTTL = 5 * time.Minute + sectionRadio = "Radio" + + // stationBatch is how many tracks a station loads at a time. When the + // last one starts, the next batch is appended; Ctrl+R on the open + // station starts it again for a fresh selection. + stationBatch = 30 + albumCacheTTL = 5 * time.Minute ) type trackCacheEntry struct { @@ -40,6 +48,7 @@ var ( _ provider.TrackFavoriter = (*Provider)(nil) _ provider.TrackFavoriteState = (*Provider)(nil) _ provider.ProgressReporter = (*Provider)(nil) + _ provider.QueueContinuer = (*Provider)(nil) ) // Provider implements playlist.Provider for a Plex Media Server. @@ -54,9 +63,19 @@ type Provider struct { trackCache map[string]trackCacheEntry partKeys map[string]string favorites map[string]bool + stations []string // [plex] stations: nil shows all, empty hides all + // stationQueues maps the path of the last track of each station batch + // to the server play queue that continues after it. + stationQueues map[string]stationQueue now func() time.Time } +// stationQueue is where a station's server play queue continues. +type stationQueue struct { + queueID int + lastItemID int +} + // newProvider returns a Provider backed by the given Client. func newProvider(client *Client) *Provider { return &Provider{client: client, now: time.Now} @@ -67,10 +86,14 @@ func NewFromConfig(cfg config.PlexConfig) *Provider { if !cfg.IsSet() { return nil } + var p *Provider if cfg.ClientID != "" && cfg.ServerID != "" { - return newProvider(NewAccountClient(cfg.URL, cfg.Token, cfg.ClientID, cfg.ServerID, cfg.Libraries...)) + p = newProvider(NewAccountClient(cfg.URL, cfg.Token, cfg.ClientID, cfg.ServerID, cfg.Libraries...)) + } else { + p = newProvider(NewClient(cfg.URL, cfg.Token, cfg.Libraries...)) } - return newProvider(NewClient(cfg.URL, cfg.Token, cfg.Libraries...)) + p.stations = cfg.Stations + return p } // Name returns the display name used in the provider selector. @@ -109,6 +132,7 @@ func (p *Provider) Playlists() ([]playlist.PlaylistInfo, error) { if err != nil { return nil, err } + lists = append(p.stationLists(sections), lists...) for _, sec := range sections { albums, err := p.client.Albums(sec.Key) if err != nil { @@ -167,6 +191,14 @@ func (p *Provider) CanRefreshPlaylist(id string) bool { // intentionally not cached so smart playlists always reflect current server // contents. func (p *Provider) Tracks(playlistID string) ([]playlist.Track, error) { + if key, ok := strings.CutPrefix(playlistID, prefixStation); ok { + // A station is a new play queue each time, never a cached list. + page, err := p.client.StationTracks(key, stationBatch) + if err != nil { + return nil, err + } + return p.stationBatchTracks(page), nil + } isPlaylist := strings.HasPrefix(playlistID, prefixPlaylist) p.mu.Lock() @@ -366,6 +398,93 @@ func (p *Provider) RestoreTrack(track playlist.Track) (playlist.Track, bool) { return track, true } +// stationBatchTracks converts one station batch and remembers that its last +// track continues the server play queue. +func (p *Provider) stationBatchTracks(page PlayQueuePage) []playlist.Track { + tracks := p.convertTracks(page.Tracks, 0) + if len(tracks) == 0 || page.LastItemID == 0 { + return tracks + } + p.mu.Lock() + if p.stationQueues == nil { + p.stationQueues = make(map[string]stationQueue) + } + p.stationQueues[tracks[len(tracks)-1].Path] = stationQueue{queueID: page.QueueID, lastItemID: page.LastItemID} + p.mu.Unlock() + return tracks +} + +// CanContinueAfter reports whether track ends a station batch. It does no I/O. +func (p *Provider) CanContinueAfter(track playlist.Track) bool { + p.mu.Lock() + defer p.mu.Unlock() + _, ok := p.stationQueues[track.Path] + return ok +} + +// ContinueAfter returns the next station batch after track, the last track +// of the batch before. No tracks means the station's queue has ended. +func (p *Provider) ContinueAfter(track playlist.Track) ([]playlist.Track, error) { + p.mu.Lock() + queue, ok := p.stationQueues[track.Path] + delete(p.stationQueues, track.Path) + p.mu.Unlock() + if !ok { + return nil, nil + } + page, err := p.client.QueueTracksAfter(queue.queueID, queue.lastItemID, stationBatch) + if err != nil { + // Keep the queue so a later start of the same track can retry. + p.mu.Lock() + if p.stationQueues == nil { + p.stationQueues = make(map[string]stationQueue) + } + p.stationQueues[track.Path] = queue + p.mu.Unlock() + return nil, err + } + return p.stationBatchTracks(page), nil +} + +// stationLists returns the radio stations of the music sections as browser +// entries, picked and ordered by the stations setting. A section whose +// stations cannot be read is skipped: stations are an extra, not the library. +func (p *Provider) stationLists(sections []Section) []playlist.PlaylistInfo { + if p.stations != nil && len(p.stations) == 0 { + return nil + } + var lists []playlist.PlaylistInfo + titles := make(map[string]string) // station ID -> title without the library + for _, sec := range sections { + stations, err := p.client.Stations(sec.Key) + if err != nil { + applog.Warn("plex: %v", err) + continue + } + for _, st := range stations { + name := st.Title + if len(sections) > 1 { + name += " · " + sec.Title + } + id := prefixStation + st.Key + lists = append(lists, playlist.PlaylistInfo{ID: id, Name: name, Section: sectionRadio}) + titles[id] = st.Title + } + } + if p.stations == nil { + return lists + } + var picked []playlist.PlaylistInfo + for _, want := range p.stations { + for _, l := range lists { + if strings.EqualFold(titles[l.ID], want) { + picked = append(picked, l) + } + } + } + return picked +} + func plexTrackID(track playlist.Track) string { if id := track.Meta(provider.MetaPlexID); id != "" { return id diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index b13c51c5f..c3efe548a 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -5,6 +5,8 @@ import ( "fmt" "net/http" "net/http/httptest" + "slices" + "strconv" "strings" "testing" "time" @@ -78,6 +80,8 @@ func sectionsHandler(t *testing.T) http.HandlerFunc { ] } }`)) + case strings.HasPrefix(r.URL.Path, "/hubs/sections/"): + w.Write([]byte(`{"MediaContainer":{"Hub":[]}}`)) default: t.Errorf("unexpected path: %s", r.URL.Path) w.WriteHeader(http.StatusNotFound) @@ -679,3 +683,234 @@ func TestProviderRestoreTrack(t *testing.T) { }) } } + +// stationServer serves one music section with four stations, the machine +// identity, and play queues. It counts the play queues started. +func stationServer(t *testing.T, hubStatus int) (*httptest.Server, *int) { + t.Helper() + queues := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.URL.Path == "/playlists": + w.Write([]byte(`{"MediaContainer":{"Metadata":[]}}`)) + case r.URL.Path == "/library/sections": + w.Write([]byte(`{"MediaContainer":{"Directory":[{"key":"3","type":"artist","title":"Music"}]}}`)) + case r.URL.Path == "/library/sections/3/all": + w.Write([]byte(`{"MediaContainer":{"totalSize":1,"Metadata":[{"ratingKey":"1","title":"Album","parentTitle":"Artist","leafCount":1}]}}`)) + case r.URL.Path == "/hubs/sections/3": + if hubStatus != http.StatusOK { + w.WriteHeader(hubStatus) + return + } + w.Write([]byte(`{"MediaContainer":{"Hub":[ + {"type":"album","Metadata":[{"key":"/library/metadata/1","title":"Album"}]}, + {"type":"station","Metadata":[ + {"key":"/library/sections/3/stations/1","title":"Library Radio"}, + {"key":"/library/sections/3/stations/8","title":"Deep Cuts Radio"}, + {"key":"/library/sections/3/stations/2","title":"Time Travel Radio"}, + {"key":"/library/sections/3/stations/3","title":"Random Album Radio"} + ]} + ]}}`)) + case r.URL.Path == "/identity": + w.Write([]byte(`{"MediaContainer":{"machineIdentifier":"machine-1"}}`)) + case r.Method == http.MethodPost && r.URL.Path == "/playQueues": + if got, want := r.URL.Query().Get("uri"), "server://machine-1/com.plexapp.plugins.library/library/sections/3/stations/3"; got != want { + t.Errorf("play queue uri = %q, want %q", got, want) + } + if got := r.URL.Query().Get("type"); got != "audio" { + t.Errorf("play queue type = %q", got) + } + queues++ + fmt.Fprintf(w, `{"MediaContainer":{"playQueueID":%d}}`, 3300+queues) + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/playQueues/"): + q := r.URL.Query() + // The first window also returns the selected item; a + // continuation window starts after its center. + wantWindow, item := strconv.Itoa(stationBatch-1), 100*queues + if center := q.Get("center"); center != "" { + if q.Get("includeBefore") != "0" { + t.Errorf("continuation includeBefore = %q, want 0", q.Get("includeBefore")) + } + wantWindow = strconv.Itoa(stationBatch) + item, _ = strconv.Atoi(center) + item++ + } + if got := q.Get("window"); got != wantWindow { + t.Errorf("window = %q, want %s", got, wantWindow) + } + fmt.Fprintf(w, `{"MediaContainer":{"Metadata":[ + {"ratingKey":"7%d","title":"Song","grandparentTitle":"Band","duration":1000,"playQueueItemID":%d,"Media":[{"Part":[{"key":"/library/parts/7/file.flac"}]}]} + ]}}`, item, item) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(srv.Close) + return srv, &queues +} + +func TestProviderStationLists(t *testing.T) { + tests := []struct { + name string + stations []string + hubStatus int + want []string + }{ + {name: "all by default", hubStatus: http.StatusOK, + want: []string{"Library Radio", "Deep Cuts Radio", "Time Travel Radio", "Random Album Radio"}}, + {name: "picked in setting order", stations: []string{"random album radio", "Library Radio", "Missing"}, hubStatus: http.StatusOK, + want: []string{"Random Album Radio", "Library Radio"}}, + {name: "hidden", stations: []string{}, hubStatus: http.StatusOK}, + {name: "hub error keeps the library", hubStatus: http.StatusInternalServerError}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + srv, _ := stationServer(t, tt.hubStatus) + p := newProvider(NewClient(srv.URL, "tok")) + p.stations = tt.stations + lists, err := p.Playlists() + if err != nil { + t.Fatalf("Playlists: %v", err) + } + var got []string + for _, l := range lists { + if l.Section == sectionRadio { + if !strings.HasPrefix(l.ID, prefixStation) { + t.Errorf("station ID %q lacks the prefix", l.ID) + } + got = append(got, l.Name) + } + } + if !slices.Equal(got, tt.want) { + t.Fatalf("stations = %v, want %v", got, tt.want) + } + if lists[len(lists)-1].ID != "1" { + t.Fatalf("album missing after stations: %v", lists) + } + if len(got) > 0 && lists[0].Section != sectionRadio { + t.Fatalf("stations are not first: %v", lists) + } + }) + } +} + +func TestProviderStationTracksStartFreshQueues(t *testing.T) { + srv, queues := stationServer(t, http.StatusOK) + p := newProvider(NewClient(srv.URL, "tok")) + id := prefixStation + "/library/sections/3/stations/3" + + first, err := p.Tracks(id) + if err != nil { + t.Fatalf("Tracks: %v", err) + } + second, err := p.Tracks(id) + if err != nil { + t.Fatalf("second Tracks: %v", err) + } + if *queues != 2 { + t.Fatalf("play queues started = %d, want 2 (stations are never cached)", *queues) + } + if len(first) != 1 || first[0].Path != TrackURIPrefix+"7100" || second[0].Path != TrackURIPrefix+"7200" { + t.Fatalf("station tracks = %+v then %+v", first, second) + } +} + +// Stations come only from the libraries the libraries setting selects, and +// carry the library name only when more than one library is shown. +func TestProviderStationsFollowLibraries(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.URL.Path == "/playlists": + w.Write([]byte(`{"MediaContainer":{"Metadata":[]}}`)) + case r.URL.Path == "/library/sections": + w.Write([]byte(`{"MediaContainer":{"Directory":[ + {"key":"3","type":"artist","title":"Music"}, + {"key":"4","type":"artist","title":"Jazz"} + ]}}`)) + case strings.HasSuffix(r.URL.Path, "/all"): + w.Write([]byte(`{"MediaContainer":{"totalSize":1,"Metadata":[{"ratingKey":"1","title":"Album","parentTitle":"Artist","leafCount":1}]}}`)) + case r.URL.Path == "/hubs/sections/3" || r.URL.Path == "/hubs/sections/4": + key := strings.TrimPrefix(r.URL.Path, "/hubs/sections/") + fmt.Fprintf(w, `{"MediaContainer":{"Hub":[{"type":"station","Metadata":[ + {"key":"/library/sections/%s/stations/1","title":"Library Radio"} + ]}]}}`, key) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + + tests := []struct { + name string + libraries []string + want []string + }{ + {name: "one selected library", libraries: []string{"jazz"}, want: []string{"Library Radio"}}, + {name: "all libraries", want: []string{"Library Radio · Music", "Library Radio · Jazz"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + p := newProvider(NewClient(srv.URL, "tok", tt.libraries...)) + lists, err := p.Playlists() + if err != nil { + t.Fatalf("Playlists: %v", err) + } + var got []string + for _, l := range lists { + if l.Section == sectionRadio { + got = append(got, l.Name) + } + } + if !slices.Equal(got, tt.want) { + t.Fatalf("stations = %v, want %v", got, tt.want) + } + if tt.libraries != nil && !strings.Contains(lists[0].ID, "/sections/4/") { + t.Fatalf("station %q is not from the selected library", lists[0].ID) + } + }) + } +} + +// The last track of a station batch continues the same server play queue, +// once; a failed continuation can be retried. +func TestProviderStationContinuesAfterLastTrack(t *testing.T) { + srv, queues := stationServer(t, http.StatusOK) + p := newProvider(NewClient(srv.URL, "tok")) + batch, err := p.Tracks(prefixStation + "/library/sections/3/stations/3") + if err != nil { + t.Fatalf("Tracks: %v", err) + } + last := batch[len(batch)-1] + if !p.CanContinueAfter(last) || p.CanContinueAfter(playlist.Track{Path: TrackURIPrefix + "1"}) { + t.Fatal("CanContinueAfter does not single out the batch's last track") + } + + next, err := p.ContinueAfter(last) + if err != nil { + t.Fatalf("ContinueAfter: %v", err) + } + if len(next) != 1 || next[0].Path != TrackURIPrefix+"7101" { + t.Fatalf("next batch = %+v, want the item after 100", next) + } + if *queues != 1 { + t.Fatalf("play queues started = %d, want 1: continuing reuses the queue", *queues) + } + if p.CanContinueAfter(last) { + t.Fatal("the old batch end still continues") + } + if !p.CanContinueAfter(next[0]) { + t.Fatal("the new batch end does not continue") + } + + srv.Close() + if _, err := p.ContinueAfter(next[0]); err == nil { + t.Fatal("ContinueAfter succeeded against a closed server") + } + if !p.CanContinueAfter(next[0]) { + t.Fatal("a failed continuation dropped the queue") + } +} diff --git a/provider/interfaces.go b/provider/interfaces.go index d3564ac3e..d661451d3 100644 --- a/provider/interfaces.go +++ b/provider/interfaces.go @@ -467,6 +467,16 @@ type CodeAuthenticator interface { Authenticate(code string) error } +// QueueContinuer is implemented by providers whose lists never end, such as +// radio stations, that load them in batches. When the last track of a batch +// starts, the UI asks for the next batch and appends it to the queue. +// CanContinueAfter must not do I/O; ContinueAfter runs from a command +// goroutine and returns no tracks when the list has ended. +type QueueContinuer interface { + CanContinueAfter(track playlist.Track) bool + ContinueAfter(track playlist.Track) ([]playlist.Track, error) +} + // ChatFilter is implemented by a provider whose list can be narrowed to a set // of sources, such as the chats of an account. Dialogs returns every source, // Chats the current filter, and SetChats persists and applies a new one. An diff --git a/site/index.html b/site/index.html index 936375a40..f265d3662 100644 --- a/site/index.html +++ b/site/index.html @@ -659,7 +659,7 @@

Close the tab. Play the music.

{name:"Telegram",kind:"streaming",note:"MTProto · phone login"}, {name:"Bandcamp",kind:"streaming",note:"your purchases · Subsonic API"}, {name:"Bilibili",kind:"streaming",note:"video audio · yt-dlp"}, - {name:"Plex",kind:"self-hosted",note:"browser login and sign-out · server-side likes · remote discovery · resume"}, + {name:"Plex",kind:"self-hosted",note:"browser login and sign-out · library radio · server-side likes · remote discovery · resume"}, {name:"Jellyfin",kind:"self-hosted",note:"API key / password, gapless, resume"}, {name:"Emby",kind:"self-hosted",note:"API key / password, resume"}, {name:"Navidrome",kind:"self-hosted",note:"Subsonic API · lyrics"}, diff --git a/ui/model/playback.go b/ui/model/playback.go index 9b44909aa..d85b411e6 100644 --- a/ui/model/playback.go +++ b/ui/model/playback.go @@ -569,7 +569,7 @@ func (m *Model) beginPlaybackTrack(track playlist.Track) (playlist.Track, tea.Cm positionSec = m.resume.secs } m.persistPlaybackContext(track, positionSec, time.Now()) - cmd := tea.Batch(m.recordListenedTrack(track), m.ytdlArtistCmd(track)) + cmd := tea.Batch(m.recordListenedTrack(track), m.ytdlArtistCmd(track), m.continueQueueCmd(track)) m.reconnect.attempts = 0 m.reconnect.at = time.Time{} m.reconnect.ytdlLiveDrain = false diff --git a/ui/model/queue_continue.go b/ui/model/queue_continue.go new file mode 100644 index 000000000..cc27ded82 --- /dev/null +++ b/ui/model/queue_continue.go @@ -0,0 +1,54 @@ +package model + +import ( + tea "charm.land/bubbletea/v2" + + "github.com/bjarneo/cliamp/applog" + "github.com/bjarneo/cliamp/playlist" + "github.com/bjarneo/cliamp/provider" +) + +// queueContinuedMsg carries the next batch of an endless list, such as a +// Plex radio station, that continues after the track at path after. +type queueContinuedMsg struct { + after string + tracks []playlist.Track + err error +} + +// continueQueueCmd asks the provider for the next batch when track ends a +// batch of an endless list. Asking when the last track starts leaves its +// whole length to load the batch and preload the next track, so playback +// does not pause. +func (m *Model) continueQueueCmd(track playlist.Track) tea.Cmd { + if m.playlist == nil { + return nil + } + continuer, _ := findCapable(m, func(c provider.QueueContinuer) bool { + return c.CanContinueAfter(track) + }) + if continuer == nil { + return nil + } + return func() tea.Msg { + tracks, err := continuer.ContinueAfter(track) + return queueContinuedMsg{after: track.Path, tracks: tracks, err: err} + } +} + +// handleQueueContinued appends the next batch when the queue still ends with +// the track it continues; a queue replaced in the meantime keeps its content. +func (m *Model) handleQueueContinued(msg queueContinuedMsg) { + if msg.err != nil { + applog.Warn("continue queue: %v", msg.err) + return + } + if len(msg.tracks) == 0 || m.playlist == nil { + return + } + tracks := m.playlist.Tracks() + if len(tracks) == 0 || tracks[len(tracks)-1].Path != msg.after { + return + } + m.playlist.Add(msg.tracks...) +} diff --git a/ui/model/queue_continue_test.go b/ui/model/queue_continue_test.go new file mode 100644 index 000000000..7f1fa3b41 --- /dev/null +++ b/ui/model/queue_continue_test.go @@ -0,0 +1,78 @@ +package model + +import ( + "errors" + "testing" + + "github.com/bjarneo/cliamp/playlist" +) + +// continueProvider continues after its batch's last track. +type continueProvider struct { + commandsTestProvider + last string + next []playlist.Track + err error + calls int +} + +func (p *continueProvider) CanContinueAfter(track playlist.Track) bool { return track.Path == p.last } + +func (p *continueProvider) ContinueAfter(playlist.Track) ([]playlist.Track, error) { + p.calls++ + return p.next, p.err +} + +func TestContinueQueue(t *testing.T) { + batch := []playlist.Track{{Path: "plex:track:1"}, {Path: "plex:track:2"}} + next := []playlist.Track{{Path: "plex:track:3"}, {Path: "plex:track:4"}} + tests := []struct { + name string + track playlist.Track + replace []playlist.Track // queue after the request, nil keeps the batch + err error + wantCmd bool + wantPath []string + }{ + {name: "last track appends", track: batch[1], wantCmd: true, + wantPath: []string{"plex:track:1", "plex:track:2", "plex:track:3", "plex:track:4"}}, + {name: "earlier track asks nothing", track: batch[0], wantPath: []string{"plex:track:1", "plex:track:2"}}, + {name: "replaced queue is kept", track: batch[1], wantCmd: true, + replace: []playlist.Track{{Path: "/music/a.mp3"}}, wantPath: []string{"/music/a.mp3"}}, + {name: "error appends nothing", track: batch[1], err: errors.New("offline"), wantCmd: true, + wantPath: []string{"plex:track:1", "plex:track:2"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + pl := playlist.New() + pl.Replace(batch) + m := New(&playbackFakeEngine{}, pl, nil, "", nil, nil, nil, nil, nil, nil) + prov := &continueProvider{commandsTestProvider: commandsTestProvider{name: "Plex"}, last: batch[1].Path, next: next, err: tt.err} + m.provider = prov + + cmd := m.continueQueueCmd(tt.track) + if (cmd != nil) != tt.wantCmd { + t.Fatalf("command = %v, want %v", cmd != nil, tt.wantCmd) + } + if cmd != nil { + msg := cmd().(queueContinuedMsg) + if tt.replace != nil { + m.playlist.Replace(tt.replace) + } + m.handleQueueContinued(msg) + } + var got []string + for _, track := range m.playlist.Tracks() { + got = append(got, track.Path) + } + if len(got) != len(tt.wantPath) { + t.Fatalf("queue = %v, want %v", got, tt.wantPath) + } + for i := range got { + if got[i] != tt.wantPath[i] { + t.Fatalf("queue = %v, want %v", got, tt.wantPath) + } + } + }) + } +} diff --git a/ui/model/update.go b/ui/model/update.go index d6e1ecacf..5bca19954 100644 --- a/ui/model/update.go +++ b/ui/model/update.go @@ -184,6 +184,10 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { m.handleCatalogSearch(msg) return m, nil + case queueContinuedMsg: + m.handleQueueContinued(msg) + return m, nil + case ytdlBatchMsg: cmd := m.handleYTDLBatch(msg) return m, cmd From 3aebd646b77f418b57248079e9dc35f62537c80d Mon Sep 17 00:00:00 2001 From: Igor Maliavko Date: Tue, 27 Oct 2026 14:37:27 +0100 Subject: [PATCH 12/32] fix(plex): stream parts as the original file Plex answered HTTP 500 for newly added FLAC albums. Its log showed why: for a /library/parts request it checks the file against the client's direct-play profile, cliamp sends none, and the generic profile has no FLAC over HTTP ("No direct play music profile exists for protocol http, with container flac"). Older FLAC passed only because Plex had not stored their audio stream details. Request parts with download=1, as Plexamp does, so Plex serves the original file without a profile check. Verified with make check (gofmt, go vet, go test ./...), a request for a failing part on the live server (500 before, 206 with download=1), and playback of the album in cliamp. Co-Authored-By: Claude Opus 5.5 --- docs/plex.md | 2 +- external/plex/client.go | 7 ++++++- external/plex/client_test.go | 32 +++++++++++++++++++++++++++++++- external/plex/provider_test.go | 2 +- 4 files changed, 39 insertions(+), 4 deletions(-) diff --git a/docs/plex.md b/docs/plex.md index a6d9f2a67..be38fbdbf 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -164,7 +164,7 @@ cliamp calls the Plex HTTP API to list audio playlists (`/playlists`) and music plex:track: ``` -When playback starts, cliamp resolves that path to the Plex part URL in memory and authenticates the request with your token. The token is not written into track paths or exposed through status output. Plex serves the original file without transcoding. cliamp handles playback through its HTTP streaming pipeline and can play MP3, FLAC, AAC, OGG, OPUS, WAV, and other supported source formats. +When playback starts, cliamp resolves that path to the Plex part URL in memory and authenticates the request with your token. The token is not written into track paths or exposed through status output. Plex serves the original file without transcoding: cliamp asks for it with `download=1`, as Plexamp does, so Plex does not check the file against a client profile. Without it Plex refuses FLAC files it has analyzed with HTTP 500. cliamp handles playback through its HTTP streaming pipeline and can play MP3, FLAC, AAC, OGG, OPUS, WAV, and other supported source formats. ## Troubleshooting diff --git a/external/plex/client.go b/external/plex/client.go index 9aa57e125..6ab1bde12 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -551,10 +551,15 @@ func (c *Client) Search(query string) ([]Track, error) { // StreamURL returns the authenticated HTTP URL for streaming a track part. // partKey is the relative path from the Part element, e.g. "/library/parts/…/file.flac". // The token is appended as a query parameter; Plex accepts it in either header or query form. +// +// download=1 asks for the original file, as Plexamp does. Without it Plex +// checks the part against the client's direct-play profile; cliamp has none, +// so Plex falls back to a generic profile without FLAC and answers 500 for +// every FLAC whose audio stream it has analyzed. func (c *Client) StreamURL(partKey string) string { c.mu.Lock() defer c.mu.Unlock() - return c.baseURL + partKey + "?X-Plex-Token=" + url.QueryEscape(c.token) + return c.baseURL + partKey + "?download=1&X-Plex-Token=" + url.QueryEscape(c.token) } // IsStreamURL reports whether the given URL looks like a Plex library part diff --git a/external/plex/client_test.go b/external/plex/client_test.go index e965eccd3..721c080ef 100644 --- a/external/plex/client_test.go +++ b/external/plex/client_test.go @@ -713,7 +713,7 @@ func TestTracks_MissingMedia(t *testing.T) { func TestStreamURL_Format(t *testing.T) { c := NewClient("http://192.168.1.10:32400", "mytoken") got := c.StreamURL("/library/parts/100/111/file.flac") - want := "http://192.168.1.10:32400/library/parts/100/111/file.flac?X-Plex-Token=mytoken" + want := "http://192.168.1.10:32400/library/parts/100/111/file.flac?download=1&X-Plex-Token=mytoken" if got != want { t.Errorf("StreamURL:\n got %q\n want %q", got, want) } @@ -883,3 +883,33 @@ func TestPingRejectsOversizedBody(t *testing.T) { t.Fatalf("Ping() error = %v, want httpclient.ErrTooLarge", err) } } + +// A part whose analyzed stream fails Plex's generic client profile answers +// 500 to a plain request; the original file request with download=1, as +// Plexamp sends it, plays. +func TestStreamURLPlaysAnalyzedFLAC(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("download") != "1" { + http.Error(w, "No direct play music profile exists for protocol http, with container flac", http.StatusInternalServerError) + return + } + if got := r.URL.Query().Get("X-Plex-Token"); got != "tok" { + t.Errorf("token = %q", got) + } + w.Header().Set("Content-Type", "audio/flac") + _, _ = w.Write([]byte("fLaC")) + })) + defer srv.Close() + + resp, err := http.Get(NewClient(srv.URL, "tok").StreamURL("/library/parts/60716/1793101096/file.flac")) + if err != nil { + t.Fatalf("GET: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200", resp.StatusCode) + } + if !IsStreamURL(resp.Request.URL.String()) { + t.Fatal("stream URL no longer routes through the buffered pipeline") + } +} diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index c3efe548a..025a327f2 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -293,7 +293,7 @@ func TestProviderResolveSourceRestoresAfterRestart(t *testing.T) { if err != nil { t.Fatalf("ResolveSource: %v", err) } - want := srv.URL + "/library/parts/1/111/file.flac?X-Plex-Token=tok" + want := srv.URL + "/library/parts/1/111/file.flac?download=1&X-Plex-Token=tok" if got != want { t.Fatalf("ResolveSource = %q, want %q", got, want) } From bb6044dae69a61afd4fba1d9f7787e643e5e74bb Mon Sep 17 00:00:00 2001 From: Igor Maliavko Date: Tue, 27 Oct 2026 14:37:49 +0100 Subject: [PATCH 13/32] fix(plex): list radio stations after playlists The Plex browser listed radio stations above the playlists. Order the sections as playlists, radio stations, then albums. Verified with make check (gofmt, go vet, go test ./...). Co-Authored-By: Claude Opus 5.5 --- docs/plex.md | 12 ++++++------ external/plex/provider.go | 3 ++- external/plex/provider_test.go | 24 +++++++++++++++++------- 3 files changed, 25 insertions(+), 14 deletions(-) diff --git a/docs/plex.md b/docs/plex.md index be38fbdbf..014bcf196 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -93,21 +93,21 @@ the other computer so Plex lists it as a separate authorized device. After configuration, **Plex** appears in the cliamp provider list. -The provider shows the library radio stations, audio playlists, and the music +The provider shows audio playlists, the library radio stations, and the music library under three headers: ```text +── Playlists ── +GOOD +All Music +drums + ── Radio ── Library Radio Deep Cuts Radio Time Travel Radio Random Album Radio -── Playlists ── -GOOD -All Music -drums - ── Albums ── Artist - Album Title (Year) ``` diff --git a/external/plex/provider.go b/external/plex/provider.go index 12a1954f1..6e7e4892f 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -132,7 +132,8 @@ func (p *Provider) Playlists() ([]playlist.PlaylistInfo, error) { if err != nil { return nil, err } - lists = append(p.stationLists(sections), lists...) + // Playlists, then radio stations, then albums. + lists = append(lists, p.stationLists(sections)...) for _, sec := range sections { albums, err := p.client.Albums(sec.Key) if err != nil { diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index 025a327f2..1abaf39c2 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -693,7 +693,7 @@ func stationServer(t *testing.T, hubStatus int) (*httptest.Server, *int) { w.Header().Set("Content-Type", "application/json") switch { case r.URL.Path == "/playlists": - w.Write([]byte(`{"MediaContainer":{"Metadata":[]}}`)) + w.Write([]byte(`{"MediaContainer":{"Metadata":[{"ratingKey":"5","title":"Mix","playlistType":"audio","leafCount":2}]}}`)) case r.URL.Path == "/library/sections": w.Write([]byte(`{"MediaContainer":{"Directory":[{"key":"3","type":"artist","title":"Music"}]}}`)) case r.URL.Path == "/library/sections/3/all": @@ -786,11 +786,19 @@ func TestProviderStationLists(t *testing.T) { if !slices.Equal(got, tt.want) { t.Fatalf("stations = %v, want %v", got, tt.want) } - if lists[len(lists)-1].ID != "1" { - t.Fatalf("album missing after stations: %v", lists) + // Playlists, then radio stations, then albums. + var sections []string + for _, l := range lists { + if len(sections) == 0 || sections[len(sections)-1] != l.Section { + sections = append(sections, l.Section) + } + } + want := []string{sectionPlaylists, sectionRadio, sectionAlbums} + if len(got) == 0 { + want = []string{sectionPlaylists, sectionAlbums} } - if len(got) > 0 && lists[0].Section != sectionRadio { - t.Fatalf("stations are not first: %v", lists) + if !slices.Equal(sections, want) { + t.Fatalf("section order = %v, want %v", sections, want) } }) } @@ -868,8 +876,10 @@ func TestProviderStationsFollowLibraries(t *testing.T) { if !slices.Equal(got, tt.want) { t.Fatalf("stations = %v, want %v", got, tt.want) } - if tt.libraries != nil && !strings.Contains(lists[0].ID, "/sections/4/") { - t.Fatalf("station %q is not from the selected library", lists[0].ID) + for _, l := range lists { + if tt.libraries != nil && l.Section == sectionRadio && !strings.Contains(l.ID, "/sections/4/") { + t.Fatalf("station %q is not from the selected library", l.ID) + } } }) } From c7a1ddbd12de66eccdcd0304ee08be70399e673c Mon Sep 17 00:00:00 2001 From: maliavko Date: Sat, 31 Oct 2026 13:58:51 +0100 Subject: [PATCH 14/32] fix(plex): show likes of the restored list After a restart, the album or playlist restored from the last session showed no Plex likes until it was opened again. Its tracks come from resume.json, and Plex knows a like only from track metadata that the server sent in this process. Add provider.TrackFavoriteLoader. At start the UI runs it in a command for the start playlist and redraws when it returns. Plex asks the server for the ratings of the tracks whose state is unknown, 100 per /library/metadata/k1,k2,... request, and keeps a state set meanwhile by a listing or a toggle. A failure is only logged. Verified with make check (gofmt, go vet, go test ./...), new tests for the Plex batches and the UI command, and by restarting cliamp on a restored Plex album. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/plex.md | 4 +- docs/provider-development.md | 1 + external/plex/client.go | 21 +++++++++++ external/plex/provider.go | 46 ++++++++++++++++++++++- external/plex/provider_test.go | 69 ++++++++++++++++++++++++++++++++++ provider/interfaces.go | 8 ++++ ui/model/favorites.go | 38 +++++++++++++++++++ ui/model/favorites_test.go | 46 +++++++++++++++++++++++ ui/model/init.go | 3 ++ ui/model/update.go | 4 ++ 10 files changed, 238 insertions(+), 2 deletions(-) diff --git a/docs/plex.md b/docs/plex.md index 014bcf196..7f99f1ddd 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -140,7 +140,9 @@ and the album or playlist it was chosen from. State is saved when a track starts, every two seconds during confirmed playback, and during a normal exit. On the next launch with no explicit files, URLs, or playlist, cliamp restores that list with the last track selected; the time and seek bar already show the -saved position. Press `Enter` to continue from it; `auto_play` is ignored for a restored list. The saved list keeps only +saved position. Press `Enter` to continue from it; `auto_play` is ignored for a restored list. The hearts of the +restored tracks appear once cliamp has asked the server for their likes, right +after start. The saved list keeps only token-free `plex:track:` paths, and the current Plex credentials are added when playback starts. This works as it does for [Jellyfin](jellyfin.md#usage). diff --git a/docs/provider-development.md b/docs/provider-development.md index 700f78381..83f242889 100644 --- a/docs/provider-development.md +++ b/docs/provider-development.md @@ -205,6 +205,7 @@ are in `provider/interfaces.go`. | `TrackFavoriter` | Copy the ♥ favorite of a track to the service, such as liked or starred songs. The UI calls it in a `tea.Cmd` and keeps the local favorite when it fails | `CanFavoriteTrack(track)`, `SetTrackFavorite(ctx, track, favorite) error` | | `TrackRater` | Set or clear a provider-owned numeric track rating | `CanRateTrack(track)`, `SetTrackRating(ctx, track, rating) error` | | `TrackFavoriteState` | Make provider metadata authoritative for a track's ♥ state. Local favorites are ignored for tracks claimed by this interface | `CanFavoriteTrack(track)`, `FavoriteState(track)` | +| `TrackFavoriteLoader` | Fetch the ♥ state of tracks that have none, such as the start playlist restored from the last session. The UI calls it in a `tea.Cmd` at start | `LoadFavoriteStates(ctx, tracks) error` | | `CatalogLoader` | Lazy paging of a large catalog | `LoadCatalogPage(offset, limit)` | | `CatalogSearcher` | Server-side catalog search that fills the pane | `SearchCatalog(query)`, `ClearSearch()`, `IsSearching()` | | `LocationConsenter` | Ask before the provider uses the location of the listener | `NeedsLocationConsent()`, `LocationConsentID()`, `LocationPrompt()`, `SetLocationConsent(allowed)` | diff --git a/external/plex/client.go b/external/plex/client.go index 6ab1bde12..67dcec30d 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -522,6 +522,27 @@ func (c *Client) Track(ratingKey string) (Track, error) { return trackFromJSON(result.MediaContainer.Metadata[0]), nil } +// TracksByKey returns the tracks with the given ratingKeys in one request. +// Keys the server does not know are left out. +func (c *Client) TracksByKey(ratingKeys []string) ([]Track, error) { + if len(ratingKeys) == 0 { + return nil, nil + } + var result struct { + MediaContainer struct { + Metadata []trackJSON `json:"Metadata"` + } `json:"MediaContainer"` + } + if err := c.get("/library/metadata/"+strings.Join(ratingKeys, ","), nil, &result); err != nil { + return nil, err + } + tracks := make([]Track, 0, len(result.MediaContainer.Metadata)) + for _, item := range result.MediaContainer.Metadata { + tracks = append(tracks, trackFromJSON(item)) + } + return tracks, nil +} + // Search searches the music library for tracks matching query. // Returns nil without making an HTTP call when query is empty. func (c *Client) Search(query string) ([]Track, error) { diff --git a/external/plex/provider.go b/external/plex/provider.go index 6e7e4892f..ee77e9bc7 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -31,7 +31,9 @@ const ( // stationBatch is how many tracks a station loads at a time. When the // last one starts, the next batch is appended; Ctrl+R on the open // station starts it again for a fresh selection. - stationBatch = 30 + stationBatch = 30 + // favoriteBatch is how many tracks one request asks the rating of. + favoriteBatch = 100 albumCacheTTL = 5 * time.Minute ) @@ -47,6 +49,7 @@ var ( _ provider.AlbumTrackLoader = (*Provider)(nil) _ provider.TrackFavoriter = (*Provider)(nil) _ provider.TrackFavoriteState = (*Provider)(nil) + _ provider.TrackFavoriteLoader = (*Provider)(nil) _ provider.ProgressReporter = (*Provider)(nil) _ provider.QueueContinuer = (*Provider)(nil) ) @@ -359,6 +362,47 @@ func (p *Provider) FavoriteState(track playlist.Track) (favorite, known bool) { return favorite, known } +// LoadFavoriteStates fetches the Plex rating of the tracks among tracks whose +// state is unknown, such as the tracks restored from the last session. A +// state set meanwhile, by a listing or a toggle, is kept. +func (p *Provider) LoadFavoriteStates(ctx context.Context, tracks []playlist.Track) error { + var ids []string + seen := make(map[string]bool) + p.mu.Lock() + for _, track := range tracks { + id := plexTrackID(track) + if id == "" || seen[id] { + continue + } + seen[id] = true + if _, known := p.favorites[id]; !known { + ids = append(ids, id) + } + } + p.mu.Unlock() + + for batch := range slices.Chunk(ids, favoriteBatch) { + if err := ctx.Err(); err != nil { + return err + } + found, err := p.client.TracksByKey(batch) + if err != nil { + return fmt.Errorf("plex: load favorites: %w", err) + } + p.mu.Lock() + if p.favorites == nil { + p.favorites = make(map[string]bool) + } + for _, t := range found { + if _, known := p.favorites[t.RatingKey]; !known { + p.favorites[t.RatingKey] = t.UserRating >= 10 + } + } + p.mu.Unlock() + } + return nil +} + // SetTrackFavorite updates the current user's favorite state in Plex. func (p *Provider) SetTrackFavorite(ctx context.Context, track playlist.Track, favorite bool) error { id := plexTrackID(track) diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index 1abaf39c2..98b0cd39a 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -8,6 +8,7 @@ import ( "slices" "strconv" "strings" + "sync" "testing" "time" @@ -924,3 +925,71 @@ func TestProviderStationContinuesAfterLastTrack(t *testing.T) { t.Fatal("a failed continuation dropped the queue") } } + +func TestProviderLoadFavoriteStates(t *testing.T) { + var ( + mu sync.Mutex + requests []string + ) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + keys, ok := strings.CutPrefix(r.URL.Path, "/library/metadata/") + if !ok { + w.WriteHeader(http.StatusNotFound) + return + } + mu.Lock() + requests = append(requests, keys) + mu.Unlock() + var items []string + for _, k := range strings.Split(keys, ",") { + rating := 0 + if n, _ := strconv.Atoi(k); n%2 == 0 { + rating = 10 + } + items = append(items, fmt.Sprintf(`{"ratingKey":%q,"title":"T%s","userRating":%d}`, k, k, rating)) + } + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"MediaContainer":{"Metadata":[%s]}}`, strings.Join(items, ",")) + })) + defer srv.Close() + sent := func() []string { + mu.Lock() + defer mu.Unlock() + return slices.Clone(requests) + } + + p := newProvider(NewClient(srv.URL, "tok")) + // A state known before the load, as from a toggle, is kept and not asked. + p.favorites = map[string]bool{"1": true} + + var tracks []playlist.Track + for i := 1; i <= favoriteBatch+2; i++ { + tracks = append(tracks, playlist.Track{Path: TrackURIPrefix + strconv.Itoa(i)}) + } + tracks = append(tracks, tracks[1], playlist.Track{Path: "/local/song.mp3"}) + if err := p.LoadFavoriteStates(t.Context(), tracks); err != nil { + t.Fatalf("LoadFavoriteStates: %v", err) + } + + got := sent() + if len(got) != 2 { + t.Fatalf("requests = %d, want 2 batches", len(got)) + } + if first := strings.Split(got[0], ","); len(first) != favoriteBatch || first[0] != "2" { + t.Fatalf("first batch = %d keys from %q, want %d from \"2\"", len(first), first[0], favoriteBatch) + } + for _, tt := range []struct { + id string + want bool + }{{"1", true}, {"2", true}, {"3", false}, {strconv.Itoa(favoriteBatch + 2), true}} { + got, known := p.FavoriteState(playlist.Track{Path: TrackURIPrefix + tt.id}) + if !known || got != tt.want { + t.Errorf("FavoriteState(%s) = %v, %v; want %v, true", tt.id, got, known, tt.want) + } + } + + // Every state is known now, so a second load sends nothing. + if err := p.LoadFavoriteStates(t.Context(), tracks); err != nil || len(sent()) != 2 { + t.Fatalf("second load: err %v, requests %d; want none", err, len(sent())) + } +} diff --git a/provider/interfaces.go b/provider/interfaces.go index d661451d3..6562ca75b 100644 --- a/provider/interfaces.go +++ b/provider/interfaces.go @@ -362,6 +362,14 @@ type TrackFavoriteState interface { FavoriteState(track playlist.Track) (favorite, known bool) } +// TrackFavoriteLoader is implemented by a TrackFavoriteState provider whose +// favorite state comes with its track listings, so tracks restored from the +// last session have none. LoadFavoriteStates fetches the state of its own +// tracks among tracks. It does I/O, so the UI runs it in a command. +type TrackFavoriteLoader interface { + LoadFavoriteStates(ctx context.Context, tracks []playlist.Track) error +} + // FavoriteToggler is implemented by providers that support marking items // as favorites (e.g. radio station favorites). type FavoriteToggler interface { diff --git a/ui/model/favorites.go b/ui/model/favorites.go index 640c28941..71a24ad95 100644 --- a/ui/model/favorites.go +++ b/ui/model/favorites.go @@ -8,6 +8,7 @@ import ( tea "charm.land/bubbletea/v2" + "github.com/bjarneo/cliamp/applog" "github.com/bjarneo/cliamp/favorites" "github.com/bjarneo/cliamp/playlist" "github.com/bjarneo/cliamp/provider" @@ -135,6 +136,43 @@ func (m *Model) syncTrackFavoriteCmd(track playlist.Track, favorite bool) tea.Cm } } +// trackFavoritesLoadedMsg reports that the providers fetched the favorite +// state of the start playlist. The redraw after it shows the hearts. +type trackFavoritesLoadedMsg struct{} + +// loadTrackFavoritesCmd fetches the favorite state that tracks restored from +// the last session lack, from each provider that keeps it with its listings. +// It returns nil when no provider does. +func (m *Model) loadTrackFavoritesCmd(tracks []playlist.Track) tea.Cmd { + if len(tracks) == 0 { + return nil + } + // The active provider is also in m.providers. A second call finds + // every state known and sends no request. + var loaders []provider.TrackFavoriteLoader + if l, ok := m.provider.(provider.TrackFavoriteLoader); ok { + loaders = append(loaders, l) + } + for _, pe := range m.providers { + if l, ok := pe.Provider.(provider.TrackFavoriteLoader); ok { + loaders = append(loaders, l) + } + } + if len(loaders) == 0 { + return nil + } + return func() tea.Msg { + ctx, cancel := context.WithTimeout(context.Background(), trackFavoriteSyncTimeout) + defer cancel() + for _, l := range loaders { + if err := l.LoadFavoriteStates(ctx, tracks); err != nil { + applog.Warn("load favorites: %v", err) + } + } + return trackFavoritesLoadedMsg{} + } +} + // handleTrackFavoriteSynced drops the optimistic provider state after the // provider cache has been updated, or rolls it back after a failure. Local // favorites copied to Spotify and Navidrome are unaffected. diff --git a/ui/model/favorites_test.go b/ui/model/favorites_test.go index 8735e6491..83f8581cf 100644 --- a/ui/model/favorites_test.go +++ b/ui/model/favorites_test.go @@ -712,3 +712,49 @@ func runCmds(cmd tea.Cmd) { } } } + +// fakeFavoriteLoader is a provider.TrackFavoriteLoader that records the +// tracks it was asked about. +type fakeFavoriteLoader struct { + commandsTestProvider + mu sync.Mutex + loaded [][]string +} + +func (p *fakeFavoriteLoader) LoadFavoriteStates(_ context.Context, tracks []playlist.Track) error { + p.mu.Lock() + defer p.mu.Unlock() + var paths []string + for _, t := range tracks { + paths = append(paths, t.Path) + } + p.loaded = append(p.loaded, paths) + return nil +} + +// Tracks restored from the last session have no provider favorite state, so +// the start loads it in the background and redraws. +func TestLoadTrackFavoritesCmd(t *testing.T) { + tracks := []playlist.Track{{Path: "plex:track:1"}, {Path: "plex:track:2"}} + loader := &fakeFavoriteLoader{commandsTestProvider: commandsTestProvider{name: "Plex"}} + + m := keybindingTestModel() + if cmd := m.loadTrackFavoritesCmd(tracks); cmd != nil { + t.Fatal("command without a loading provider") + } + m.providers = []provider.Entry{{Name: "Plex", Provider: loader}} + if cmd := m.loadTrackFavoritesCmd(nil); cmd != nil { + t.Fatal("command without tracks") + } + + msgs := runCmd(m.loadTrackFavoritesCmd(tracks)) + if len(msgs) != 1 { + t.Fatalf("messages = %v, want one", msgs) + } + if _, ok := msgs[0].(trackFavoritesLoadedMsg); !ok { + t.Fatalf("message = %T, want trackFavoritesLoadedMsg", msgs[0]) + } + if len(loader.loaded) != 1 || strings.Join(loader.loaded[0], " ") != "plex:track:1 plex:track:2" { + t.Fatalf("loaded = %v, want the two tracks once", loader.loaded) + } +} diff --git a/ui/model/init.go b/ui/model/init.go index 04e0b2e79..b5b044667 100644 --- a/ui/model/init.go +++ b/ui/model/init.go @@ -346,6 +346,9 @@ func (m Model) Init() tea.Cmd { if m.autoPlay && m.playlist.Len() > 0 { cmds = append(cmds, func() tea.Msg { return autoPlayMsg{} }) } + if cmd := m.loadTrackFavoritesCmd(m.playlist.Tracks()); cmd != nil { + cmds = append(cmds, cmd) + } return tea.Batch(cmds...) } diff --git a/ui/model/update.go b/ui/model/update.go index 5bca19954..532ba9696 100644 --- a/ui/model/update.go +++ b/ui/model/update.go @@ -388,6 +388,10 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { m.handleTrackRatingSynced(msg) return m, nil + case trackFavoritesLoadedMsg: + // The provider now knows the state; the redraw shows it. + return m, nil + case ShowStatusMsg: ttl := statusTTLDefault if msg.Duration > 0 { From 6a7c88795f0ebfeb9c0af8034ffa3767869bd535 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sat, 31 Oct 2026 15:28:13 +0100 Subject: [PATCH 15/32] fix(ui): recount album headers after undo Ctrl+Z after a replace of the whole queue, such as opening an album from a list of liked tracks, brought the old tracks back but kept the album headers of the replacing queue, so every single track got its own album header. Recount the header state from the restored tracks. A manual Ctrl+H choice still stands. Verified with make check (gofmt, go vet, go test ./...) and a new test that fails without the fix. Co-Authored-By: Claude Opus 5.5 (1M context) --- ui/model/playback.go | 3 +++ ui/model/undo_headers_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 ui/model/undo_headers_test.go diff --git a/ui/model/playback.go b/ui/model/playback.go index d85b411e6..79b137c95 100644 --- a/ui/model/playback.go +++ b/ui/model/playback.go @@ -386,6 +386,9 @@ func (m *Model) undoPlaylistMutation() tea.Cmd { } m.playlist.Restore(undo.snapshot) m.normalizeQueueOverlay() + // The restored queue can be another list altogether, such as the one a + // song mix replaced, so its album headers follow its own tracks. + m.recountHeaderState(m.playlist.Tracks()) m.playlistUndo = playlistUndo{} if m.plCursor >= m.playlist.Len() { m.plCursor = max(0, m.playlist.Len()-1) diff --git a/ui/model/undo_headers_test.go b/ui/model/undo_headers_test.go new file mode 100644 index 000000000..198d2ea2c --- /dev/null +++ b/ui/model/undo_headers_test.go @@ -0,0 +1,31 @@ +package model + +import ( + "testing" + + "github.com/bjarneo/cliamp/playlist" +) + +// Undoing a replace of the whole queue brings back the album headers of the +// old queue: a list of single tracks from many albums shows none, though the +// album that replaced it did. +func TestUndoRecountsAlbumHeaders(t *testing.T) { + m := keybindingTestModel() + singles := []playlist.Track{{Path: "a.mp3", Album: "A"}, {Path: "b.mp3", Album: "B"}, {Path: "c.mp3", Album: "C"}} + m.playlist.Replace(singles) + m.setHeaderStateFromTracks(singles) + snapshot := m.playlist.Snapshot() + + album := []playlist.Track{{Path: "x1.mp3", Album: "X"}, {Path: "x2.mp3", Album: "X"}, {Path: "x3.mp3", Album: "X"}} + m.replacePlaylist(album) + m.setHeaderStateFromTracks(album) + m.recordPlaylistUndo(playlistUndo{snapshot: snapshot}) + if !m.showAlbumHeaders { + t.Fatal("the album shows no album headers") + } + + m.undoPlaylistMutation() + if m.showAlbumHeaders { + t.Fatal("undo kept the album's headers on a list of single tracks") + } +} From 9b705e3266de2ec54158599cacab0fab85ac3b16 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sat, 31 Oct 2026 15:28:38 +0100 Subject: [PATCH 16/32] feat(plex): open a track's album or artist MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From a Plex track in the queue there was no way to reach its album or the other albums of its artist except scrolling or filtering the browser by hand. Alt+O replaces the queue with the album of the highlighted track and puts the cursor on it; playback goes on, and a playing track on the album becomes its current track. Ctrl+Z brings the old queue back with the cursor on that track again. Alt+L opens the browser of the track's provider filtered to "^Artist — ", the albums of its artist; the filter is an ordinary one, and a filter set before the lists arrive applies to them. Both keys are free in the core, and the plugin docs do not offer them as examples. Ctrl+O went to reversing the playlist. Two provider interfaces carry it: TrackAlbumResolver names the album of a track as a list, and TrackArtistFilter names the filter. Plex keeps the album key of a track in ProviderMeta and, for a list restored without it, from the metadata it fetches at start. The "^" phrase filter comes with the word-start fuzzy matcher. Verified with make check (gofmt, go vet, go test ./...), new tests for the jumps, the undo cursor and the Plex resolvers, and in kitty on a Plex library. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/keybindings.md | 2 + docs/plex.md | 6 ++ docs/provider-development.md | 2 + external/plex/client.go | 3 + external/plex/provider.go | 65 +++++++++++- external/plex/provider_test.go | 38 +++++++ provider/interfaces.go | 14 +++ provider/types.go | 2 + ui/model/command_registry.go | 2 + ui/model/keys.go | 11 ++ ui/model/playback.go | 3 + ui/model/providers.go | 5 + ui/model/state.go | 3 + ui/model/track_jumps.go | 163 +++++++++++++++++++++++++++++ ui/model/track_jumps_test.go | 184 +++++++++++++++++++++++++++++++++ ui/model/update.go | 3 + 16 files changed, 504 insertions(+), 2 deletions(-) create mode 100644 ui/model/track_jumps.go create mode 100644 ui/model/track_jumps_test.go diff --git a/docs/keybindings.md b/docs/keybindings.md index 96f7ac791..82cd79938 100644 --- a/docs/keybindings.md +++ b/docs/keybindings.md @@ -135,6 +135,8 @@ and `Esc` clears it. | `Ctrl+I` | Toggle Metadata below Settings for the highlighted playlist item (remembered in `show_metadata`; requires a terminal that distinguishes Ctrl+I from Tab) | | `Ctrl+S` | Save track to `[downloads].directory` (default `~/Music/cliamp`) | | `w` | Write the highlighted track to a local playlist | +| `Alt+O` | Open the album of the highlighted track: the queue becomes the album with the cursor on that track, and playback goes on. `Ctrl+Z` brings the old queue back. Plex tracks | +| `Alt+L` | Show the albums of the highlighted track's artist: open its provider browser filtered to `^Artist — `. Edit the filter as usual; `Esc` clears it. Plex tracks | | `N` | Open the active provider browser. On a selected Mixcloud show, open that creator's Uploads/Favorites. In the radio pane, open the country browser. | | `L` | Open Local provider | | `R` | Open radio provider | diff --git a/docs/plex.md b/docs/plex.md index 7f99f1ddd..63af5ce22 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -120,6 +120,12 @@ of the same queue are appended, so the station plays on without end. Press `Ctrl+R` while the station is open for a fresh selection. The `stations` setting picks which stations appear. +On a Plex track in the playlist, `Alt+O` opens its album: the queue becomes +the album, the cursor lands on the track, and playback goes on; `Ctrl+Z` +brings the old queue back. `Alt+L` opens the Plex browser filtered to the +albums of the track's artist, with the filter `^Artist — `, which you can +edit or clear with `Esc`. + Press `Ctrl+R` while an open Plex album or playlist is focused to reload it and pick up server-side changes. Album contents are cached for up to five minutes; Plex playlists are always loaded fresh so smart playlists stay current. diff --git a/docs/provider-development.md b/docs/provider-development.md index 83f242889..e423c01aa 100644 --- a/docs/provider-development.md +++ b/docs/provider-development.md @@ -205,6 +205,8 @@ are in `provider/interfaces.go`. | `TrackFavoriter` | Copy the ♥ favorite of a track to the service, such as liked or starred songs. The UI calls it in a `tea.Cmd` and keeps the local favorite when it fails | `CanFavoriteTrack(track)`, `SetTrackFavorite(ctx, track, favorite) error` | | `TrackRater` | Set or clear a provider-owned numeric track rating | `CanRateTrack(track)`, `SetTrackRating(ctx, track, rating) error` | | `TrackFavoriteState` | Make provider metadata authoritative for a track's ♥ state. Local favorites are ignored for tracks claimed by this interface | `CanFavoriteTrack(track)`, `FavoriteState(track)` | +| `TrackAlbumResolver` | Name the album of a track as one of the provider's lists, for `Alt+O`. Must not do I/O | `AlbumForTrack(track)` | +| `TrackArtistFilter` | Name the list filter that shows a track's artist, for `Alt+L`. Must not do I/O | `ArtistFilter(track)` | | `TrackFavoriteLoader` | Fetch the ♥ state of tracks that have none, such as the start playlist restored from the last session. The UI calls it in a `tea.Cmd` at start | `LoadFavoriteStates(ctx, tracks) error` | | `CatalogLoader` | Lazy paging of a large catalog | `LoadCatalogPage(offset, limit)` | | `CatalogSearcher` | Server-side catalog search that fills the pane | `SearchCatalog(query)`, `ClearSearch()`, `IsSearching()` | diff --git a/external/plex/client.go b/external/plex/client.go index 67dcec30d..e01166fdc 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -118,6 +118,7 @@ type Track struct { Title string ArtistName string // grandparentTitle AlbumName string // parentTitle + AlbumKey string // parentRatingKey Year int TrackNumber int // index field in Plex API Duration int // milliseconds @@ -600,6 +601,7 @@ type trackJSON struct { Title string `json:"title"` GrandparentTitle string `json:"grandparentTitle"` // artist ParentTitle string `json:"parentTitle"` // album + ParentRatingKey string `json:"parentRatingKey"` // album Year int `json:"year"` ParentYear int `json:"parentYear"` // album year; tracks rarely carry their own Index int `json:"index"` // track number within album @@ -626,6 +628,7 @@ func trackFromJSON(m trackJSON) Track { Title: m.Title, ArtistName: m.GrandparentTitle, AlbumName: m.ParentTitle, + AlbumKey: m.ParentRatingKey, Year: year, TrackNumber: m.Index, Duration: m.Duration, diff --git a/external/plex/provider.go b/external/plex/provider.go index ee77e9bc7..2a745b88a 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -50,6 +50,8 @@ var ( _ provider.TrackFavoriter = (*Provider)(nil) _ provider.TrackFavoriteState = (*Provider)(nil) _ provider.TrackFavoriteLoader = (*Provider)(nil) + _ provider.TrackAlbumResolver = (*Provider)(nil) + _ provider.TrackArtistFilter = (*Provider)(nil) _ provider.ProgressReporter = (*Provider)(nil) _ provider.QueueContinuer = (*Provider)(nil) ) @@ -66,7 +68,10 @@ type Provider struct { trackCache map[string]trackCacheEntry partKeys map[string]string favorites map[string]bool - stations []string // [plex] stations: nil shows all, empty hides all + // albumKeys maps a track ratingKey to its album's, for tracks whose + // ProviderMeta predates the album key, such as a restored list. + albumKeys map[string]string + stations []string // [plex] stations: nil shows all, empty hides all // stationQueues maps the path of the last track of each station batch // to the server play queue that continues after it. stationQueues map[string]stationQueue @@ -279,7 +284,7 @@ func (p *Provider) convertTracks(plexTracks []Track, limit int) []playlist.Track TrackNumber: t.TrackNumber, DurationSecs: t.Duration / 1000, Stream: true, - ProviderMeta: map[string]string{provider.MetaPlexID: t.RatingKey}, + ProviderMeta: trackMeta(t), }) if limit > 0 && len(tracks) >= limit { break @@ -322,6 +327,16 @@ func (p *Provider) ResolveSource(uri string) (string, error) { return p.client.StreamURL(partKey), nil } +// trackMeta returns the ProviderMeta of a Plex track: its ratingKey and, when +// known, its album's. +func trackMeta(t Track) map[string]string { + meta := map[string]string{provider.MetaPlexID: t.RatingKey} + if validRatingKey(t.AlbumKey) { + meta[provider.MetaPlexAlbumID] = t.AlbumKey + } + return meta +} + func trackIDFromPath(path string) (string, bool) { id, ok := strings.CutPrefix(path, TrackURIPrefix) if !ok || !validRatingKey(id) { @@ -393,10 +408,14 @@ func (p *Provider) LoadFavoriteStates(ctx context.Context, tracks []playlist.Tra if p.favorites == nil { p.favorites = make(map[string]bool) } + if p.albumKeys == nil { + p.albumKeys = make(map[string]string) + } for _, t := range found { if _, known := p.favorites[t.RatingKey]; !known { p.favorites[t.RatingKey] = t.UserRating >= 10 } + p.albumKeys[t.RatingKey] = t.AlbumKey } p.mu.Unlock() } @@ -491,6 +510,48 @@ func (p *Provider) ContinueAfter(track playlist.Track) ([]playlist.Track, error) return p.stationBatchTracks(page), nil } +// AlbumForTrack names the album of a Plex track as a list that Tracks opens. +// A restored track saved without the album key uses the one LoadFavoriteStates +// fetched. It does no I/O. +// Implements provider.TrackAlbumResolver. +func (p *Provider) AlbumForTrack(track playlist.Track) (playlist.PlaylistInfo, bool) { + trackID := plexTrackID(track) + if trackID == "" { + return playlist.PlaylistInfo{}, false + } + p.mu.Lock() + id := track.Meta(provider.MetaPlexAlbumID) + if id == "" { + id = p.albumKeys[trackID] + } + if !validRatingKey(id) { + p.mu.Unlock() + return playlist.PlaylistInfo{}, false + } + for _, l := range p.playlistCache { + if l.ID == id { + p.mu.Unlock() + return l, true + } + } + p.mu.Unlock() + name := track.Album + if track.Artist != "" { + name = track.Artist + " — " + name + } + return playlist.PlaylistInfo{ID: id, Name: name, Section: sectionAlbums}, true +} + +// ArtistFilter returns the browser filter that shows the albums of a Plex +// track's artist: the album rows start with the artist and a dash. It does +// no I/O. Implements provider.TrackArtistFilter. +func (p *Provider) ArtistFilter(track playlist.Track) (string, bool) { + if plexTrackID(track) == "" || strings.TrimSpace(track.Artist) == "" { + return "", false + } + return "^" + track.Artist + " — ", true +} + // stationLists returns the radio stations of the music sections as browser // entries, picked and ordered by the stations setting. A section whose // stations cannot be read is skipped: stations are an extra, not the library. diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index 98b0cd39a..7292cadeb 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -993,3 +993,41 @@ func TestProviderLoadFavoriteStates(t *testing.T) { t.Fatalf("second load: err %v, requests %d; want none", err, len(sent())) } } + +// A Plex track names its album as a list that Tracks opens, from its +// ProviderMeta or, for a restored track saved without it, from the metadata +// LoadFavoriteStates fetched; and it names the filter of its artist. +func TestProviderTrackAlbumAndArtist(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, `{"MediaContainer":{"Metadata":[{"ratingKey":"7","title":"Song","parentRatingKey":"70"}]}}`) + })) + defer srv.Close() + p := newProvider(NewClient(srv.URL, "tok")) + p.playlistCache = []playlist.PlaylistInfo{{ID: "60", Name: "Opeth — Damnation (2003)", Section: sectionAlbums}} + + fresh := p.convertTracks([]Track{{RatingKey: "6", Title: "Windowpane", ArtistName: "Opeth", AlbumName: "Damnation", AlbumKey: "60", PartKey: "/p/6"}}, 0)[0] + if album, ok := p.AlbumForTrack(fresh); !ok || album.Name != "Opeth — Damnation (2003)" || album.ID != "60" { + t.Fatalf("AlbumForTrack(listed) = %+v, %v; want the cached album list", album, ok) + } + + restored := playlist.Track{Path: TrackURIPrefix + "7", Artist: "Opeth", Album: "Ghost Reveries", ProviderMeta: map[string]string{provider.MetaPlexID: "7"}} + if _, ok := p.AlbumForTrack(restored); ok { + t.Fatal("AlbumForTrack found an album before any metadata") + } + if err := p.LoadFavoriteStates(t.Context(), []playlist.Track{restored}); err != nil { + t.Fatalf("LoadFavoriteStates: %v", err) + } + if album, ok := p.AlbumForTrack(restored); !ok || album.ID != "70" || album.Name != "Opeth — Ghost Reveries" { + t.Fatalf("AlbumForTrack(restored) = %+v, %v; want album 70", album, ok) + } + + if q, ok := p.ArtistFilter(fresh); !ok || q != "^Opeth — " { + t.Fatalf("ArtistFilter = %q, %v; want ^Opeth — ", q, ok) + } + for _, tr := range []playlist.Track{{Path: "/local/song.mp3", Artist: "Opeth"}, {Path: TrackURIPrefix + "8"}} { + if _, ok := p.ArtistFilter(tr); ok { + t.Fatalf("ArtistFilter(%q) found a filter", tr.Path) + } + } +} diff --git a/provider/interfaces.go b/provider/interfaces.go index 6562ca75b..ada2faeb0 100644 --- a/provider/interfaces.go +++ b/provider/interfaces.go @@ -475,6 +475,20 @@ type CodeAuthenticator interface { Authenticate(code string) error } +// TrackAlbumResolver is implemented by providers that can name the album of +// one of their tracks as one of their lists, so the UI can open the album +// from the track. AlbumForTrack must not do I/O. +type TrackAlbumResolver interface { + AlbumForTrack(track playlist.Track) (playlist.PlaylistInfo, bool) +} + +// TrackArtistFilter is implemented by providers whose list filter can show +// the lists of a track's artist, so the UI can open them from the track. +// ArtistFilter returns that filter query and must not do I/O. +type TrackArtistFilter interface { + ArtistFilter(track playlist.Track) (string, bool) +} + // QueueContinuer is implemented by providers whose lists never end, such as // radio stations, that load them in batches. When the last track of a batch // starts, the UI asks for the next batch and appends it to the queue. diff --git a/provider/types.go b/provider/types.go index cdb1d0232..d5ea8dbfc 100644 --- a/provider/types.go +++ b/provider/types.go @@ -73,6 +73,8 @@ func YearFromDate(date string) int { const ( MetaNavidromeID = "navidrome.id" MetaPlexID = "plex.id" + // MetaPlexAlbumID is the ratingKey of a Plex track's album. + MetaPlexAlbumID = "plex.album_id" MetaJellyfinID = "jellyfin.id" MetaEmbyID = "emby.id" MetaNetEaseID = "netease.id" diff --git a/ui/model/command_registry.go b/ui/model/command_registry.go index abfa51074..8d985ca96 100644 --- a/ui/model/command_registry.go +++ b/ui/model/command_registry.go @@ -160,6 +160,8 @@ var commandRegistry = []commandSpec{ } return "Browse provider" }, Enabled: func(m Model) bool { return m.canOpenProviderBrowser() }, Keymap: true, ContextHelp: true, Prominent: true}, + {Mode: commandModeMain, Keys: []string{"alt+o"}, KeyLabel: "Alt+O", Label: "Open the track's album", Enabled: func(m Model) bool { return m.canOpenTrackAlbum() }, Keymap: true}, + {Mode: commandModeMain, Keys: []string{"alt+l"}, KeyLabel: "Alt+L", Label: "List the track's artist", Enabled: func(m Model) bool { return m.canOpenTrackArtist() }, Keymap: true}, {Mode: commandModeMain, Keys: []string{"L"}, KeyLabel: "L", Label: "Open Local provider", Keymap: true}, {Mode: commandModeMain, Keys: []string{"R"}, KeyLabel: "R", Label: "Open radio provider", Keymap: true}, {Mode: commandModeMain, Keys: []string{"O"}, KeyLabel: "O", Label: "Open Podcasts provider", Keymap: true}, diff --git a/ui/model/keys.go b/ui/model/keys.go index 50dc1c60c..83d610d7a 100644 --- a/ui/model/keys.go +++ b/ui/model/keys.go @@ -283,6 +283,11 @@ func (m *Model) handleGlobalKey(msg tea.KeyPressMsg) (cmd tea.Cmd, ok bool) { } switch msg.String() { case "ctrl+z": + if m.playlistUndo.cursorPath != "" { + // Undoing a whole-queue replace puts the cursor back on its + // track, not on the row it had in the replacing queue. + return m.undoPlaylistMutation(), true + } m.keepPlCursorRow(func() { cmd = m.undoPlaylistMutation() }) return cmd, true case "ctrl+k": @@ -761,6 +766,12 @@ func (m *Model) handleMainKey(msg tea.KeyPressMsg) tea.Cmd { case "u": m.urlInput = urlInputState{active: true} + case "alt+o": + return m.openTrackAlbum() + + case "alt+l": + return m.openTrackArtist() + case "N": if cmd, ok := m.openSelectedTrackArtistBrowser(); ok { return cmd diff --git a/ui/model/playback.go b/ui/model/playback.go index 79b137c95..55ab332ab 100644 --- a/ui/model/playback.go +++ b/ui/model/playback.go @@ -390,6 +390,9 @@ func (m *Model) undoPlaylistMutation() tea.Cmd { // song mix replaced, so its album headers follow its own tracks. m.recountHeaderState(m.playlist.Tracks()) m.playlistUndo = playlistUndo{} + if i := trackIndexByPath(m.playlist.Tracks(), undo.cursorPath); undo.cursorPath != "" && i >= 0 { + m.plCursor = i + } if m.plCursor >= m.playlist.Len() { m.plCursor = max(0, m.playlist.Len()-1) } diff --git a/ui/model/providers.go b/ui/model/providers.go index c05a732a9..189c8d00f 100644 --- a/ui/model/providers.go +++ b/ui/model/providers.go @@ -152,6 +152,11 @@ func (m *Model) replaceProviderLists(lists []playlist.PlaylistInfo) { selectedID = m.provPane.lists[m.provPane.cursor].ID } m.provPane.lists = providerListsWithBrowse(m.provider, lists) + if _, catalog := m.provider.(provider.CatalogSearcher); m.provSearch.active && m.provSearch.query != "" && !catalog { + // A filter set before the lists arrived, as Alt+L sets one, applies + // to them now. + m.updateProvSearch() + } m.provPane.cursor = max(0, min(m.provPane.cursor, len(m.provPane.lists)-1)) if selectedID != "" { for i, item := range m.provPane.lists { diff --git a/ui/model/state.go b/ui/model/state.go index cce4de723..9f6b7842b 100644 --- a/ui/model/state.go +++ b/ui/model/state.go @@ -37,6 +37,9 @@ type playlistUndo struct { persisted bool removed playlist.Track savedIdx int + // cursorPath is the track the cursor returns to, for an edit that + // replaced the whole queue. + cursorPath string } // netSearchScreenType identifies which screen of the net search overlay is active. diff --git a/ui/model/track_jumps.go b/ui/model/track_jumps.go new file mode 100644 index 000000000..a6fdb25f1 --- /dev/null +++ b/ui/model/track_jumps.go @@ -0,0 +1,163 @@ +package model + +import ( + tea "charm.land/bubbletea/v2" + + "github.com/bjarneo/cliamp/playlist" + "github.com/bjarneo/cliamp/provider" +) + +// albumOpenedMsg carries the tracks of the album that Alt+O opened from the +// track at path from. +type albumOpenedMsg struct { + id uint64 + provider string + album playlist.PlaylistInfo + from string + tracks []playlist.Track + err error +} + +// selectedQueueTrack returns the highlighted playlist row while the playlist +// has focus. +func (m Model) selectedQueueTrack() (playlist.Track, bool) { + if m.focus != focusPlaylist || m.playlist == nil { + return playlist.Track{}, false + } + return m.playlist.Track(m.plCursor) +} + +// trackAlbum finds the provider that can open the album of track. +func (m Model) trackAlbum(track playlist.Track) (playlist.Provider, string, playlist.PlaylistInfo, bool) { + r, name := findCapable(&m, func(r provider.TrackAlbumResolver) bool { + _, ok := r.AlbumForTrack(track) + return ok + }) + prov, ok := r.(playlist.Provider) + if !ok { + return nil, "", playlist.PlaylistInfo{}, false + } + album, _ := r.AlbumForTrack(track) + return prov, name, album, true +} + +// trackArtistFilter finds the provider whose list filter can show the artist +// of track, and that filter. +func (m Model) trackArtistFilter(track playlist.Track) (string, string, bool) { + f, name := findCapable(&m, func(f provider.TrackArtistFilter) bool { + _, ok := f.ArtistFilter(track) + return ok + }) + if f == nil { + return "", "", false + } + query, _ := f.ArtistFilter(track) + return name, query, true +} + +func (m Model) canOpenTrackAlbum() bool { + track, ok := m.selectedQueueTrack() + if !ok { + return false + } + _, _, _, ok = m.trackAlbum(track) + return ok +} + +func (m Model) canOpenTrackArtist() bool { + track, ok := m.selectedQueueTrack() + if !ok { + return false + } + _, _, ok = m.trackArtistFilter(track) + return ok +} + +// openTrackAlbum loads the album of the highlighted track. The queue is left +// alone until its tracks arrive; any newer queue makes the answer stale. +func (m *Model) openTrackAlbum() tea.Cmd { + track, ok := m.selectedQueueTrack() + if !ok { + return nil + } + prov, name, album, ok := m.trackAlbum(track) + if !ok { + return nil + } + id := nextRequest(&m.requests.queue) + m.status.Activityf(statusTTLLong, "Opening %s...", album.Name) + return func() tea.Msg { + tracks, err := prov.Tracks(album.ID) + return albumOpenedMsg{id: id, provider: name, album: album, from: track.Path, tracks: tracks, err: err} + } +} + +// handleAlbumOpened replaces the queue with the album and puts the cursor on +// the track the jump started from. Playback goes on: a playing track on the +// album becomes its current track, and any other keeps playing until it ends. +// Ctrl+Z brings the old queue back. +func (m *Model) handleAlbumOpened(msg albumOpenedMsg) tea.Cmd { + if msg.id != m.requests.queue { + return nil + } + if msg.err != nil { + m.status.Errorf(statusTTLMedium, "Opening %s failed: %s", msg.album.Name, msg.err) + return nil + } + if len(msg.tracks) == 0 { + m.status.Warningf(statusTTLMedium, "%s has no tracks", msg.album.Name) + return nil + } + snapshot := m.playlist.Snapshot() + m.retireTracksPaging() + m.replacePlayerPlaylist(msg.tracks) + if i := trackIndexByPath(msg.tracks, m.playingTrack.Path); m.playingTrackActive && i >= 0 { + m.playlist.SetIndex(i) + m.playbackDetached = false + if t, ok := m.playlist.Track(i); ok { + m.playingTrack = t + } + } + if i := trackIndexByPath(msg.tracks, msg.from); i >= 0 { + m.plCursor = i + } + if m.isActiveProvider(msg.provider) { + m.activeProviderPlaylistID = msg.album.ID + } + m.adjustScroll() + m.status.Successf(statusTTLDefault, "Album: %s (Ctrl+Z to undo)", msg.album.Name) + m.recordPlaylistUndo(playlistUndo{snapshot: snapshot, cursorPath: msg.from}) + return m.rearmStalePreload() +} + +// openTrackArtist opens the browser of the provider that owns the highlighted +// track, filtered to the lists of its artist. The filter is an ordinary one: +// it can be edited, and Esc clears it. +func (m *Model) openTrackArtist() tea.Cmd { + track, ok := m.selectedQueueTrack() + if !ok { + return nil + } + name, query, ok := m.trackArtistFilter(track) + if !ok { + return nil + } + var cmd tea.Cmd + if !m.isActiveProvider(name) { + idx := -1 + for i, pe := range m.providers { + if pe.Name == name { + idx = i + break + } + } + if idx < 0 { + return nil + } + cmd = m.switchProvider(idx) + } + m.focus = focusProvider + m.provSearch = provSearchState{active: true, query: query} + m.updateProvSearch() + return cmd +} diff --git a/ui/model/track_jumps_test.go b/ui/model/track_jumps_test.go new file mode 100644 index 000000000..e54c5cd1a --- /dev/null +++ b/ui/model/track_jumps_test.go @@ -0,0 +1,184 @@ +package model + +import ( + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + + "github.com/bjarneo/cliamp/playlist" + "github.com/bjarneo/cliamp/provider" +) + +// fakeAlbumProvider owns "fk:" tracks: all of them are on one album, and its +// artist filter is "artist". +type fakeAlbumProvider struct { + commandsTestProvider + album []playlist.Track +} + +func (p *fakeAlbumProvider) Playlists() ([]playlist.PlaylistInfo, error) { return p.lists, nil } +func (p *fakeAlbumProvider) Tracks(id string) ([]playlist.Track, error) { + if id != "alb" { + return nil, nil + } + return p.album, nil +} +func (p *fakeAlbumProvider) AlbumForTrack(t playlist.Track) (playlist.PlaylistInfo, bool) { + if !strings.HasPrefix(t.Path, "fk:") { + return playlist.PlaylistInfo{}, false + } + return playlist.PlaylistInfo{ID: "alb", Name: "Artist — Album"}, true +} +func (p *fakeAlbumProvider) ArtistFilter(t playlist.Track) (string, bool) { + if !strings.HasPrefix(t.Path, "fk:") { + return "", false + } + return "artist", true +} + +// trackJumpModel plays x.mp3 from a queue of x.mp3, fk:2 and y.mp3, with the +// cursor on fk:2, whose album is fk:1 fk:2 fk:3. +func trackJumpModel() (Model, *playbackFakeEngine, *fakeAlbumProvider) { + player := &playbackFakeEngine{playing: true} + fake := &fakeAlbumProvider{ + commandsTestProvider: commandsTestProvider{name: "Fake", lists: []playlist.PlaylistInfo{ + {ID: "alb", Name: "Artist — Album (2001)"}, + {ID: "other", Name: "Other — Album (2002)"}, + {ID: "alb2", Name: "Artist — Second (2005)"}, + }}, + album: []playlist.Track{{Path: "fk:1"}, {Path: "fk:2"}, {Path: "fk:3"}}, + } + p := playlist.New() + p.Replace([]playlist.Track{{Path: "x.mp3"}, {Path: "fk:2"}, {Path: "y.mp3"}}) + p.SetIndex(0) + m := Model{ + player: player, + playlist: p, + providers: []provider.Entry{{Name: "Fake", Provider: fake}}, + focus: focusPlaylist, + plCursor: 1, + } + m.playingTrack, m.playingTrackActive = playlist.Track{Path: "x.mp3"}, true + return m, player, fake +} + +var ( + altO = tea.KeyPressMsg{Code: 'o', Mod: tea.ModAlt} + altL = tea.KeyPressMsg{Code: 'l', Mod: tea.ModAlt} +) + +// Alt+O replaces the queue with the album of the highlighted track, puts the +// cursor on that track, leaves playback alone and can be undone. +func TestOpenTrackAlbum(t *testing.T) { + m, player, fake := trackJumpModel() + fake.album = []playlist.Track{{Path: "fk:1"}, {Path: "fk:3"}, {Path: "fk:2"}} + + next, cmd := m.Update(altO) + m = next.(Model) + if cmd == nil { + t.Fatal("Alt+O on a track with an album started no load") + } + if got := jumpPaths(m.playlist.Tracks()); strings.Join(got, " ") != "x.mp3 fk:2 y.mp3" { + t.Fatalf("queue changed before the album arrived: %v", got) + } + next, _ = m.Update(cmd()) + m = next.(Model) + + if got := jumpPaths(m.playlist.Tracks()); strings.Join(got, " ") != "fk:1 fk:3 fk:2" { + t.Fatalf("queue = %v, want the album", got) + } + if m.plCursor != 2 || player.stopCalls != 0 || !m.playingTrackActive || m.playingTrack.Path != "x.mp3" { + t.Fatalf("cursor %d, Stop %d, playing %q (%v); want the cursor on fk:2 and x.mp3 still playing", + m.plCursor, player.stopCalls, m.playingTrack.Path, m.playingTrackActive) + } + + next, _ = m.Update(tea.KeyPressMsg{Code: 'z', Mod: tea.ModCtrl}) + m = next.(Model) + if got := jumpPaths(m.playlist.Tracks()); strings.Join(got, " ") != "x.mp3 fk:2 y.mp3" || m.plCursor != 1 { + t.Fatalf("Ctrl+Z queue = %v, cursor %d; want the old queue back with the cursor on fk:2", got, m.plCursor) + } +} + +// Ctrl+Z after Alt+O brings back the album headers of the old queue too: a +// list of single tracks from many albums shows none. +func TestOpenTrackAlbumUndoRestoresHeaders(t *testing.T) { + m, _, fake := trackJumpModel() + m.playlist.Replace([]playlist.Track{{Path: "x.mp3", Album: "X"}, {Path: "fk:2", Album: "A"}, {Path: "y.mp3", Album: "Y"}}) + m.setHeaderStateFromTracks(m.playlist.Tracks()) + fake.album = []playlist.Track{{Path: "fk:1", Album: "A"}, {Path: "fk:2", Album: "A"}, {Path: "fk:3", Album: "A"}} + + next, cmd := m.Update(altO) + m = next.(Model) + next, _ = m.Update(cmd()) + m = next.(Model) + if !m.showAlbumHeaders { + t.Fatal("the album shows no album headers") + } + next, _ = m.Update(tea.KeyPressMsg{Code: 'z', Mod: tea.ModCtrl}) + m = next.(Model) + if m.showAlbumHeaders { + t.Fatal("Ctrl+Z kept the album's headers on a list of single tracks") + } +} + +// A playing track on the album goes on as the album's current track. +func TestOpenTrackAlbumKeepsPlayingTrack(t *testing.T) { + m, player, _ := trackJumpModel() + m.playlist.SetIndex(1) + m.playingTrack = playlist.Track{Path: "fk:2"} + + next, cmd := m.Update(altO) + m = next.(Model) + next, _ = m.Update(cmd()) + m = next.(Model) + + if m.playlist.Index() != 1 || m.playbackDetached || player.stopCalls != 0 || len(player.playCalls) != 0 { + t.Fatalf("index %d, detached %v, Stop %d, playCalls %v; want fk:2 current and untouched", + m.playlist.Index(), m.playbackDetached, player.stopCalls, player.playCalls) + } +} + +// Alt+O and Alt+L do nothing on a track no provider places. +func TestTrackJumpsNeedAProvider(t *testing.T) { + m, _, _ := trackJumpModel() + m.plCursor = 0 + for _, key := range []tea.KeyPressMsg{altO, altL} { + next, cmd := m.Update(key) + if cmd != nil || next.(Model).focus != focusPlaylist { + t.Fatalf("%s on x.mp3 did something", key.String()) + } + } +} + +// Alt+L opens the owning provider with the artist filter, which applies to +// the lists once they arrive. +func TestOpenTrackArtist(t *testing.T) { + m, _, fake := trackJumpModel() + + next, _ := m.Update(altL) + m = next.(Model) + if m.focus != focusProvider || !m.isActiveProvider("Fake") { + t.Fatalf("focus %v, provider %v; want the Fake browser", m.focus, m.provider) + } + if !m.provSearch.active || m.provSearch.query != "artist" { + t.Fatalf("filter = %q (active %v), want artist", m.provSearch.query, m.provSearch.active) + } + + m.replaceProviderLists(fake.lists) + var got []string + for _, i := range m.provSearch.results { + got = append(got, m.provPane.lists[i].Name) + } + if strings.Join(got, "|") != "Artist — Album (2001)|Artist — Second (2005)" { + t.Fatalf("filtered lists = %q, want the two Artist albums", got) + } +} + +func jumpPaths(tracks []playlist.Track) []string { + out := make([]string, len(tracks)) + for i, t := range tracks { + out[i] = t.Path + } + return out +} diff --git a/ui/model/update.go b/ui/model/update.go index 532ba9696..b64f76e4e 100644 --- a/ui/model/update.go +++ b/ui/model/update.go @@ -160,6 +160,9 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { cmd := m.handleTracksLoaded(msg) return m, cmd + case albumOpenedMsg: + return m, m.handleAlbumOpened(msg) + case navArtistsLoadedMsg: m.handleNavArtistsLoaded(msg) return m, nil From 5b6ed839731227a88b9f02006652517e600c0945 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sat, 31 Oct 2026 15:45:34 +0100 Subject: [PATCH 17/32] feat(plex): save a Plex track with Ctrl+S Ctrl+S saved only yt-dlp tracks and temporary downloads, so on a Plex track it failed with "only downloaded tracks can be saved". Add provider.TrackDownloader: a provider hands over the original file of a streamed track and its extension. tracksave.SaveFrom writes it to the download directory as "Artist - Title.ext" through a hidden temporary file, so a broken download leaves no partial track, and reads nothing when that file exists. Ctrl+S and the IPC save operation try the provider first; other tracks save as before. Plex downloads the part it streams, with the token in a request header. Verified with make check (gofmt, go vet, go test ./...), new tests for SaveFrom, the Plex download and both save paths, and by saving Plex tracks in kitty. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/configuration.md | 4 +- docs/keybindings.md | 2 +- docs/plex.md | 5 +++ docs/provider-development.md | 1 + external/plex/client.go | 31 +++++++++++++++ external/plex/provider.go | 34 ++++++++++++++++ external/plex/provider_test.go | 32 +++++++++++++++ provider/interfaces.go | 9 +++++ tracksave/save.go | 61 ++++++++++++++++++++++++++--- tracksave/save_test.go | 55 ++++++++++++++++++++++++++ ui/model/commands.go | 3 +- ui/model/download_directory_test.go | 50 +++++++++++++++++++++++ ui/model/ipc_extended.go | 9 ++++- ui/model/keys.go | 22 ++++++++++- ui/model/update_playback.go | 2 + 15 files changed, 308 insertions(+), 12 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 3e09cf298..d0f526321 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -592,8 +592,8 @@ disk or network mount. ## Download directory -By default, TUI `Ctrl+S` saves yt-dlp downloads and temporary audio files in -`~/Music/cliamp`. To use another directory, add this setting and restart cliamp: +By default, TUI `Ctrl+S` saves yt-dlp downloads, temporary audio files, and the +original files of Plex tracks in `~/Music/cliamp`. To use another directory, add this setting and restart cliamp: ```toml [downloads] diff --git a/docs/keybindings.md b/docs/keybindings.md index 82cd79938..95752b499 100644 --- a/docs/keybindings.md +++ b/docs/keybindings.md @@ -133,7 +133,7 @@ and `Esc` clears it. | `[` / `]` | Adjust synced-lyrics timing offset (−/+250 ms) while lyrics show timestamped lines | | `i` | From the playlist, open full info for the highlighted item, including Path (`Up`/`Down` or `j`/`k` scroll; `i`/`Esc`/`q` closes) | | `Ctrl+I` | Toggle Metadata below Settings for the highlighted playlist item (remembered in `show_metadata`; requires a terminal that distinguishes Ctrl+I from Tab) | -| `Ctrl+S` | Save track to `[downloads].directory` (default `~/Music/cliamp`) | +| `Ctrl+S` | Save track to `[downloads].directory` (default `~/Music/cliamp`). A Plex track saves its original file; one saved before is not downloaded again | | `w` | Write the highlighted track to a local playlist | | `Alt+O` | Open the album of the highlighted track: the queue becomes the album with the cursor on that track, and playback goes on. `Ctrl+Z` brings the old queue back. Plex tracks | | `Alt+L` | Show the albums of the highlighted track's artist: open its provider browser filtered to `^Artist — `. Edit the filter as usual; `Esc` clears it. Plex tracks | diff --git a/docs/plex.md b/docs/plex.md index 63af5ce22..fe6f81da8 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -126,6 +126,11 @@ brings the old queue back. `Alt+L` opens the Plex browser filtered to the albums of the track's artist, with the filter `^Artist — `, which you can edit or clear with `Esc`. +`Ctrl+S` saves the playing Plex track: cliamp downloads its original file from +the server, the one it streams, to the [download +directory](configuration.md#download-directory) as `Artist - Title.flac` (or +the file's own extension). A track saved before is not downloaded again. + Press `Ctrl+R` while an open Plex album or playlist is focused to reload it and pick up server-side changes. Album contents are cached for up to five minutes; Plex playlists are always loaded fresh so smart playlists stay current. diff --git a/docs/provider-development.md b/docs/provider-development.md index e423c01aa..ba4668962 100644 --- a/docs/provider-development.md +++ b/docs/provider-development.md @@ -207,6 +207,7 @@ are in `provider/interfaces.go`. | `TrackFavoriteState` | Make provider metadata authoritative for a track's ♥ state. Local favorites are ignored for tracks claimed by this interface | `CanFavoriteTrack(track)`, `FavoriteState(track)` | | `TrackAlbumResolver` | Name the album of a track as one of the provider's lists, for `Alt+O`. Must not do I/O | `AlbumForTrack(track)` | | `TrackArtistFilter` | Name the list filter that shows a track's artist, for `Alt+L`. Must not do I/O | `ArtistFilter(track)` | +| `TrackDownloader` | Hand over the original file of a streamed track, for `Ctrl+S` and the `save` operation. `CanDownloadTrack` must not do I/O | `CanDownloadTrack(track)`, `OpenTrackFile(ctx, track) (io.ReadCloser, ext, error)` | | `TrackFavoriteLoader` | Fetch the ♥ state of tracks that have none, such as the start playlist restored from the last session. The UI calls it in a `tea.Cmd` at start | `LoadFavoriteStates(ctx, tracks) error` | | `CatalogLoader` | Lazy paging of a large catalog | `LoadCatalogPage(offset, limit)` | | `CatalogSearcher` | Server-side catalog search that fills the pane | `SearchCatalog(query)`, `ClearSearch()`, `IsSearching()` | diff --git a/external/plex/client.go b/external/plex/client.go index e01166fdc..48323025f 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -570,6 +570,37 @@ func (c *Client) Search(query string) ([]Track, error) { return tracks, nil } +// OpenPart opens the original file of a track part, with the token in a +// request header. The caller closes the body. +func (c *Client) OpenPart(ctx context.Context, partKey string) (io.ReadCloser, error) { + if !strings.HasPrefix(partKey, "/library/parts/") { + return nil, fmt.Errorf("plex: download: invalid part") + } + baseURL, token, err := c.endpoint(ctx) + if err != nil { + return nil, fmt.Errorf("plex: connect account server: %w", err) + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+partKey+"?download=1", nil) + if err != nil { + return nil, fmt.Errorf("plex: download: %w", err) + } + req.Header.Set("X-Plex-Product", "cliamp") + req.Header.Set("X-Plex-Client-Identifier", c.clientID) + req.Header.Set("X-Plex-Token", token) + resp, err := httpclient.Streaming.Do(req) + if err != nil { + return nil, fmt.Errorf("plex: download: server unreachable: %w", netdiag.Explain(err)) + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + resp.Body.Close() + if resp.StatusCode == http.StatusUnauthorized { + return nil, fmt.Errorf("plex: token invalid or expired") + } + return nil, fmt.Errorf("plex: download: HTTP %s", resp.Status) + } + return resp.Body, nil +} + // StreamURL returns the authenticated HTTP URL for streaming a track part. // partKey is the relative path from the Part element, e.g. "/library/parts/…/file.flac". // The token is appended as a query parameter; Plex accepts it in either header or query form. diff --git a/external/plex/provider.go b/external/plex/provider.go index 2a745b88a..c25b5e755 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -4,6 +4,8 @@ import ( "context" "errors" "fmt" + "io" + "path" "slices" "strings" "sync" @@ -52,6 +54,7 @@ var ( _ provider.TrackFavoriteLoader = (*Provider)(nil) _ provider.TrackAlbumResolver = (*Provider)(nil) _ provider.TrackArtistFilter = (*Provider)(nil) + _ provider.TrackDownloader = (*Provider)(nil) _ provider.ProgressReporter = (*Provider)(nil) _ provider.QueueContinuer = (*Provider)(nil) ) @@ -552,6 +555,37 @@ func (p *Provider) ArtistFilter(track playlist.Track) (string, bool) { return "^" + track.Artist + " — ", true } +// CanDownloadTrack reports whether track is a Plex track. It does no I/O. +// Implements provider.TrackDownloader. +func (p *Provider) CanDownloadTrack(track playlist.Track) bool { + return plexTrackID(track) != "" +} + +// OpenTrackFile opens the original file of a Plex track, the one it streams, +// and names its extension from the part path. Implements +// provider.TrackDownloader. +func (p *Provider) OpenTrackFile(ctx context.Context, track playlist.Track) (io.ReadCloser, string, error) { + id := plexTrackID(track) + if id == "" { + return nil, "", fmt.Errorf("plex: %q is not a Plex track", track.Path) + } + p.mu.Lock() + partKey := p.partKeys[id] + p.mu.Unlock() + if partKey == "" { + t, err := p.client.Track(id) + if err != nil { + return nil, "", fmt.Errorf("plex: download track %s: %w", id, err) + } + partKey = t.PartKey + } + body, err := p.client.OpenPart(ctx, partKey) + if err != nil { + return nil, "", err + } + return body, path.Ext(partKey), nil +} + // stationLists returns the radio stations of the music sections as browser // entries, picked and ordered by the stations setting. A section whose // stations cannot be read is skipped: stations are an extra, not the library. diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index 7292cadeb..5064265c9 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -3,6 +3,7 @@ package plex import ( "context" "fmt" + "io" "net/http" "net/http/httptest" "slices" @@ -1031,3 +1032,34 @@ func TestProviderTrackAlbumAndArtist(t *testing.T) { } } } + +// A Plex track downloads its original part with the token in a header, and +// names the part's extension. +func TestProviderOpenTrackFile(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/library/parts/6/66/Windowpane.flac" || r.URL.Query().Get("download") != "1" { + w.WriteHeader(http.StatusNotFound) + return + } + if r.Header.Get("X-Plex-Token") != "tok" || r.URL.Query().Get("X-Plex-Token") != "" { + t.Errorf("token header %q, query %q; want the header only", r.Header.Get("X-Plex-Token"), r.URL.Query().Get("X-Plex-Token")) + } + fmt.Fprint(w, "flac bytes") + })) + defer srv.Close() + p := newProvider(NewClient(srv.URL, "tok")) + track := p.convertTracks([]Track{{RatingKey: "6", Title: "Windowpane", PartKey: "/library/parts/6/66/Windowpane.flac"}}, 0)[0] + + if !p.CanDownloadTrack(track) || p.CanDownloadTrack(playlist.Track{Path: "/local/song.flac"}) { + t.Fatal("CanDownloadTrack should accept only Plex tracks") + } + body, ext, err := p.OpenTrackFile(t.Context(), track) + if err != nil { + t.Fatalf("OpenTrackFile: %v", err) + } + defer body.Close() + got, _ := io.ReadAll(body) + if ext != ".flac" || string(got) != "flac bytes" { + t.Fatalf("OpenTrackFile = %q, %q; want .flac and the part's bytes", ext, got) + } +} diff --git a/provider/interfaces.go b/provider/interfaces.go index ada2faeb0..101e49cb2 100644 --- a/provider/interfaces.go +++ b/provider/interfaces.go @@ -2,6 +2,7 @@ package provider import ( "context" + "io" "time" "github.com/gopxl/beep/v2" @@ -489,6 +490,14 @@ type TrackArtistFilter interface { ArtistFilter(track playlist.Track) (string, bool) } +// TrackDownloader is implemented by providers that can download the file of +// one of their streamed tracks, for Ctrl+S. CanDownloadTrack must not do I/O. +// OpenTrackFile returns the file's body and its extension, such as ".flac". +type TrackDownloader interface { + CanDownloadTrack(track playlist.Track) bool + OpenTrackFile(ctx context.Context, track playlist.Track) (io.ReadCloser, string, error) +} + // QueueContinuer is implemented by providers whose lists never end, such as // radio stations, that load them in batches. When the last track of a batch // starts, the UI asks for the next batch and appends it to the queue. diff --git a/tracksave/save.go b/tracksave/save.go index 458bce043..871bc943f 100644 --- a/tracksave/save.go +++ b/tracksave/save.go @@ -4,6 +4,7 @@ package tracksave import ( "context" "fmt" + "io" "os" "path/filepath" "strings" @@ -48,6 +49,59 @@ func SaveTo(ctx context.Context, track playlist.Track, directory string) (string if track.Stream || !insideTempDir(track.Path) { return "", fmt.Errorf("only downloaded tracks can be saved") } + destination := filepath.Join(saveDir, fileName(track)+filepath.Ext(track.Path)) + if err := fileutil.CopyFile(track.Path, destination); err != nil { + return "", err + } + return destination, nil +} + +// Opener opens the file of a streamed track, such as the original file on a +// media server, and names its extension, such as ".flac". +type Opener func(ctx context.Context, track playlist.Track) (body io.ReadCloser, ext string, err error) + +// SaveFrom saves the file that open returns for track in the configured +// directory, as "Artist - Title.ext". When that file exists, it reads nothing +// and reports existed. The download goes to a hidden temporary file first, +// so a failed one leaves no partial track behind. +func SaveFrom(ctx context.Context, track playlist.Track, directory string, open Opener) (path string, existed bool, err error) { + saveDir, err := Directory(directory) + if err != nil { + return "", false, err + } + if err := os.MkdirAll(saveDir, 0o755); err != nil { + return "", false, err + } + body, ext, err := open(ctx, track) + if err != nil { + return "", false, err + } + defer body.Close() + destination := filepath.Join(saveDir, fileName(track)+ext) + if _, err := os.Stat(destination); err == nil { + return destination, true, nil + } + tmp, err := os.CreateTemp(saveDir, ".cliamp-save-*"+ext) + if err != nil { + return "", false, err + } + defer os.Remove(tmp.Name()) + if _, err := io.Copy(tmp, body); err != nil { + tmp.Close() + return "", false, fmt.Errorf("download: %w", err) + } + if err := tmp.Close(); err != nil { + return "", false, err + } + if err := os.Rename(tmp.Name(), destination); err != nil { + return "", false, err + } + return destination, false, nil +} + +// fileName names a saved track "Artist - Title", with the characters that +// file systems reject replaced. +func fileName(track playlist.Track) string { name := track.Title if name == "" { name = strings.TrimSuffix(filepath.Base(track.Path), filepath.Ext(track.Path)) @@ -55,17 +109,12 @@ func SaveTo(ctx context.Context, track playlist.Track, directory string) (string if track.Artist != "" { name = track.Artist + " - " + name } - name = strings.Map(func(r rune) rune { + return strings.Map(func(r rune) rune { if strings.ContainsRune(`/\\:*?"<>|`, r) { return '_' } return r }, name) - destination := filepath.Join(saveDir, name+filepath.Ext(track.Path)) - if err := fileutil.CopyFile(track.Path, destination); err != nil { - return "", err - } - return destination, nil } // NeedsDownload reports whether SaveTo downloads track with yt-dlp, which can diff --git a/tracksave/save_test.go b/tracksave/save_test.go index c0c2d332a..cf4bc1e82 100644 --- a/tracksave/save_test.go +++ b/tracksave/save_test.go @@ -2,8 +2,11 @@ package tracksave import ( "context" + "errors" + "io" "os" "path/filepath" + "strings" "testing" "github.com/bjarneo/cliamp/playlist" @@ -96,3 +99,55 @@ func TestNeedsDownload(t *testing.T) { }) } } + +// failingReader fails every read, standing in for a download that breaks or +// must not be read at all. +type failingReader struct{ read *bool } + +func (r failingReader) Read([]byte) (int, error) { + *r.read = true + return 0, errors.New("connection reset") +} + +func TestSaveFrom(t *testing.T) { + dir := t.TempDir() + track := playlist.Track{Path: "plex:track:1", Title: "Windowpane", Artist: "Opeth", Stream: true} + open := func(body io.Reader) Opener { + return func(context.Context, playlist.Track) (io.ReadCloser, string, error) { + return io.NopCloser(body), ".flac", nil + } + } + want := filepath.Join(dir, "Opeth - Windowpane.flac") + + path, existed, err := SaveFrom(t.Context(), track, dir, open(strings.NewReader("audio"))) + if err != nil || existed || path != want { + t.Fatalf("SaveFrom = %q, %v, %v; want %q saved", path, existed, err, want) + } + if got, _ := os.ReadFile(want); string(got) != "audio" { + t.Fatalf("saved %q, want audio", got) + } + + // A file saved before stays as it is, and the download is not read. + var read bool + path, existed, err = SaveFrom(t.Context(), track, dir, open(failingReader{&read})) + if err != nil || !existed || path != want || read { + t.Fatalf("SaveFrom again = %q, %v, %v (read %v); want the existing file, nothing read", path, existed, err, read) + } + + // A broken download leaves neither the track nor a temporary file. + other := playlist.Track{Path: "plex:track:2", Title: "Death Whispered a Lullaby", Artist: "Opeth"} + if _, _, err := SaveFrom(t.Context(), other, dir, open(failingReader{&read})); err == nil { + t.Fatal("SaveFrom of a broken download succeeded") + } + if entries, _ := os.ReadDir(dir); len(entries) != 1 { + t.Fatalf("directory holds %d files after a broken download, want only the first track", len(entries)) + } + + // An open that fails reports its error. + failed := func(context.Context, playlist.Track) (io.ReadCloser, string, error) { + return nil, "", errors.New("offline") + } + if _, _, err := SaveFrom(t.Context(), other, dir, failed); err == nil || !strings.Contains(err.Error(), "offline") { + t.Fatalf("SaveFrom with a failing open = %v, want offline", err) + } +} diff --git a/ui/model/commands.go b/ui/model/commands.go index 391bc8c45..4268a3b20 100644 --- a/ui/model/commands.go +++ b/ui/model/commands.go @@ -136,7 +136,8 @@ type ytdlBatchMsg struct { type trackSavedMsg struct { path string err error - download bool // the save ran yt-dlp and counts as a pending download + download bool // the save downloaded and counts as a pending download + existed bool // the file was saved before, so nothing was downloaded } // — Navidrome browser message types — diff --git a/ui/model/download_directory_test.go b/ui/model/download_directory_test.go index 5ebbf77d3..f66f65b4c 100644 --- a/ui/model/download_directory_test.go +++ b/ui/model/download_directory_test.go @@ -1,6 +1,8 @@ package model import ( + "context" + "io" "os" "path/filepath" "strings" @@ -8,6 +10,7 @@ import ( "github.com/bjarneo/cliamp/ipc" "github.com/bjarneo/cliamp/playlist" + "github.com/bjarneo/cliamp/provider" ) func TestSaveUsesConfiguredDirectory(t *testing.T) { @@ -166,3 +169,50 @@ func TestSaveTrackStartsDownloadForYTDLTracks(t *testing.T) { }) } } + +// fakeDownloader streams "dl:" tracks and hands over their files as ".flac". +type fakeDownloader struct { + commandsTestProvider + opened int +} + +func (*fakeDownloader) CanDownloadTrack(t playlist.Track) bool { + return strings.HasPrefix(t.Path, "dl:") +} +func (d *fakeDownloader) OpenTrackFile(context.Context, playlist.Track) (io.ReadCloser, string, error) { + d.opened++ + return io.NopCloser(strings.NewReader("original")), ".flac", nil +} + +// Ctrl+S and IPC save a streamed track through its provider's original file, +// and a second save finds the file instead of downloading it again. +func TestSaveDownloadsProviderTrack(t *testing.T) { + directory := t.TempDir() + tracks := playlist.New() + tracks.Add(playlist.Track{Path: "dl:1", Title: "Song", Artist: "Artist", Stream: true}) + downloader := &fakeDownloader{commandsTestProvider: commandsTestProvider{name: "Fake"}} + m := Model{playlist: tracks, providers: []provider.Entry{{Name: "Fake", Provider: downloader}}} + m.SetDownloadsDirectory(directory) + + cmd := m.saveTrack() + if cmd == nil || m.save.pendingDownloads != 1 { + t.Fatalf("Ctrl+S started no download (pending %d)", m.save.pendingDownloads) + } + msg := cmd().(trackSavedMsg) + want := filepath.Join(directory, "Artist - Song.flac") + if data, _ := os.ReadFile(want); msg.err != nil || msg.existed || msg.path != want || string(data) != "original" { + t.Fatalf("saved %+v, file %q; want %s with the original file", msg, data, want) + } + + reply := make(chan ipc.Response, 1) + m.handleIPCSave(ipcSaveRequest{Reply: reply})() + if response := <-reply; !response.OK || response.Output != want { + t.Fatalf("IPC save = %+v, want %s", response, want) + } + + msg = m.saveTrack()().(trackSavedMsg) + m.handleTrackSaved(msg) + if !msg.existed || !strings.Contains(m.status.text, "Already saved to") { + t.Fatalf("second save existed=%v, status %q; want the file found", msg.existed, m.status.text) + } +} diff --git a/ui/model/ipc_extended.go b/ui/model/ipc_extended.go index bcfff9e29..23df1d96e 100644 --- a/ui/model/ipc_extended.go +++ b/ui/model/ipc_extended.go @@ -155,8 +155,15 @@ func (m *Model) handleIPCSave(request ipcSaveRequest) tea.Cmd { return nil } directory := m.downloadsDirectory + save := func(ctx context.Context, directory string) (string, bool, error) { + path, err := tracksave.SaveTo(ctx, track, directory) + return path, false, err + } + if s, ok := m.providerTrackSave(track); ok { + save = s + } return func() tea.Msg { - path, err := tracksave.SaveTo(requestContext(request.Context), track, directory) + path, _, err := save(requestContext(request.Context), directory) if err != nil { request.Reply <- ipc.Response{OK: false, Error: err.Error()} } else { diff --git a/ui/model/keys.go b/ui/model/keys.go index 83d610d7a..80667b525 100644 --- a/ui/model/keys.go +++ b/ui/model/keys.go @@ -962,18 +962,38 @@ func (m *Model) saveTrack() tea.Cmd { m.status.Warning("Nothing to save", statusTTLShort) return nil } + directory := m.downloadsDirectory + if save, ok := m.providerTrackSave(track); ok { + m.status.Clear() + m.save.startDownload() + return func() tea.Msg { + path, existed, err := save(context.Background(), directory) + return trackSavedMsg{path: path, err: err, download: true, existed: existed} + } + } download := tracksave.NeedsDownload(track) if download { m.status.Clear() m.save.startDownload() } - directory := m.downloadsDirectory return func() tea.Msg { path, err := tracksave.SaveTo(context.Background(), track, directory) return trackSavedMsg{path: path, err: err, download: download} } } +// providerTrackSave returns how to save track through the provider that +// streams it, which hands over the original file, when one can. +func (m *Model) providerTrackSave(track playlist.Track) (func(ctx context.Context, directory string) (string, bool, error), bool) { + d, _ := findCapable(m, func(d provider.TrackDownloader) bool { return d.CanDownloadTrack(track) }) + if d == nil { + return nil, false + } + return func(ctx context.Context, directory string) (string, bool, error) { + return tracksave.SaveFrom(ctx, track, directory, d.OpenTrackFile) + }, true +} + func (m *Model) openJumpMode() { m.jump = jumpState{active: true} } diff --git a/ui/model/update_playback.go b/ui/model/update_playback.go index f523e79ce..42124ba9e 100644 --- a/ui/model/update_playback.go +++ b/ui/model/update_playback.go @@ -184,6 +184,8 @@ func (m *Model) handleTrackSaved(msg trackSavedMsg) { m.save.finishDownload() } switch { + case msg.err == nil && msg.existed: + m.status.Showf(statusTTLMedium, "Already saved to %s", msg.path) case msg.err == nil: m.status.Showf(statusTTLMedium, "Saved to %s", msg.path) case msg.download: From a42355cceb89feb835a23be319fe923650006695 Mon Sep 17 00:00:00 2001 From: Igor Maliavko Date: Sun, 1 Nov 2026 16:18:24 +0100 Subject: [PATCH 18/32] fix(plex): fail over to another server route When the chosen Plex address stopped answering mid-session, every request waited for the 30 s client timeout and failed, and playback stalled on the next track until Ctrl+R picked a new route. All server requests (lists, tracks, stations, timeline reports, ratings and Ctrl+S downloads) now go through one send helper. On a network error an account-backed client drops the route, rediscovers the server through plex.tv and retries once on the best answering address. HTTP errors keep the route, and manual clients keep their URL. A response must start within 10 s; the body read is not limited. ResolveSource refreshes the route before building the stream URL, and request no longer mutates its params. Verified with make check (fmt, vet, tests) and go test -race on external/plex, including dead, hanging and HTTP 500 routes. Co-Authored-By: Claude Opus 5.5 --- docs/plex.md | 5 ++ external/plex/client.go | 160 +++++++++++++++++++++++++---------- external/plex/client_test.go | 97 +++++++++++++++++++++ external/plex/provider.go | 5 ++ 4 files changed, 220 insertions(+), 47 deletions(-) diff --git a/docs/plex.md b/docs/plex.md index fe6f81da8..9cb2219ee 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -28,6 +28,11 @@ addresses. It prefers a reachable local address, then a secure direct remote address, and finally a secure relay. Public plain-HTTP addresses are never selected. Pressing `Ctrl+R` also repeats connection discovery. +If the chosen address stops answering during a session, for example after a +network change, the next Plex request notices within about 10 seconds, asks +Plex for the current addresses again, and retries once on the best one that +answers. Playback moves on to the next track without a restart or `Ctrl+R`. + This means the same configuration can move between home and work without hard-coding a `192.168.x.x` address. Remote playback still requires the Plex server to advertise a reachable remote or relay connection. diff --git a/external/plex/client.go b/external/plex/client.go index 48323025f..316541c4c 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -12,6 +12,7 @@ import ( "sync" "time" + "github.com/bjarneo/cliamp/applog" "github.com/bjarneo/cliamp/internal/httpclient" "github.com/bjarneo/cliamp/internal/netdiag" ) @@ -86,6 +87,79 @@ func (c *Client) endpoint(ctx context.Context) (string, string, error) { return c.baseURL, c.token, nil } +// responseHeaderTimeout bounds the wait for a server's response headers on +// one attempt. A dead route then fails in seconds instead of after the full +// request timeout, and send can move to another route. Tests shorten it. +var responseHeaderTimeout = 10 * time.Second + +// send runs one request against the current server route; build makes it for +// a base URL and token. When an account-backed client cannot reach its route, +// send drops the route, rediscovers one through plex.tv and retries once, so +// a dead local, remote or relay connection does not stall playback. HTTP +// error responses are returned as they are. label names the call in errors. +func (c *Client) send(ctx context.Context, client *http.Client, label string, build func(baseURL, token string) (*http.Request, error)) (*http.Response, error) { + for retried := false; ; retried = true { + baseURL, token, err := c.endpoint(ctx) + if err != nil { + return nil, fmt.Errorf("plex: connect account server: %w", err) + } + req, err := build(baseURL, token) + if err != nil { + return nil, fmt.Errorf("plex: %s: %w", label, err) + } + resp, err := doWithHeaderDeadline(client, req) + if err == nil { + return resp, nil + } + if retried || ctx.Err() != nil || !c.dropRoute(baseURL) { + return nil, fmt.Errorf("plex: %s: server unreachable: %w", label, netdiag.Explain(err)) + } + applog.Info("plex: %s: %v; finding another server route", label, netdiag.Explain(err)) + } +} + +// dropRoute makes the next request rediscover the route when baseURL is still +// the current one. It reports whether rediscovery is possible: manual clients +// have only their configured URL. +func (c *Client) dropRoute(baseURL string) bool { + c.mu.Lock() + defer c.mu.Unlock() + if c.account == nil { + return false + } + if c.baseURL == baseURL { + c.account.connected = false + } + return true +} + +// doWithHeaderDeadline sends req and cancels it when no response headers +// arrive within responseHeaderTimeout. The body read is not limited by it. +func doWithHeaderDeadline(client *http.Client, req *http.Request) (*http.Response, error) { + ctx, cancel := context.WithCancel(req.Context()) + timer := time.AfterFunc(responseHeaderTimeout, cancel) + resp, err := client.Do(req.WithContext(ctx)) + timer.Stop() + if err != nil { + cancel() + return nil, err + } + resp.Body = cancelOnClose{ReadCloser: resp.Body, cancel: cancel} + return resp, nil +} + +// cancelOnClose releases a request context when its response body closes. +type cancelOnClose struct { + io.ReadCloser + cancel context.CancelFunc +} + +func (b cancelOnClose) Close() error { + err := b.ReadCloser.Close() + b.cancel() + return err +} + // RefreshConnection makes an account-backed client rediscover its route on // the next request. Manual clients keep their configured URL unchanged. func (c *Client) RefreshConnection() { @@ -150,26 +224,23 @@ func (c *Client) get(path string, params url.Values, result any) error { // request issues an authenticated request and decodes the JSON response into // result. func (c *Client) request(method, path string, params url.Values, result any) error { - baseURL, token, err := c.endpoint(context.Background()) - if err != nil { - return fmt.Errorf("plex: connect account server: %w", err) - } - if params == nil { - params = url.Values{} - } - params.Set("X-Plex-Token", token) - - req, err := http.NewRequest(method, baseURL+path+"?"+params.Encode(), nil) - if err != nil { - return fmt.Errorf("plex: %s: %w", path, err) - } - req.Header.Set("Accept", "application/json") - req.Header.Set("X-Plex-Product", "cliamp") - req.Header.Set("X-Plex-Client-Identifier", c.clientID) - - resp, err := apiClient.Do(req) + resp, err := c.send(context.Background(), apiClient, path, func(baseURL, token string) (*http.Request, error) { + query := url.Values{} + for k, v := range params { + query[k] = v + } + query.Set("X-Plex-Token", token) + req, err := http.NewRequest(method, baseURL+path+"?"+query.Encode(), nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + req.Header.Set("X-Plex-Product", "cliamp") + req.Header.Set("X-Plex-Client-Identifier", c.clientID) + return req, nil + }) if err != nil { - return fmt.Errorf("plex: %s: server unreachable: %w", path, netdiag.Explain(err)) + return err } defer resp.Body.Close() @@ -236,22 +307,19 @@ func (c *Client) Scrobble(ctx context.Context, ratingKey string) error { } func (c *Client) doAction(ctx context.Context, method, endpoint string, params url.Values) error { - baseURL, token, err := c.endpoint(ctx) - if err != nil { - return fmt.Errorf("plex: connect account server: %w", err) - } - req, err := http.NewRequestWithContext(ctx, method, baseURL+endpoint+"?"+params.Encode(), nil) - if err != nil { - return fmt.Errorf("plex: %s: %w", strings.TrimPrefix(endpoint, "/:/"), err) - } - req.Header.Set("Accept", "application/json") - req.Header.Set("X-Plex-Product", "cliamp") - req.Header.Set("X-Plex-Client-Identifier", c.clientID) - req.Header.Set("X-Plex-Token", token) - - resp, err := apiClient.Do(req) + resp, err := c.send(ctx, apiClient, strings.TrimPrefix(endpoint, "/:/"), func(baseURL, token string) (*http.Request, error) { + req, err := http.NewRequestWithContext(ctx, method, baseURL+endpoint+"?"+params.Encode(), nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + req.Header.Set("X-Plex-Product", "cliamp") + req.Header.Set("X-Plex-Client-Identifier", c.clientID) + req.Header.Set("X-Plex-Token", token) + return req, nil + }) if err != nil { - return fmt.Errorf("plex: %s: server unreachable: %w", strings.TrimPrefix(endpoint, "/:/"), netdiag.Explain(err)) + return err } defer resp.Body.Close() _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxResponseBody)) @@ -576,20 +644,18 @@ func (c *Client) OpenPart(ctx context.Context, partKey string) (io.ReadCloser, e if !strings.HasPrefix(partKey, "/library/parts/") { return nil, fmt.Errorf("plex: download: invalid part") } - baseURL, token, err := c.endpoint(ctx) - if err != nil { - return nil, fmt.Errorf("plex: connect account server: %w", err) - } - req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+partKey+"?download=1", nil) - if err != nil { - return nil, fmt.Errorf("plex: download: %w", err) - } - req.Header.Set("X-Plex-Product", "cliamp") - req.Header.Set("X-Plex-Client-Identifier", c.clientID) - req.Header.Set("X-Plex-Token", token) - resp, err := httpclient.Streaming.Do(req) + resp, err := c.send(ctx, httpclient.Streaming, "download", func(baseURL, token string) (*http.Request, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+partKey+"?download=1", nil) + if err != nil { + return nil, err + } + req.Header.Set("X-Plex-Product", "cliamp") + req.Header.Set("X-Plex-Client-Identifier", c.clientID) + req.Header.Set("X-Plex-Token", token) + return req, nil + }) if err != nil { - return nil, fmt.Errorf("plex: download: server unreachable: %w", netdiag.Explain(err)) + return nil, err } if resp.StatusCode < 200 || resp.StatusCode >= 300 { resp.Body.Close() diff --git a/external/plex/client_test.go b/external/plex/client_test.go index 721c080ef..d4ac54427 100644 --- a/external/plex/client_test.go +++ b/external/plex/client_test.go @@ -913,3 +913,100 @@ func TestStreamURLPlaysAnalyzedFLAC(t *testing.T) { t.Fatal("stream URL no longer routes through the buffered pipeline") } } + +// failoverFixture builds an account client whose current route is dead and +// whose plex.tv lists that route and a live one. discoveries counts the +// plex.tv lookups. +func failoverFixture(t *testing.T, dead *httptest.Server) (*Client, *httptest.Server, *int) { + t.Helper() + alive := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/identity": + w.Write([]byte(`{"MediaContainer":{"machineIdentifier":"server-1"}}`)) + case "/library/sections": + w.Write([]byte(`{"MediaContainer":{"Directory":[{"key":"3","type":"artist","title":"Music"}]}}`)) + case "/:/timeline": + w.WriteHeader(http.StatusOK) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(alive.Close) + discoveries := 0 + tv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + discoveries++ + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `[{"name":"Home","clientIdentifier":"server-1","provides":"server","owned":true,"accessToken":"server-token", + "connections":[{"uri":%q,"protocol":"http","local":true},{"uri":%q,"protocol":"http","local":true}]}]`, dead.URL, alive.URL) + })) + t.Cleanup(tv.Close) + api := &AccountAPI{baseURL: tv.URL, client: tv.Client(), pollInterval: time.Millisecond} + c := newAccountClient(dead.URL, "account-token", "client-1", "server-1", api) + // The dead route was the working one when the session found it. + c.account.connected = true + c.token = "server-token" + return c, alive, &discoveries +} + +func TestClientFailsOverFromDeadRoute(t *testing.T) { + t.Run("connection refused", func(t *testing.T) { + dead := httptest.NewServer(http.NotFoundHandler()) + dead.Close() + c, alive, discoveries := failoverFixture(t, dead) + + sections, err := c.MusicSections() + if err != nil || len(sections) != 1 { + t.Fatalf("MusicSections = %v, %v; want the live route's library", sections, err) + } + if c.baseURL != alive.URL || *discoveries != 1 { + t.Fatalf("route = %q after %d discoveries, want %q after 1", c.baseURL, *discoveries, alive.URL) + } + }) + + t.Run("no response", func(t *testing.T) { + old := responseHeaderTimeout + responseHeaderTimeout = 50 * time.Millisecond + t.Cleanup(func() { responseHeaderTimeout = old }) + dead := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + <-r.Context().Done() + })) + t.Cleanup(dead.Close) + c, alive, _ := failoverFixture(t, dead) + + start := time.Now() + if err := c.ReportTimeline(t.Context(), "42", "playing", time.Second, time.Minute); err != nil { + t.Fatalf("ReportTimeline: %v", err) + } + if c.baseURL != alive.URL { + t.Fatalf("route = %q, want %q", c.baseURL, alive.URL) + } + if elapsed := time.Since(start); elapsed > 5*time.Second { + t.Fatalf("failover took %v", elapsed) + } + }) +} + +func TestClientKeepsRouteOnHTTPError(t *testing.T) { + failing := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "boom", http.StatusInternalServerError) + })) + t.Cleanup(failing.Close) + c, _, discoveries := failoverFixture(t, failing) + + if _, err := c.MusicSections(); err == nil || !strings.Contains(err.Error(), "500") { + t.Fatalf("MusicSections error = %v, want the server's HTTP 500", err) + } + if *discoveries != 0 || c.baseURL != failing.URL { + t.Fatalf("an HTTP error rediscovered the route: %d discoveries, route %q", *discoveries, c.baseURL) + } +} + +func TestManualClientDoesNotFailOver(t *testing.T) { + dead := httptest.NewServer(http.NotFoundHandler()) + dead.Close() + _, err := NewClient(dead.URL, "tok").MusicSections() + if err == nil || !strings.Contains(err.Error(), "server unreachable") { + t.Fatalf("MusicSections error = %v, want server unreachable", err) + } +} diff --git a/external/plex/provider.go b/external/plex/provider.go index c25b5e755..59b5de483 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -327,6 +327,11 @@ func (p *Provider) ResolveSource(uri string) (string, error) { p.favorites[id] = track.UserRating >= 10 p.mu.Unlock() } + // A request that found the route dead dropped it; find the new one + // before building the stream URL on it. + if _, _, err := p.client.endpoint(context.Background()); err != nil { + return "", fmt.Errorf("plex: resolve track %s: connect account server: %w", id, err) + } return p.client.StreamURL(partKey), nil } From ffde6d8a5ddef84725560f82c7dd1dbeb22f7dac Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 1 Nov 2026 18:41:08 +0100 Subject: [PATCH 19/32] fix(plex): keep the token out of route errors When a request failed on a dead route, the failover log line and the returned error quoted the full request URL, and with it the X-Plex-Token query parameter, so the token landed in cliamp.log. A route that sent no headers in time was also reported as a bare "context canceled". send now drops the URL of a url.Error and keeps its cause, and the header deadline reports "no response in 10s". Verified with make check (fmt, vet, tests), go test -race on external/plex with a token assertion on the unreachable error, and an end-to-end run through a proxy that silenced and reset the local route: the log shows only the cause, and playback moved to the remote route. Co-Authored-By: Claude Opus 5.5 (1M context) --- external/plex/client.go | 13 +++++++++++-- external/plex/client_test.go | 17 ++++++++++++++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/external/plex/client.go b/external/plex/client.go index 316541c4c..ed4b769de 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -3,6 +3,7 @@ package plex import ( "context" + "errors" "fmt" "io" "net/http" @@ -111,6 +112,10 @@ func (c *Client) send(ctx context.Context, client *http.Client, label string, bu if err == nil { return resp, nil } + // A url.Error names the request URL, and with it the token. + if uerr, ok := errors.AsType[*url.Error](err); ok { + err = uerr.Err + } if retried || ctx.Err() != nil || !c.dropRoute(baseURL) { return nil, fmt.Errorf("plex: %s: server unreachable: %w", label, netdiag.Explain(err)) } @@ -137,11 +142,15 @@ func (c *Client) dropRoute(baseURL string) bool { // arrive within responseHeaderTimeout. The body read is not limited by it. func doWithHeaderDeadline(client *http.Client, req *http.Request) (*http.Response, error) { ctx, cancel := context.WithCancel(req.Context()) - timer := time.AfterFunc(responseHeaderTimeout, cancel) + timeout := responseHeaderTimeout + timer := time.AfterFunc(timeout, cancel) resp, err := client.Do(req.WithContext(ctx)) - timer.Stop() + fired := !timer.Stop() if err != nil { cancel() + if fired && req.Context().Err() == nil { + return nil, fmt.Errorf("no response in %s", timeout) + } return nil, err } resp.Body = cancelOnClose{ReadCloser: resp.Body, cancel: cancel} diff --git a/external/plex/client_test.go b/external/plex/client_test.go index d4ac54427..3c66b7832 100644 --- a/external/plex/client_test.go +++ b/external/plex/client_test.go @@ -974,6 +974,9 @@ func TestClientFailsOverFromDeadRoute(t *testing.T) { t.Cleanup(dead.Close) c, alive, _ := failoverFixture(t, dead) + if _, err := doWithHeaderDeadline(http.DefaultClient, mustRequest(t, dead.URL)); err == nil || err.Error() != "no response in 50ms" { + t.Fatalf("hanging route error = %v, want no response in 50ms", err) + } start := time.Now() if err := c.ReportTimeline(t.Context(), "42", "playing", time.Second, time.Minute); err != nil { t.Fatalf("ReportTimeline: %v", err) @@ -1005,8 +1008,20 @@ func TestClientKeepsRouteOnHTTPError(t *testing.T) { func TestManualClientDoesNotFailOver(t *testing.T) { dead := httptest.NewServer(http.NotFoundHandler()) dead.Close() - _, err := NewClient(dead.URL, "tok").MusicSections() + _, err := NewClient(dead.URL, "secret-token").MusicSections() if err == nil || !strings.Contains(err.Error(), "server unreachable") { t.Fatalf("MusicSections error = %v, want server unreachable", err) } + if strings.Contains(err.Error(), "secret-token") { + t.Fatalf("MusicSections error = %v names the token", err) + } +} + +func mustRequest(t *testing.T, target string) *http.Request { + t.Helper() + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, target, nil) + if err != nil { + t.Fatal(err) + } + return req } From db9d6332385239d80c59880d7b17669099db7704 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 1 Nov 2026 18:51:20 +0100 Subject: [PATCH 20/32] fix(plex): keep Ctrl+R on a restored playlist After a restart restored a Plex playlist queue, Ctrl+R in the playlist did nothing: the resume state saved the tracks but not the playlist, so the reload found no open playlist to refresh. The resume state now carries the ID of the open provider playlist when it reloads in place and the playing track comes from it, both in the periodic save and at exit, and the restore sets it again. Verified with make check (fmt, vet, tests), new tests for the saved ID, and by hand: after a restart Ctrl+R reloaded Recently Added in place. Co-Authored-By: Claude Opus 5.5 (1M context) --- internal/resume/resume.go | 3 ++ main.go | 7 +++-- main_test.go | 8 ++--- providers.go | 3 +- providers_test.go | 2 +- ui/model/init.go | 13 ++++++-- ui/model/keys.go | 1 + ui/model/model.go | 5 +++- ui/model/playback.go | 11 ++++++- ui/model/playback_context_test.go | 48 ++++++++++++++++++++++++++---- ui/model/playback_test.go | 8 ++--- ui/model/resume_checkpoint_test.go | 6 ++-- 12 files changed, 88 insertions(+), 27 deletions(-) diff --git a/internal/resume/resume.go b/internal/resume/resume.go index f9320abd9..ed221d162 100644 --- a/internal/resume/resume.go +++ b/internal/resume/resume.go @@ -19,6 +19,9 @@ type State struct { Playlist string `json:"playlist,omitempty"` Context []playlist.Track `json:"context,omitempty"` ContextIndex int `json:"context_index,omitempty"` + // PlaylistID names the provider playlist of Context when it reloads in + // place, so Ctrl+R works on the restored queue. + PlaylistID string `json:"playlist_id,omitempty"` } func stateFile() (string, error) { diff --git a/main.go b/main.go index 474d7dca2..5299e8126 100644 --- a/main.go +++ b/main.go @@ -180,6 +180,7 @@ func run(overrides config.Overrides, positional []string, headless, visualizer60 } if restoredContext { m.SetInitialTrack(restoredIndex) + m.SetProviderPlaylist(resumeState.PlaylistID) } m.SetIPCBroker(pluginBroker) if luaMgr != nil { @@ -420,16 +421,16 @@ func saveOnExit(final tea.Model, headless bool, resumeServer contextServer) { // resumeServer is set and owns the track at path, it also saves // the list that resumeContext returns. A track with no position saves // nothing. -func saveExitResume(path string, secs int, playlistName string, resumeContext func() ([]playlist.Track, int), resumeServer contextServer) { +func saveExitResume(path string, secs int, playlistName string, resumeContext func() ([]playlist.Track, int, string), resumeServer contextServer) { if path == "" || secs <= 0 { return } if resumeServer != nil { if _, ok := resumeServer.RestoreTrack(playlist.Track{Path: path}); ok { - tracks, index := resumeContext() + tracks, index, playlistID := resumeContext() resume.SaveState(resume.State{ Path: path, PositionSec: secs, Playlist: playlistName, - Context: tracks, ContextIndex: index, + Context: tracks, ContextIndex: index, PlaylistID: playlistID, }) return } diff --git a/main_test.go b/main_test.go index dec8ed93f..e0904988a 100644 --- a/main_test.go +++ b/main_test.go @@ -94,11 +94,11 @@ func TestSaveExitResume(t *testing.T) { }{ { name: "server stream", path: stream, secs: 95, server: server.Provider, tracks: tracks, useContext: true, - want: resume.State{Path: stream, PositionSec: 95, Playlist: "Mix", Context: tracks, ContextIndex: 1}, + want: resume.State{Path: stream, PositionSec: 95, Playlist: "Mix", Context: tracks, ContextIndex: 1, PlaylistID: "4242"}, }, { name: "plex track", path: plexTrack, secs: 95, server: plexServer, tracks: plexTracks, useContext: true, - want: resume.State{Path: plexTrack, PositionSec: 95, Playlist: "Mix", Context: plexTracks, ContextIndex: 1}, + want: resume.State{Path: plexTrack, PositionSec: 95, Playlist: "Mix", Context: plexTracks, ContextIndex: 1, PlaylistID: "4242"}, }, { name: "emby stream with plex server", path: stream, secs: 95, server: plexServer, @@ -121,9 +121,9 @@ func TestSaveExitResume(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Setenv("CLIAMP_CONFIG_DIR", t.TempDir()) usedContext := false - resumeContext := func() ([]playlist.Track, int) { + resumeContext := func() ([]playlist.Track, int, string) { usedContext = true - return tt.tracks, 1 + return tt.tracks, 1, "4242" } saveExitResume(tt.path, tt.secs, "Mix", resumeContext, tt.server) if got := resume.Load(); !reflect.DeepEqual(got, tt.want) { diff --git a/providers.go b/providers.go index 7afe2f37c..c7698b8e9 100644 --- a/providers.go +++ b/providers.go @@ -505,13 +505,14 @@ func (s *providerSet) observeAuthURLs(send func(tea.Msg)) (restore func()) { // serverResumeSaver saves the play context of each track that server owns, // so the next start can restore it. func serverResumeSaver(server contextServer) model.ResumeSaver { - return func(track playlist.Track, positionSec int, context []playlist.Track, contextIndex int) { + return func(track playlist.Track, positionSec int, context []playlist.Track, contextIndex int, playlistID string) { if _, ok := server.RestoreTrack(track); !ok { return } resume.SaveState(resume.State{ Path: track.Path, PositionSec: positionSec, Context: context, ContextIndex: contextIndex, + PlaylistID: playlistID, }) } } diff --git a/providers_test.go b/providers_test.go index 013bdeab1..4dd99a4f9 100644 --- a/providers_test.go +++ b/providers_test.go @@ -293,7 +293,7 @@ func TestServerResumeSaver(t *testing.T) { } { t.Run(tt.name, func(t *testing.T) { t.Setenv("CLIAMP_CONFIG_DIR", t.TempDir()) - serverResumeSaver(server.Provider)(playlist.Track{Path: tt.path, Title: "Two"}, 42, context, 1) + serverResumeSaver(server.Provider)(playlist.Track{Path: tt.path, Title: "Two"}, 42, context, 1, "") if got := resume.Load(); !reflect.DeepEqual(got, tt.want) { t.Fatalf("saved state = %+v, want %+v", got, tt.want) } diff --git a/ui/model/init.go b/ui/model/init.go index b5b044667..4a443cd27 100644 --- a/ui/model/init.go +++ b/ui/model/init.go @@ -271,6 +271,12 @@ func (m *Model) SetResume(path string, secs int) { m.resume.secs = secs } +// SetProviderPlaylist names the open provider playlist of a restored queue, +// so Ctrl+R reloads it in place. +func (m *Model) SetProviderPlaylist(id string) { + m.activeProviderPlaylistID = id +} + // SetResumeSaver enables continuous playback-context persistence. func (m *Model) SetResumeSaver(save ResumeSaver) { m.resumeSaver = save @@ -308,9 +314,10 @@ func (m Model) ResumeState() (path string, secs int, playlist string) { return m.exitResume.path, m.exitResume.secs, m.exitResume.playlist } -// ResumeContext returns the complete list the active track was selected from. -func (m Model) ResumeContext() ([]playlist.Track, int) { - return cloneTracks(m.exitResume.context), m.exitResume.contextIndex +// ResumeContext returns the complete list the active track was selected from, +// and the provider playlist it reloads from, if any. +func (m Model) ResumeContext() ([]playlist.Track, int, string) { + return cloneTracks(m.exitResume.context), m.exitResume.contextIndex, m.exitResume.playlistID } // ThemeName returns the current theme name. diff --git a/ui/model/keys.go b/ui/model/keys.go index 80667b525..56fe840b0 100644 --- a/ui/model/keys.go +++ b/ui/model/keys.go @@ -32,6 +32,7 @@ func (m *Model) quit() tea.Cmd { m.exitResume.playlist = m.loadedPlaylist m.exitResume.context = cloneTracks(context) m.exitResume.contextIndex = contextIndex + m.exitResume.playlistID = m.resumePlaylistID() } } diff --git a/ui/model/model.go b/ui/model/model.go index 5a0c695b7..cfc9f73a4 100644 --- a/ui/model/model.go +++ b/ui/model/model.go @@ -29,7 +29,9 @@ type ConfigSaver interface { } // ResumeSaver persists the active track, timeline position, and source context. -type ResumeSaver func(track playlist.Track, positionSec int, context []playlist.Track, contextIndex int) +// playlistID names the provider playlist of the context when it reloads in +// place, or is empty. +type ResumeSaver func(track playlist.Track, positionSec int, context []playlist.Track, contextIndex int, playlistID string) // The saveConfig* helpers persist a top-level config key and show a write // failure in the status line. They return the error, so an IPC job can fail @@ -476,6 +478,7 @@ type Model struct { playlist string context []playlist.Track contextIndex int + playlistID string } // preloading is true while a preloadStreamCmd goroutine is in-flight. diff --git a/ui/model/playback.go b/ui/model/playback.go index 55ab332ab..fb17adea6 100644 --- a/ui/model/playback.go +++ b/ui/model/playback.go @@ -78,6 +78,15 @@ func (m *Model) playbackContextFor(track playlist.Track) ([]playlist.Track, int) return context, trackIndexByPath(context, track.Path) } +// resumePlaylistID names the open provider playlist that the playing track +// comes from when it reloads in place, so a restored queue keeps Ctrl+R. +func (m *Model) resumePlaylistID() string { + if m.playbackDetached || !m.refreshesInPlace() { + return "" + } + return m.activeProviderPlaylistID +} + func (m *Model) persistPlaybackContext(track playlist.Track, positionSec int, now time.Time) { if m.resumeSaver == nil { return @@ -86,7 +95,7 @@ func (m *Model) persistPlaybackContext(track playlist.Track, positionSec int, no if index < 0 { return } - m.resumeSaver(track, positionSec, cloneTracks(context), index) + m.resumeSaver(track, positionSec, cloneTracks(context), index, m.resumePlaylistID()) m.lastResumeSave = now } diff --git a/ui/model/playback_context_test.go b/ui/model/playback_context_test.go index 1d72e0c9e..d3e3c6ed2 100644 --- a/ui/model/playback_context_test.go +++ b/ui/model/playback_context_test.go @@ -17,10 +17,11 @@ type savedPlaybackContext struct { tracks []playlist.Track index int position int + listID string } -func (s *savedPlaybackContext) save(track playlist.Track, position int, tracks []playlist.Track, index int) { - s.track, s.position, s.tracks, s.index = track, position, tracks, index +func (s *savedPlaybackContext) save(track playlist.Track, position int, tracks []playlist.Track, index int, playlistID string) { + s.track, s.position, s.tracks, s.index, s.listID = track, position, tracks, index, playlistID } func (s savedPlaybackContext) check(t *testing.T, tracks []playlist.Track, index int) { @@ -66,7 +67,7 @@ func TestPlaybackContextOverlappingReplacement(t *testing.T) { saved.check(t, old, 0) detached := m detached.quit() - if context, index := detached.ResumeContext(); index != 0 || !reflect.DeepEqual(context, old) { + if context, index, _ := detached.ResumeContext(); index != 0 || !reflect.DeepEqual(context, old) { t.Fatalf("detached quit context = (%+v, %d), want old source", context, index) } @@ -198,7 +199,7 @@ func TestDuplicatePlaybackContextPersistenceAndRestore(t *testing.T) { t.Fatalf("periodic save position = %d, want 17", saved.position) } m.quit() - context, index := m.ResumeContext() + context, index, _ := m.ResumeContext() if index != 2 || !reflect.DeepEqual(context, tracks) { t.Fatalf("quit context = (%+v, %d), want duplicate at index 2", context, index) } @@ -244,7 +245,7 @@ func TestSetResumeSaverPreservesPlaylistState(t *testing.T) { want := playlist.New() want.Restore(pl.Snapshot()) m := Model{playlist: pl} - m.SetResumeSaver(func(playlist.Track, int, []playlist.Track, int) {}) + m.SetResumeSaver(func(playlist.Track, int, []playlist.Track, int, string) {}) if pl.Index() != want.Index() || !pl.CurrentIsQueued() || !pl.Shuffled() || pl.Repeat() != playlist.RepeatAll || pl.QueueLen() != 1 { t.Fatal("enabling context tracking changed playback state") } @@ -269,7 +270,42 @@ func TestPlaybackContextSelectionWithoutSaver(t *testing.T) { pl.SetIndex(0) settlePlay(t, &m, m.playCurrentTrack()) m.quit() - if context, index := m.ResumeContext(); index != 0 || !reflect.DeepEqual(context, tracks) { + if context, index, _ := m.ResumeContext(); index != 0 || !reflect.DeepEqual(context, tracks) { t.Fatalf("quit context = (%+v, %d), want active duplicate at index 0", context, index) } } + +// The saved context names the open provider playlist when it reloads in +// place, so Ctrl+R works on the queue restored from it; a queue that only +// plays on beside another open playlist names none. +func TestResumeSaveNamesRefreshablePlaylist(t *testing.T) { + for _, tt := range []struct { + name string + id string + detached bool + want string + }{ + {name: "stable playlist", id: "wave", want: "wave"}, + {name: "positional ID", id: "station-3"}, + {name: "detached playback", id: "wave", detached: true}, + } { + t.Run(tt.name, func(t *testing.T) { + tracks := []playlist.Track{{Path: "a.mp3"}, {Path: "b.mp3"}} + m := keybindingTestModel() + refreshes := 0 + m.provider = refreshTestProvider{commandsTestProvider: commandsTestProvider{name: "Wave"}, refreshes: &refreshes, stable: map[string]bool{"wave": true}} + m.playlist.Replace(tracks) + m.playlist.SetIndex(1) + m.activeProviderPlaylistID = tt.id + m.playbackDetached = tt.detached + var saved savedPlaybackContext + m.SetResumeSaver(saved.save) + + m.persistPlaybackContext(tracks[1], 5, time.Now()) + + if saved.listID != tt.want { + t.Fatalf("saved playlist ID %q, want %q", saved.listID, tt.want) + } + }) + } +} diff --git a/ui/model/playback_test.go b/ui/model/playback_test.go index 2472ec0ec..87e5df903 100644 --- a/ui/model/playback_test.go +++ b/ui/model/playback_test.go @@ -319,7 +319,7 @@ func TestQuitCapturesMixcloudResumePosition(t *testing.T) { if m.exitResume.path != track.Path || m.exitResume.secs != 754 { t.Fatalf("exit resume = (%q, %d), want (%q, 754)", m.exitResume.path, m.exitResume.secs, track.Path) } - gotContext, gotIndex := m.ResumeContext() + gotContext, gotIndex, _ := m.ResumeContext() if len(gotContext) != 3 || gotIndex != 1 || gotContext[gotIndex].Path != track.Path { t.Fatalf("exit context = len:%d index:%d tracks:%+v", len(gotContext), gotIndex, gotContext) } @@ -394,7 +394,7 @@ func TestNavTrackPlaybackKeepsCompleteAlbumContext(t *testing.T) { cursor: 1, }, } - m.SetResumeSaver(func(playlist.Track, int, []playlist.Track, int) {}) + m.SetResumeSaver(func(playlist.Track, int, []playlist.Track, int, string) {}) if cmd := m.handleNavTrackListKey(tea.KeyPressMsg{Code: tea.KeyEnter}); cmd == nil { t.Fatal("handleNavTrackListKey(Enter) = nil, want playback command") @@ -418,7 +418,7 @@ func TestBeginPlaybackPersistsActualTrackAndCompleteContextImmediately(t *testin var savedTrack playlist.Track var savedContext []playlist.Track var savedIndex, savedPosition int - m.SetResumeSaver(func(track playlist.Track, positionSec int, context []playlist.Track, contextIndex int) { + m.SetResumeSaver(func(track playlist.Track, positionSec int, context []playlist.Track, contextIndex int, _ string) { savedTrack = track savedPosition = positionSec savedContext = context @@ -444,7 +444,7 @@ func TestTickResumeSavePersistsPositionAndThrottlesWrites(t *testing.T) { pl.Add(track) m := Model{player: player, playlist: pl, playingTrack: track, playingTrackActive: true, playbackContext: []playlist.Track{track}} var positions []int - m.SetResumeSaver(func(_ playlist.Track, positionSec int, _ []playlist.Track, _ int) { + m.SetResumeSaver(func(_ playlist.Track, positionSec int, _ []playlist.Track, _ int, _ string) { positions = append(positions, positionSec) }) base := time.Now() diff --git a/ui/model/resume_checkpoint_test.go b/ui/model/resume_checkpoint_test.go index e8213a2e1..ac862b9fe 100644 --- a/ui/model/resume_checkpoint_test.go +++ b/ui/model/resume_checkpoint_test.go @@ -30,7 +30,7 @@ func TestResumeCheckpointWaitsForConfirmedPlayback(t *testing.T) { buffering: tt.buffering, seek: tt.seek, cachedPos: 600 * time.Second, } var positions []int - m.SetResumeSaver(func(_ playlist.Track, seconds int, _ []playlist.Track, _ int) { + m.SetResumeSaver(func(_ playlist.Track, seconds int, _ []playlist.Track, _ int, _ string) { positions = append(positions, seconds) }) m.tickResumeSave(time.Now()) @@ -57,7 +57,7 @@ func TestResumeCheckpointAfterFailedSeek(t *testing.T) { seek: seekState{active: true, inFlight: true, targetPos: 600 * time.Second}, } position := -1 - m.SetResumeSaver(func(_ playlist.Track, seconds int, _ []playlist.Track, _ int) { position = seconds }) + m.SetResumeSaver(func(_ playlist.Track, seconds int, _ []playlist.Track, _ int, _ string) { position = seconds }) updated, _ := m.Update(seekTickMsg{target: 600 * time.Second, err: errors.New("seek failed")}) m = updated.(Model) m.tickResumeSave(time.Now()) @@ -76,7 +76,7 @@ func TestResumeCheckpointReconcilesGaplessTrackFirst(t *testing.T) { } m.SetVisualizer("none") var savedPositions []int - m.SetResumeSaver(func(track playlist.Track, seconds int, _ []playlist.Track, _ int) { + m.SetResumeSaver(func(track playlist.Track, seconds int, _ []playlist.Track, _ int, _ string) { if track.Path == jellyfinTrack.Path { savedPositions = append(savedPositions, seconds) } From 10d8bd2efbf20459aceb9e644ba569373d5ad63e Mon Sep 17 00:00:00 2001 From: maliavko Date: Sat, 7 Nov 2026 22:07:35 +0100 Subject: [PATCH 21/32] fix(plex): show pause, seek and stop on the dashboard The Plex dashboard showed a paused track as playing on: cliamp sent no timeline while paused, so Plex counted the position on. A track left before half its length, by a skip, a stop or quitting, stayed on the dashboard until its session timed out, since only the scrobble sent the stopped state. A seek showed up only with the next report, up to 15 seconds later. A new provider.TimelineReporter takes paused and stopped reports; Plex implements it. A pause and a resume are reported at once, and a paused track repeats its position every 15 seconds. A position that strays from the one the last report implies, as after a seek, is reported at once. A track left without a scrobble reports stopped. While the track buffers, no report goes out. Verified with make check (gofmt, go vet, go test ./...), new tests that fail without the fix, and against a Plex server's session list: pause, resume, seek, next, stop, quit and quit while paused. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/plex.md | 2 +- external/plex/provider.go | 22 +++- external/plex/provider_test.go | 8 +- provider/interfaces.go | 14 +++ ui/model/audiobookshelf_resume_test.go | 148 +++++++++++++++++++++++++ ui/model/model.go | 4 +- ui/model/notifications.go | 75 +++++++++++-- 7 files changed, 257 insertions(+), 16 deletions(-) diff --git a/docs/plex.md b/docs/plex.md index 9cb2219ee..fbd9c3679 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -148,7 +148,7 @@ Existing local Plex favorites are left intact but do not control that heart, so the change does not discard old data. Press `Ctrl+R` to pick up likes changed in another client while the list is open. -While a Plex track plays, cliamp reports its timeline position about every 15 seconds. After at least half of a known-duration track has played, leaving the track records one Plex play and updates Plex history. Short skips do not increment the play count. +While a Plex track plays, cliamp reports its timeline position about every 15 seconds, so the Plex dashboard shows what plays. A pause, a resume, and a seek reach Plex at once. Leaving a track, by skipping, stopping, or quitting, ends its session on the dashboard. After at least half of a known-duration track has played, leaving the track records one Plex play and updates Plex history. Short skips do not increment the play count. When Plex is the default provider (`provider = "plex"` or `--provider plex`), cliamp remembers the most recently played Plex track, its playback position, diff --git a/external/plex/provider.go b/external/plex/provider.go index 59b5de483..e2f600733 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -55,7 +55,7 @@ var ( _ provider.TrackAlbumResolver = (*Provider)(nil) _ provider.TrackArtistFilter = (*Provider)(nil) _ provider.TrackDownloader = (*Provider)(nil) - _ provider.ProgressReporter = (*Provider)(nil) + _ provider.TimelineReporter = (*Provider)(nil) _ provider.QueueContinuer = (*Provider)(nil) ) @@ -665,6 +665,26 @@ func (p *Provider) ReportProgress(track playlist.Track, position time.Duration) return p.client.ReportTimeline(context.Background(), id, "playing", position, plexTrackDuration(track)) } +// ReportPaused sends a paused timeline update, so Plex stops counting the +// position on. +func (p *Provider) ReportPaused(track playlist.Track, position time.Duration) error { + id := plexTrackID(track) + if id == "" { + return nil + } + return p.client.ReportTimeline(context.Background(), id, "paused", position, plexTrackDuration(track)) +} + +// ReportStopped sends a stopped timeline update, so Plex ends the session of +// a track left before it counts as played. +func (p *Provider) ReportStopped(track playlist.Track, position time.Duration) error { + id := plexTrackID(track) + if id == "" { + return nil + } + return p.client.ReportTimeline(context.Background(), id, "stopped", position, plexTrackDuration(track)) +} + // ReportScrobble sends a final stopped timeline and records one completed play. func (p *Provider) ReportScrobble(track playlist.Track, elapsed, duration time.Duration, _ bool) error { id := plexTrackID(track) diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index 5064265c9..3d20bcea8 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -366,10 +366,16 @@ func TestProviderPlaybackReporting(t *testing.T) { if err := p.ReportProgress(track, 30*time.Second); err != nil { t.Fatalf("ReportProgress: %v", err) } + if err := p.ReportPaused(track, 31*time.Second); err != nil { + t.Fatalf("ReportPaused: %v", err) + } + if err := p.ReportStopped(track, 32*time.Second); err != nil { + t.Fatalf("ReportStopped: %v", err) + } if err := p.ReportScrobble(track, 70*time.Second, 2*time.Minute, true); err != nil { t.Fatalf("ReportScrobble: %v", err) } - if got := strings.Join(timelineStates, ","); got != "playing,playing,stopped" { + if got := strings.Join(timelineStates, ","); got != "playing,playing,paused,stopped,stopped" { t.Fatalf("timeline states = %q", got) } if scrobbleCount != 1 { diff --git a/provider/interfaces.go b/provider/interfaces.go index 101e49cb2..ec7eef54b 100644 --- a/provider/interfaces.go +++ b/provider/interfaces.go @@ -159,6 +159,20 @@ type ProgressReporter interface { ReportProgress(track playlist.Track, position time.Duration) error } +// TimelineReporter is implemented by progress reporters whose server shows +// the state of each listen, such as a dashboard of what plays now. Without +// these reports, such a server counts a paused track on as playing, and +// keeps a track left before ReportScrobble qualifies as playing until the +// session times out. +type TimelineReporter interface { + ProgressReporter + // ReportPaused sends the position of a paused track. + ReportPaused(track playlist.Track, position time.Duration) error + // ReportStopped ends the listen of a track that was left at position + // without a scrobble. + ReportStopped(track playlist.Track, position time.Duration) error +} + // TrackPosition is implemented by providers that can report where a single // track should resume from. type TrackPosition interface { diff --git a/ui/model/audiobookshelf_resume_test.go b/ui/model/audiobookshelf_resume_test.go index bdc2b41e7..16090ce0b 100644 --- a/ui/model/audiobookshelf_resume_test.go +++ b/ui/model/audiobookshelf_resume_test.go @@ -237,3 +237,151 @@ func TestTickProgressReportSkipsWhenPaused(t *testing.T) { case <-time.After(50 * time.Millisecond): } } + +// timelineProv records the reports of a TimelineReporter as "kind position". +type timelineProv struct { + progressProv + timeline chan string +} + +func newTimelineProv() *timelineProv { + return &timelineProv{progressProv: progressProv{reports: make(chan time.Duration, 8)}, timeline: make(chan string, 8)} +} + +func (p *timelineProv) ReportProgress(_ playlist.Track, position time.Duration) error { + p.timeline <- "playing " + position.String() + return nil +} + +func (p *timelineProv) ReportPaused(_ playlist.Track, position time.Duration) error { + p.timeline <- "paused " + position.String() + return nil +} + +func (p *timelineProv) ReportStopped(_ playlist.Track, position time.Duration) error { + p.timeline <- "stopped " + position.String() + return nil +} + +func (p *timelineProv) ReportScrobble(_ playlist.Track, elapsed, _ time.Duration, _ bool) error { + p.timeline <- "scrobble " + elapsed.String() + return nil +} + +// expect fails unless the next report is want, or, for want "", unless no +// report comes. +func (p *timelineProv) expect(t *testing.T, want string) { + t.Helper() + if want == "" { + select { + case got := <-p.timeline: + t.Fatalf("unexpected report %q", got) + case <-time.After(50 * time.Millisecond): + } + return + } + select { + case got := <-p.timeline: + if got != want { + t.Fatalf("report = %q, want %q", got, want) + } + case <-time.After(time.Second): + t.Fatalf("no report, want %q", want) + } +} + +func timelineModel(prov *timelineProv, engine *playbackFakeEngine) Model { + return Model{ + player: engine, + provider: prov, + providers: []provider.Entry{{Key: "stub", Name: "Plain", Provider: prov}}, + playingTrack: stubTracks()[0], + playingTrackActive: true, + playingTrackStarted: true, + } +} + +// A TimelineReporter hears of a pause and of the resume at once, inside the +// throttle window, and gets the paused position after it. +func TestTickProgressReportsPause(t *testing.T) { + prov := newTimelineProv() + engine := &playbackFakeEngine{playing: true, position: 10 * time.Second} + m := timelineModel(prov, engine) + + now := time.Now() + m.tickProgressReport(now) + prov.expect(t, "playing 10s") + + engine.paused = true + m.tickProgressReport(now.Add(time.Second)) + prov.expect(t, "paused 10s") + m.tickProgressReport(now.Add(2 * time.Second)) + prov.expect(t, "") + m.tickProgressReport(now.Add(time.Second + progressReportInterval)) + prov.expect(t, "paused 10s") + + engine.paused = false + m.tickProgressReport(now.Add(2*time.Second + progressReportInterval)) + prov.expect(t, "playing 10s") +} + +// A seek reports the new position at once; the position moving on with +// playback, at the playback speed, waits for the interval. +func TestTickProgressReportsSeek(t *testing.T) { + for _, tt := range []struct { + name string + speed float64 + paused bool + at time.Duration // position one second after the first report + want string + }{ + {name: "plays on", at: 11 * time.Second}, + {name: "plays on faster", speed: 2, at: 12 * time.Second}, + {name: "seek forward", at: 70 * time.Second, want: "playing 1m10s"}, + {name: "seek back", at: 3 * time.Second, want: "playing 3s"}, + {name: "seek while paused", paused: true, at: 70 * time.Second, want: "paused 1m10s"}, + } { + t.Run(tt.name, func(t *testing.T) { + prov := newTimelineProv() + engine := &playbackFakeEngine{playing: true, paused: tt.paused, position: 10 * time.Second, speed: tt.speed} + m := timelineModel(prov, engine) + now := time.Now() + m.tickProgressReport(now) + <-prov.timeline + engine.position = tt.at + m.tickProgressReport(now.Add(time.Second)) + prov.expect(t, tt.want) + }) + } +} + +// No report goes out while the track buffers. +func TestTickProgressReportWaitsForBuffering(t *testing.T) { + prov := newTimelineProv() + m := timelineModel(prov, &playbackFakeEngine{playing: true}) + m.buffering = true + m.tickProgressReport(time.Now()) + prov.expect(t, "") +} + +// Leaving a track scrobbles it past half its length; before that, a +// TimelineReporter hears that the listen stopped, so the server does not +// show it as playing on. +func TestLeaveTrackEndsListen(t *testing.T) { + for _, tt := range []struct { + name string + elapsed time.Duration + want string + }{ + {name: "skipped early", elapsed: 20 * time.Second, want: "stopped 20s"}, + {name: "played past half", elapsed: 150 * time.Second, want: "scrobble 2m30s"}, + } { + t.Run(tt.name, func(t *testing.T) { + prov := newTimelineProv() + m := timelineModel(prov, &playbackFakeEngine{playing: true}) + m.leaveTrack(tt.elapsed, 200*time.Second) + prov.expect(t, tt.want) + prov.expect(t, "") + }) + } +} diff --git a/ui/model/model.go b/ui/model/model.go index cfc9f73a4..afa494706 100644 --- a/ui/model/model.go +++ b/ui/model/model.go @@ -446,7 +446,9 @@ type Model struct { resumeSaver ResumeSaver lastResumeSave time.Time - lastProgressReport time.Time // last interim provider progress report + lastProgressReport time.Time // last interim provider progress report + progressPos time.Duration // position in that report + progressPaused bool // the last report said the track was paused // loadedPlaylist names the saved local list that the queue mirrors, for // resume. When it is set, the ♥ rule treats station rows as tracks. diff --git a/ui/model/notifications.go b/ui/model/notifications.go index 849174b0c..b3cdf4529 100644 --- a/ui/model/notifications.go +++ b/ui/model/notifications.go @@ -228,6 +228,8 @@ func (m *Model) nowPlaying(track playlist.Track) { } canSeek := m.player.Seekable() position := m.player.Position() + // The now-playing report is the first position report of the listen. + m.lastProgressReport, m.progressPos, m.progressPaused = time.Now(), position, false m.queueReport("", func() { if err := reporter.ReportNowPlaying(track, position, canSeek); err != nil { applog.Warn("now-playing report failed for %q: %v", track.Title, err) @@ -290,14 +292,15 @@ func (m *Model) refreshHistoryViews() tea.Cmd { // maybeScrobble fires a playback-complete report for the given track when it // is left (skip, stop, natural end) and past 50% of its known duration, // matching Last.fm-style play-count conventions. Local history is recorded -// separately at track start via recordListenedTrack. -func (m *Model) maybeScrobble(track playlist.Track, elapsed, duration time.Duration) { +// separately at track start via recordListenedTrack. It reports whether a +// provider got the scrobble. +func (m *Model) maybeScrobble(track playlist.Track, elapsed, duration time.Duration) bool { if duration <= 0 { // Unknown duration: use DurationSecs metadata as fallback. duration = time.Duration(track.DurationSecs) * time.Second } if duration <= 0 || elapsed < duration/2 { - return // unknown duration, or less than 50% played + return false // unknown duration, or less than 50% played } // Emit scrobble event to Lua plugins for all tracks (not just Navidrome). @@ -309,7 +312,7 @@ func (m *Model) maybeScrobble(track playlist.Track, elapsed, duration time.Durat reporter := m.findPlaybackReporter(track) if reporter == nil { - return + return false } canSeek := m.player.Seekable() m.queueReport("", func() { @@ -317,10 +320,26 @@ func (m *Model) maybeScrobble(track playlist.Track, elapsed, duration time.Durat applog.Warn("scrobble failed for %q: %v", track.Title, err) } }) + return true +} + +// reportStopped ends the listen of track at position on a provider that +// shows each listen, for a track left without a scrobble. +func (m *Model) reportStopped(track playlist.Track, position time.Duration) { + reporter, ok := m.findPlaybackReporter(track).(provider.TimelineReporter) + if !ok { + return + } + m.queueReport("", func() { + if err := reporter.ReportStopped(track, position); err != nil { + applog.Warn("stop report failed for %q: %v", track.Title, err) + } + }) } // leaveTrack reports that the listener left the track that plays after -// elapsed of dur, and scrobbles it when it qualifies. stopPlayback and +// elapsed of dur: it scrobbles it when it qualifies, and otherwise ends the +// listen on a provider that shows it. stopPlayback and // playTrack call it with the engine position before the engine moves on. // It reports only a track that the engine started, and each start once, so // a stop or a start that follows the end of a track does not report the @@ -330,7 +349,11 @@ func (m *Model) leaveTrack(elapsed, dur time.Duration) { return } m.playingTrackLeft = true - m.maybeScrobble(m.playingTrack, elapsed, dur) + // A replay of the track after a rewind reports its position at once. + m.lastProgressReport, m.progressPaused = time.Time{}, false + if !m.maybeScrobble(m.playingTrack, elapsed, dur) { + m.reportStopped(m.playingTrack, elapsed) + } } // findTrackPosition returns the provider that can report track's saved @@ -351,13 +374,24 @@ func (m *Model) findPlaybackReporter(track playlist.Track) provider.PlaybackRepo // pushed to providers that accept them. const progressReportInterval = 15 * time.Second +// progressJump is how far the position may stray from the one the last +// report implies before a report goes out at once, as after a seek. +const progressJump = 2 * time.Second + // tickProgressReport pushes an interim position update for the playing track to -// providers that accept them, at most once per progressReportInterval. +// providers that accept them, at most once per progressReportInterval, and at +// once after a seek. A TimelineReporter also hears of a pause and a resume at +// once and keeps getting the paused position; the others hear nothing while +// paused. No report goes out while the track buffers, since its position +// is not settled yet. func (m *Model) tickProgressReport(now time.Time) { - if m.player == nil || !m.player.IsPlaying() || m.player.IsPaused() { + if m.player == nil || !m.player.IsPlaying() || m.buffering { return } - if !m.lastProgressReport.IsZero() && now.Sub(m.lastProgressReport) < progressReportInterval { + paused := m.player.IsPaused() + position := m.player.Position() + due := m.lastProgressReport.IsZero() || now.Sub(m.lastProgressReport) >= progressReportInterval + if !due && paused == m.progressPaused && !m.progressJumped(now, position) { return } track, idx := m.currentPlaybackTrack() @@ -368,15 +402,32 @@ func (m *Model) tickProgressReport(now time.Time) { if !ok { return } - m.lastProgressReport = now - position := m.player.Position() + report := reporter.ReportProgress + if paused { + timeline, ok := reporter.(provider.TimelineReporter) + if !ok { + return + } + report = timeline.ReportPaused + } + m.lastProgressReport, m.progressPos, m.progressPaused = now, position, paused m.queueReport(track.Path, func() { - if err := reporter.ReportProgress(track, position); err != nil { + if err := report(track, position); err != nil { applog.Warn("progress report failed for %q: %v", track.Title, err) } }) } +// progressJumped reports whether position strays from the one the last +// report implies at now by more than progressJump. +func (m *Model) progressJumped(now time.Time, position time.Duration) bool { + want := m.progressPos + if !m.progressPaused { + want += time.Duration(float64(now.Sub(m.lastProgressReport)) * m.player.Speed()) + } + return position > want+progressJump || position < want-progressJump +} + // hasPlaybackState reports whether any provider stores local listening state, // so a render pass can decide whether to reserve the played-marker column. func (m Model) hasPlaybackState() bool { From 0cb4c12ba1060fccf38d60e62417c56983beba93 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 8 Nov 2026 14:27:03 +0100 Subject: [PATCH 22/32] fix(plex): show the length of a track to resume A restored Plex track waits paused at its saved position until it plays. The time status showed "01:35 / LIVE" for it, because the engine cannot seek a stream it does not play yet, and an unseekable stream counted as live. The status now shows LIVE only when no resume is pending, so the restored track shows "01:35 / 05:00" and a radio stream still shows LIVE. TestTimeStatusOfPendingResumeStream covers both and fails without the fix. Verified with make check (fmt, vet, tests). Co-Authored-By: Claude Opus 5.5 (1M context) --- ui/model/tick_test.go | 31 +++++++++++++++++++++++++++++++ ui/model/view.go | 4 +++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/ui/model/tick_test.go b/ui/model/tick_test.go index fcc1938a7..88c6815dd 100644 --- a/ui/model/tick_test.go +++ b/ui/model/tick_test.go @@ -3,6 +3,7 @@ package model import ( "math" "os" + "strings" "testing" "time" @@ -10,6 +11,7 @@ import ( "github.com/bjarneo/cliamp/ui" tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" ) type stereoFakeEngine struct { @@ -658,3 +660,32 @@ func TestTickSampleClockShowsPendingResume(t *testing.T) { }) } } + +// A streamed track waiting to resume shows its length, not LIVE: the engine +// cannot seek it only because it does not play it yet. A live stream still +// shows LIVE. +func TestTimeStatusOfPendingResumeStream(t *testing.T) { + saved := playlist.Track{Path: "plex:track:200", Title: "Saved", DurationSecs: 300, Stream: true} + for _, tt := range []struct { + name string + resume int + want string + }{ + {name: "waiting to resume", resume: 95, want: "01:35 / 05:00"}, + {name: "live stream", want: "00:00 / LIVE"}, + } { + t.Run(tt.name, func(t *testing.T) { + pl := playlist.New() + pl.Replace([]playlist.Track{saved}) + pl.SetIndex(0) + m := New(&playbackFakeEngine{}, pl, nil, "", nil, nil, nil, nil, nil, nil) + if tt.resume > 0 { + m.SetResume(saved.Path, tt.resume) + } + m.tickSampleClock() + if got := ansi.Strip(m.renderTimeStatus()); !strings.Contains(got, tt.want) { + t.Fatalf("time status = %q, want %q", got, tt.want) + } + }) + } +} diff --git a/ui/model/view.go b/ui/model/view.go index 83f3c1f4f..21ce3d695 100644 --- a/ui/model/view.go +++ b/ui/model/view.go @@ -633,8 +633,10 @@ func (m Model) renderTimeStatus() string { timeStr := fmt.Sprintf("%02d:%02d / %02d:%02d", posMin, posSec, durMin, durSec) + // A streamed track waiting to resume is not live: the engine cannot seek + // it only because it does not play it yet. track, _ := m.currentPlaybackTrack() - if track.Stream && !m.player.Seekable() { + if _, _, pending := m.pendingResumeClock(); !pending && track.Stream && !m.player.Seekable() { timeStr = fmt.Sprintf("%02d:%02d / LIVE", posMin, posSec) } From 7772cc41f97b848b8dfdbb43c005f43e662f9f8f Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 8 Nov 2026 14:49:37 +0100 Subject: [PATCH 23/32] fix(plex): check the server before using a route The route probe sent the server token to /identity on every advertised address, plain-HTTP local ones included, and took any 2xx answer. On another network a host that owns the same LAN address got the token, and became the route if it answered. The probe now sends no token: /identity needs no sign-in. It reads the machineIdentifier of the answer and takes the route only when it is the selected server. TestReachableConnectionChecksServerIdentity fails without the fix. Checked live: the real server still connects over plex.direct. Verified with make check (fmt, vet, tests). Co-Authored-By: Claude Opus 5.5 (1M context) --- external/plex/account.go | 22 +++++++-- external/plex/account_test.go | 93 ++++++++++++++++++++++++++++------- 2 files changed, 93 insertions(+), 22 deletions(-) diff --git a/external/plex/account.go b/external/plex/account.go index aa7c459c5..fdfd21726 100644 --- a/external/plex/account.go +++ b/external/plex/account.go @@ -283,7 +283,7 @@ func (a *AccountAPI) ReachableConnection(ctx context.Context, server AccountServ results <- probeResult{ connection: connection, rank: connectionRank(connection), - err: a.probe(requestCtx, connection.URI, token, clientID), + err: a.probe(requestCtx, connection.URI, server.ClientIdentifier, clientID), } }() } @@ -344,21 +344,35 @@ func looksLikeServerURL(raw string) bool { return err == nil && u.Host != "" && (u.Scheme == "http" || u.Scheme == "https") } -func (a *AccountAPI) probe(ctx context.Context, baseURL, token, clientID string) error { +// probe checks that baseURL answers as the server serverID. It sends no +// token: a plain-HTTP local address can belong to another host on another +// network, and /identity needs no sign-in. +func (a *AccountAPI) probe(ctx context.Context, baseURL, serverID, clientID string) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/identity", nil) if err != nil { return err } - setAccountHeaders(req, clientID, token) + setAccountHeaders(req, clientID, "") resp, err := a.client.Do(req) if err != nil { return err } defer resp.Body.Close() - _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxResponseBody)) if resp.StatusCode < 200 || resp.StatusCode >= 300 { + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxResponseBody)) return fmt.Errorf("HTTP %s", resp.Status) } + var identity struct { + MediaContainer struct { + MachineIdentifier string `json:"machineIdentifier"` + } `json:"MediaContainer"` + } + if err := httpclient.ReadJSON(resp.Body, maxResponseBody, &identity); err != nil { + return err + } + if got := identity.MediaContainer.MachineIdentifier; got == "" || got != serverID { + return fmt.Errorf("answers as server %q, not %q", got, serverID) + } return nil } diff --git a/external/plex/account_test.go b/external/plex/account_test.go index 1190cb8f9..9a7a8ed5e 100644 --- a/external/plex/account_test.go +++ b/external/plex/account_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "net/http" "net/http/httptest" "strings" @@ -84,21 +85,26 @@ func TestAccountServersFiltersAndSorts(t *testing.T) { } } +// identityHandler answers /identity as the server machineID. +func identityHandler(machineID string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"MediaContainer":{"machineIdentifier":%q}}`, machineID) + } +} + func TestReachableConnectionPrefersLocal(t *testing.T) { - secure := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) + secure := httptest.NewTLSServer(identityHandler("server-1")) defer secure.Close() - local := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) + local := httptest.NewServer(identityHandler("server-1")) defer local.Close() api := &AccountAPI{baseURL: "unused", client: secure.Client(), pollInterval: time.Millisecond} server := AccountServer{ - Name: "Home", - AccessToken: "server-token", + Name: "Home", + ClientIdentifier: "server-1", + AccessToken: "server-token", Connections: []AccountConnection{ {URI: local.URL, Protocol: "http", Local: true}, {URI: secure.URL, Protocol: "https"}, @@ -119,15 +125,14 @@ func TestReachableConnectionDoesNotWaitForSlowLocalAddress(t *testing.T) { })) defer local.Close() - remote := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) + remote := httptest.NewTLSServer(identityHandler("server-1")) defer remote.Close() api := &AccountAPI{baseURL: "unused", client: remote.Client(), pollInterval: time.Millisecond} started := time.Now() connection, _, err := api.ReachableConnection(t.Context(), AccountServer{ - Name: "Home", + Name: "Home", + ClientIdentifier: "server-1", Connections: []AccountConnection{ {URI: local.URL, Protocol: "http", Local: true}, {URI: remote.URL, Protocol: "https"}, @@ -146,13 +151,10 @@ func TestReachableConnectionDoesNotWaitForSlowLocalAddress(t *testing.T) { func TestReachableConnectionFallsBackToRemoteHTTPS(t *testing.T) { secure := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if got := r.Header.Get("X-Plex-Token"); got != "server-token" { - t.Errorf("token = %q, want server-token", got) - } if got := r.Header.Get("X-Plex-Client-Identifier"); got != "client-1" { t.Errorf("client identifier = %q, want client-1", got) } - w.WriteHeader(http.StatusOK) + identityHandler("server-1")(w, r) })) defer secure.Close() @@ -163,8 +165,9 @@ func TestReachableConnectionFallsBackToRemoteHTTPS(t *testing.T) { api := &AccountAPI{baseURL: "unused", client: secure.Client(), pollInterval: time.Millisecond} server := AccountServer{ - Name: "Home", - AccessToken: "server-token", + Name: "Home", + ClientIdentifier: "server-1", + AccessToken: "server-token", Connections: []AccountConnection{ {URI: local.URL, Protocol: "http", Local: true}, {URI: secure.URL, Protocol: "https"}, @@ -195,6 +198,60 @@ func TestReachableConnectionRejectsPublicHTTP(t *testing.T) { } } +// TestReachableConnectionChecksServerIdentity keeps the token from a host +// that holds the local address on another network: the probe sends no token, +// and a host that answers as another server is not a route. +func TestReachableConnectionChecksServerIdentity(t *testing.T) { + probe := func(w http.ResponseWriter, r *http.Request, machineID string) { + if got := r.Header.Get("X-Plex-Token"); got != "" { + t.Errorf("probe of %s sent token %q", machineID, got) + } + identityHandler(machineID)(w, r) + } + stranger := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + probe(w, r, "other-server") + })) + defer stranger.Close() + remote := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + probe(w, r, "server-1") + })) + defer remote.Close() + + tests := []struct { + name string + connections []AccountConnection + want string + }{ + {"skips a stranger", []AccountConnection{ + {URI: stranger.URL, Protocol: "http", Local: true}, + {URI: remote.URL, Protocol: "https"}, + }, remote.URL}, + {"only a stranger", []AccountConnection{ + {URI: stranger.URL, Protocol: "http", Local: true}, + }, ""}, + } + api := &AccountAPI{baseURL: "unused", client: remote.Client(), pollInterval: time.Millisecond} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + connection, _, err := api.ReachableConnection(t.Context(), AccountServer{ + Name: "Home", + ClientIdentifier: "server-1", + AccessToken: "server-token", + Connections: tt.connections, + }, "account-token", "client-1") + if tt.want == "" { + if err == nil { + t.Fatalf("connection = %+v, want an error", connection) + } + return + } + if err != nil || connection.URI != tt.want { + t.Fatalf("connection = %+v, err = %v, want %s", connection, err, tt.want) + } + }) + } +} + func TestNewClientIdentifier(t *testing.T) { a, err := NewClientIdentifier() if err != nil { From 90df5ad2d4d3836b43b4a6fa6003be003e4259ad Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 8 Nov 2026 14:49:49 +0100 Subject: [PATCH 24/32] fix(plex): do not resend a write after a timeout send retried any request on another route after a transport error. A request that timed out waiting for headers may already have reached the server, so a scrobble could count a play twice and a station could start a second play queue. A read is still retried. A write is retried only when it never left this computer, a dial error. The route is dropped either way, so the next request finds a live one. TestClientDoesNotResendWriteAfterTimeout fails without the fix. Verified with make check (fmt, vet, tests). Co-Authored-By: Claude Opus 5.5 (1M context) --- external/plex/client.go | 14 ++++++++++++- external/plex/client_test.go | 40 +++++++++++++++++++++++++++++++----- 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/external/plex/client.go b/external/plex/client.go index ed4b769de..0e0acef8b 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io" + "net" "net/http" "net/url" "strconv" @@ -116,13 +117,24 @@ func (c *Client) send(ctx context.Context, client *http.Client, label string, bu if uerr, ok := errors.AsType[*url.Error](err); ok { err = uerr.Err } - if retried || ctx.Err() != nil || !c.dropRoute(baseURL) { + if retried || ctx.Err() != nil || !c.dropRoute(baseURL) || !retrySafe(req.Method, err) { return nil, fmt.Errorf("plex: %s: server unreachable: %w", label, netdiag.Explain(err)) } applog.Info("plex: %s: %v; finding another server route", label, netdiag.Explain(err)) } } +// retrySafe reports whether a failed request may be sent again. A read may. +// A write, such as a scrobble or a new play queue, may only when it never left +// this computer: after a timeout the server may already have applied it. +func retrySafe(method string, err error) bool { + if method == http.MethodGet || method == http.MethodHead { + return true + } + opErr, ok := errors.AsType[*net.OpError](err) + return ok && opErr.Op == "dial" +} + // dropRoute makes the next request rediscover the route when baseURL is still // the current one. It reports whether rediscovery is possible: manual clients // have only their configured URL. diff --git a/external/plex/client_test.go b/external/plex/client_test.go index 3c66b7832..83322f5a1 100644 --- a/external/plex/client_test.go +++ b/external/plex/client_test.go @@ -9,6 +9,7 @@ import ( "slices" "strconv" "strings" + "sync/atomic" "testing" "time" @@ -812,10 +813,10 @@ func TestAccountClientRediscoversSelectedServer(t *testing.T) { t.Errorf("server client identifier = %q, want client-1", got) } if r.URL.Path == "/identity" { - if got := r.Header.Get("X-Plex-Token"); got != "server-token" { - t.Errorf("probe token = %q, want server-token", got) + if got := r.Header.Get("X-Plex-Token"); got != "" { + t.Errorf("probe token = %q, want none", got) } - w.WriteHeader(http.StatusOK) + identityHandler("server-1")(w, r) return } if got := r.URL.Query().Get("X-Plex-Token"); got != "server-token" { @@ -978,8 +979,8 @@ func TestClientFailsOverFromDeadRoute(t *testing.T) { t.Fatalf("hanging route error = %v, want no response in 50ms", err) } start := time.Now() - if err := c.ReportTimeline(t.Context(), "42", "playing", time.Second, time.Minute); err != nil { - t.Fatalf("ReportTimeline: %v", err) + if _, err := c.MusicSections(); err != nil { + t.Fatalf("MusicSections: %v", err) } if c.baseURL != alive.URL { t.Fatalf("route = %q, want %q", c.baseURL, alive.URL) @@ -990,6 +991,35 @@ func TestClientFailsOverFromDeadRoute(t *testing.T) { }) } +// TestClientDoesNotResendWriteAfterTimeout keeps a play from counting twice: +// a route that took a scrobble and never answered may have applied it. +func TestClientDoesNotResendWriteAfterTimeout(t *testing.T) { + old := responseHeaderTimeout + responseHeaderTimeout = 50 * time.Millisecond + t.Cleanup(func() { responseHeaderTimeout = old }) + var scrobbles atomic.Int32 + hanging := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/:/scrobble" { + scrobbles.Add(1) + } + <-r.Context().Done() + })) + t.Cleanup(hanging.Close) + c, alive, _ := failoverFixture(t, hanging) + + // A resend would reach the live route, which does not know /:/scrobble. + if err := c.Scrobble(t.Context(), "42"); err == nil || !strings.Contains(err.Error(), "no response") { + t.Fatalf("Scrobble error = %v, want no response", err) + } + if n := scrobbles.Load(); n != 1 { + t.Fatalf("scrobbles sent = %d, want 1", n) + } + // The route is dropped all the same, so the next request finds another. + if _, err := c.MusicSections(); err != nil || c.baseURL != alive.URL { + t.Fatalf("MusicSections = %v on route %q, want %q", err, c.baseURL, alive.URL) + } +} + func TestClientKeepsRouteOnHTTPError(t *testing.T) { failing := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "boom", http.StatusInternalServerError) From e15e78d1e50101b89e1556726abe337c13eb3b88 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 8 Nov 2026 14:49:51 +0100 Subject: [PATCH 25/32] fix(plex): keep queue likes across Ctrl+R Refresh drops the provider's favorite states. A queue track that no listing reloaded then showed no heart, and f liked it again instead of clearing the like. Ctrl+R now also loads the favorite states of the queue tracks, as the start does for a restored queue. TestRefreshReloadsTrackFavorites fails without the fix. Verified with make check (fmt, vet, tests). Co-Authored-By: Claude Opus 5.5 (1M context) --- ui/model/favorites_test.go | 19 +++++++++++++++++++ ui/model/providers.go | 7 +++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/ui/model/favorites_test.go b/ui/model/favorites_test.go index 83f8581cf..02e416a2e 100644 --- a/ui/model/favorites_test.go +++ b/ui/model/favorites_test.go @@ -758,3 +758,22 @@ func TestLoadTrackFavoritesCmd(t *testing.T) { t.Fatalf("loaded = %v, want the two tracks once", loader.loaded) } } + +// Refresh drops a provider's favorite states, so Ctrl+R loads them again for +// the queue tracks that no listing reloads. +func TestRefreshReloadsTrackFavorites(t *testing.T) { + loader := &fakeFavoriteLoader{commandsTestProvider: commandsTestProvider{name: "Plex"}} + refreshes := 0 + m := keybindingTestModel() + m.provider = refresherOnlyProvider{commandsTestProvider: commandsTestProvider{name: "Plex"}, refreshes: &refreshes} + m.providers = []provider.Entry{{Name: "Plex", Provider: loader}} + m.playlist.Add(playlist.Track{Path: "plex:track:1"}) + + runCmd(m.refreshActiveProvider(false)) + if refreshes != 1 { + t.Fatalf("refreshes = %d, want 1", refreshes) + } + if len(loader.loaded) != 1 || strings.Join(loader.loaded[0], " ") != "plex:track:1" { + t.Fatalf("loaded = %v, want the queue track once", loader.loaded) + } +} diff --git a/ui/model/providers.go b/ui/model/providers.go index 189c8d00f..923fac637 100644 --- a/ui/model/providers.go +++ b/ui/model/providers.go @@ -235,11 +235,14 @@ func (m *Model) refreshActiveProvider(tracksOnly bool) tea.Cmd { // arrival finds a stale cache and refetches. m.radioListenersAt = time.Time{} m.status.Activityf(statusTTLShort, "Refreshing %s…", m.provider.Name()) + // Refresh drops the favorite states too. The queue tracks that no + // listing reloads get theirs back, so a ♥ does not vanish. + favorites := m.loadTrackFavoritesCmd(m.playlist.Tracks()) if inPlace { - return m.fetchProviderTracks(m.activeProviderPlaylistID) + return tea.Batch(m.fetchProviderTracks(m.activeProviderPlaylistID), favorites) } m.activeProviderPlaylistID = "" - return m.fetchProviderPlaylists() + return tea.Batch(m.fetchProviderPlaylists(), favorites) } // applyTracksResume positions the cursor on the in-progress track and arms the From a5c454e84a7b7a7d32ffb6f997c2f52d5ca68c56 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 8 Nov 2026 14:49:54 +0100 Subject: [PATCH 26/32] fix(plex): preload a station's next batch at once The next batch of a station was appended without a preload; the next tick started it. A batch that arrived just before the last track ended could miss the gapless transition. Appending a batch now re-arms the preload, as every other queue edit does. TestQueueContinuedArmsNextTrack fails without the fix. Verified with make check (fmt, vet, tests). Co-Authored-By: Claude Opus 5.5 (1M context) --- ui/model/preload_stale_test.go | 14 ++++++++++++++ ui/model/queue_continue.go | 11 +++++++---- ui/model/update.go | 3 +-- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/ui/model/preload_stale_test.go b/ui/model/preload_stale_test.go index 8ee8ccd91..dd00f0a5b 100644 --- a/ui/model/preload_stale_test.go +++ b/ui/model/preload_stale_test.go @@ -131,6 +131,20 @@ func TestPreloadNextKeepsAnInFlightPreload(t *testing.T) { } } +// The next batch of a station arrives while its last track plays. Its first +// track is preloaded at once, so the end of the batch stays gapless. +func TestQueueContinuedArmsNextTrack(t *testing.T) { + m, player := armedModel() + m.playlist.SetIndex(2) + player.hasPreload, m.preloadFor = false, "" + + next, _ := m.Update(queueContinuedMsg{after: "c.mp3", tracks: []playlist.Track{{Title: "D", Path: "d.mp3", DurationSecs: 180}}}) + m = next.(Model) + if !m.preloading || m.preloadFor != "d.mp3" { + t.Fatalf("preloading %v for %q, want d.mp3 in flight at once", m.preloading, m.preloadFor) + } +} + // Appending over IPC while the last track plays with repeat-all puts the new // track next instead of the first one. func TestUpdateDropsStalePreloadOnRepeatAllAppend(t *testing.T) { diff --git a/ui/model/queue_continue.go b/ui/model/queue_continue.go index cc27ded82..9b1c66d23 100644 --- a/ui/model/queue_continue.go +++ b/ui/model/queue_continue.go @@ -38,17 +38,20 @@ func (m *Model) continueQueueCmd(track playlist.Track) tea.Cmd { // handleQueueContinued appends the next batch when the queue still ends with // the track it continues; a queue replaced in the meantime keeps its content. -func (m *Model) handleQueueContinued(msg queueContinuedMsg) { +// The first new track is preloaded at once: the batch can arrive just before +// the last track ends. +func (m *Model) handleQueueContinued(msg queueContinuedMsg) tea.Cmd { if msg.err != nil { applog.Warn("continue queue: %v", msg.err) - return + return nil } if len(msg.tracks) == 0 || m.playlist == nil { - return + return nil } tracks := m.playlist.Tracks() if len(tracks) == 0 || tracks[len(tracks)-1].Path != msg.after { - return + return nil } m.playlist.Add(msg.tracks...) + return m.rearmStalePreload() } diff --git a/ui/model/update.go b/ui/model/update.go index b64f76e4e..b696e859f 100644 --- a/ui/model/update.go +++ b/ui/model/update.go @@ -188,8 +188,7 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil case queueContinuedMsg: - m.handleQueueContinued(msg) - return m, nil + return m, m.handleQueueContinued(msg) case ytdlBatchMsg: cmd := m.handleYTDLBatch(msg) From 20bc72c9ea6f6cf5b9e43a4e1ae47e6b35768717 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 8 Nov 2026 14:49:56 +0100 Subject: [PATCH 27/32] fix(plex): close the replaced playlist on Alt+O Alt+O replaces the queue with an album, but kept the open provider playlist when the album's provider was not the active one. Ctrl+R then reloaded that playlist over the album, and the resume context saved it. Ctrl+Z after Alt+O had the same problem the other way: the album stayed the open playlist under the restored queue. Alt+O now clears the open playlist unless the album's provider is active, and Ctrl+Z reopens the replaced one while its provider is still active. TestOpenTrackAlbumOpenPlaylist fails without the fix. Verified with make check (fmt, vet, tests). Co-Authored-By: Claude Opus 5.5 (1M context) --- ui/model/playback.go | 6 +++++ ui/model/state.go | 5 ++++ ui/model/track_jumps.go | 10 +++++++- ui/model/track_jumps_test.go | 45 ++++++++++++++++++++++++++++++++++++ 4 files changed, 65 insertions(+), 1 deletion(-) diff --git a/ui/model/playback.go b/ui/model/playback.go index fb17adea6..991e02c98 100644 --- a/ui/model/playback.go +++ b/ui/model/playback.go @@ -399,6 +399,12 @@ func (m *Model) undoPlaylistMutation() tea.Cmd { // song mix replaced, so its album headers follow its own tracks. m.recountHeaderState(m.playlist.Tracks()) m.playlistUndo = playlistUndo{} + if undo.providerName != "" { + m.activeProviderPlaylistID = "" + if m.isActiveProvider(undo.providerName) { + m.activeProviderPlaylistID = undo.providerPlaylistID + } + } if i := trackIndexByPath(m.playlist.Tracks(), undo.cursorPath); undo.cursorPath != "" && i >= 0 { m.plCursor = i } diff --git a/ui/model/state.go b/ui/model/state.go index 9f6b7842b..223f77fd3 100644 --- a/ui/model/state.go +++ b/ui/model/state.go @@ -40,6 +40,11 @@ type playlistUndo struct { // cursorPath is the track the cursor returns to, for an edit that // replaced the whole queue. cursorPath string + // providerName and providerPlaylistID name the open provider playlist + // that an edit replacing the whole queue closed. Undo reopens it while + // that provider is still the active one. + providerName string + providerPlaylistID string } // netSearchScreenType identifies which screen of the net search overlay is active. diff --git a/ui/model/track_jumps.go b/ui/model/track_jumps.go index a6fdb25f1..3022567d7 100644 --- a/ui/model/track_jumps.go +++ b/ui/model/track_jumps.go @@ -109,6 +109,10 @@ func (m *Model) handleAlbumOpened(msg albumOpenedMsg) tea.Cmd { return nil } snapshot := m.playlist.Snapshot() + undo := playlistUndo{snapshot: snapshot, cursorPath: msg.from, providerPlaylistID: m.activeProviderPlaylistID} + if m.provider != nil { + undo.providerName = m.provider.Name() + } m.retireTracksPaging() m.replacePlayerPlaylist(msg.tracks) if i := trackIndexByPath(msg.tracks, m.playingTrack.Path); m.playingTrackActive && i >= 0 { @@ -121,12 +125,16 @@ func (m *Model) handleAlbumOpened(msg albumOpenedMsg) tea.Cmd { if i := trackIndexByPath(msg.tracks, msg.from); i >= 0 { m.plCursor = i } + // The queue is the album now, so the open playlist is the album, or none + // when the album's provider is not the active one: Ctrl+R and the saved + // resume context must not bring back the playlist the album replaced. + m.activeProviderPlaylistID = "" if m.isActiveProvider(msg.provider) { m.activeProviderPlaylistID = msg.album.ID } m.adjustScroll() m.status.Successf(statusTTLDefault, "Album: %s (Ctrl+Z to undo)", msg.album.Name) - m.recordPlaylistUndo(playlistUndo{snapshot: snapshot, cursorPath: msg.from}) + m.recordPlaylistUndo(undo) return m.rearmStalePreload() } diff --git a/ui/model/track_jumps_test.go b/ui/model/track_jumps_test.go index e54c5cd1a..899c584af 100644 --- a/ui/model/track_jumps_test.go +++ b/ui/model/track_jumps_test.go @@ -100,6 +100,51 @@ func TestOpenTrackAlbum(t *testing.T) { } } +// Alt+O makes the album the open provider playlist, or none when its +// provider is not the active one, so Ctrl+R and the resume context do not +// bring back the replaced playlist. Ctrl+Z reopens that playlist while its +// provider is still active. +func TestOpenTrackAlbumOpenPlaylist(t *testing.T) { + navidrome := commandsTestProvider{name: "Navidrome"} + tests := []struct { + name string + active string // "fake" or "navidrome" + switchTo bool // another provider becomes active before Ctrl+Z + wantAlbum string + wantUndo string + }{ + {name: "album provider active", active: "fake", wantAlbum: "alb", wantUndo: "pl-x"}, + {name: "other provider active", active: "navidrome", wantAlbum: "", wantUndo: "pl-x"}, + {name: "provider switched before undo", active: "navidrome", switchTo: true, wantAlbum: "", wantUndo: ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m, _, fake := trackJumpModel() + m.provider = fake + if tt.active == "navidrome" { + m.provider = navidrome + } + m.activeProviderPlaylistID = "pl-x" + + next, cmd := m.Update(altO) + m = next.(Model) + next, _ = m.Update(cmd()) + m = next.(Model) + if m.activeProviderPlaylistID != tt.wantAlbum { + t.Fatalf("open playlist after Alt+O = %q, want %q", m.activeProviderPlaylistID, tt.wantAlbum) + } + if tt.switchTo { + m.provider = commandsTestProvider{name: "Radio"} + } + next, _ = m.Update(tea.KeyPressMsg{Code: 'z', Mod: tea.ModCtrl}) + m = next.(Model) + if m.activeProviderPlaylistID != tt.wantUndo { + t.Fatalf("open playlist after Ctrl+Z = %q, want %q", m.activeProviderPlaylistID, tt.wantUndo) + } + }) + } +} + // Ctrl+Z after Alt+O brings back the album headers of the old queue too: a // list of single tracks from many albums shows none. func TestOpenTrackAlbumUndoRestoresHeaders(t *testing.T) { From 3f9a67e0780dff0c9ad94811cd380f7f82aaae0e Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 8 Nov 2026 14:49:59 +0100 Subject: [PATCH 28/32] docs(plex): name the scope of Alt+O and the new APIs The Alt+O and Alt+L rows ended with the fragment "Plex tracks". They now say that only Plex tracks have an album or artist to open and that the keys do nothing on other tracks. The capability table lacked TimelineReporter and QueueContinuer; both rows are added. Verified with make check (fmt, vet, tests). Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/keybindings.md | 4 ++-- docs/provider-development.md | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/keybindings.md b/docs/keybindings.md index 95752b499..3daeedefc 100644 --- a/docs/keybindings.md +++ b/docs/keybindings.md @@ -135,8 +135,8 @@ and `Esc` clears it. | `Ctrl+I` | Toggle Metadata below Settings for the highlighted playlist item (remembered in `show_metadata`; requires a terminal that distinguishes Ctrl+I from Tab) | | `Ctrl+S` | Save track to `[downloads].directory` (default `~/Music/cliamp`). A Plex track saves its original file; one saved before is not downloaded again | | `w` | Write the highlighted track to a local playlist | -| `Alt+O` | Open the album of the highlighted track: the queue becomes the album with the cursor on that track, and playback goes on. `Ctrl+Z` brings the old queue back. Plex tracks | -| `Alt+L` | Show the albums of the highlighted track's artist: open its provider browser filtered to `^Artist — `. Edit the filter as usual; `Esc` clears it. Plex tracks | +| `Alt+O` | Open the album of the highlighted track: the queue becomes the album with the cursor on that track, and playback goes on. `Ctrl+Z` brings the old queue back. Only Plex tracks have an album to open; on other tracks the key does nothing | +| `Alt+L` | Show the albums of the highlighted track's artist: open its provider browser filtered to `^Artist — `. Edit the filter as usual; `Esc` clears it. Only Plex tracks name their artist this way; on other tracks the key does nothing | | `N` | Open the active provider browser. On a selected Mixcloud show, open that creator's Uploads/Favorites. In the radio pane, open the country browser. | | `L` | Open Local provider | | `R` | Open radio provider | diff --git a/docs/provider-development.md b/docs/provider-development.md index ba4668962..c5400541b 100644 --- a/docs/provider-development.md +++ b/docs/provider-development.md @@ -183,6 +183,7 @@ are in `provider/interfaces.go`. | `AlbumTrackLoader` | Album track listing | `AlbumTracks(albumID)` | | `PlaybackReporter` | Playback reporting at track start and finish | `CanReportPlayback(track)`, `ReportNowPlaying(track, position, canSeek) error`, `ReportScrobble(track, elapsed, duration, canSeek) error` | | `ProgressReporter` | Interim position updates while playing, in addition to the start and finish reports of `PlaybackReporter` | `ReportProgress(track, position) error` | +| `TimelineReporter` | A `ProgressReporter` whose server shows the state of each listen. The UI reports a pause, a resume or a seek at once, and ends a listen left without a scrobble | `ReportPaused(track, position) error`, `ReportStopped(track, position) error` | | `TrackPosition` | Server-side position for one track, read on every play | `CanTrackPosition(track)`, `TrackPosition(track)` | | `ResumeTarget` | Server-side resume position of a playlist | `ResumeTarget(playlistID, tracks)` | | `PlaybackStateReporter` | Played and in-progress markers from local state. It must do no I/O | `HasPlaybackState()`, `PlaybackState(track)` | @@ -200,6 +201,7 @@ are in `provider/interfaces.go`. | `PlaylistDocumenter` | Snapshot and restore a playlist document for undo | `PlaylistDocument(name)`, `RestorePlaylistDocument(name, data)` | | `PlaylistDirSourceManager` | Directory sources of a playlist | `DirSources`, `AddDirSource`, `RemoveDirSource`, `SetDirRecursive` | | `TrackPager` | Fill the queue one page at a time | `TracksPage(playlistID, offset)` | +| `QueueContinuer` | Lists that never end, such as radio stations, loaded in batches. When the last track of a batch starts, the UI appends the next batch. `CanContinueAfter` must not do I/O | `CanContinueAfter(track)`, `ContinueAfter(track)` | | `CustomStreamer` | Custom URI decode pipeline | `URISchemes()`, `NewStreamer(uri)` | | `FavoriteToggler` | Favorite toggling for provider list items, such as stations and shows | `ToggleFavorite(id)` | | `TrackFavoriter` | Copy the ♥ favorite of a track to the service, such as liked or starred songs. The UI calls it in a `tea.Cmd` and keeps the local favorite when it fails | `CanFavoriteTrack(track)`, `SetTrackFavorite(ctx, track, favorite) error` | From cce1fb9193a4190afd8d2eff42dc626e873fd1f7 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 8 Nov 2026 16:24:51 +0100 Subject: [PATCH 29/32] fix(plex): load an unknown like before toggling it Right after start or Ctrl+R, the like of a queue track loads in the background. An f pressed before it arrived took the unknown state as not liked and liked a liked track again. While the state is unknown, f now loads it for that track and asks to press again; the next f toggles the loaded state. A failed load is retried by the next f. TestUnknownProviderFavoriteLoadsBeforeToggle fails without the fix. docs/plex.md describes it. Verified with make check (fmt, vet, tests). Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/plex.md | 4 ++- ui/model/favorites.go | 20 +++++++++++++++ ui/model/favorites_test.go | 50 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 1 deletion(-) diff --git a/docs/plex.md b/docs/plex.md index fbd9c3679..5c4dccc4f 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -146,7 +146,9 @@ clients. Plex is the source of truth for these hearts. cliamp neither reads nor writes its local `favorites.toml` entry when it draws or toggles a Plex heart. Existing local Plex favorites are left intact but do not control that heart, so the change does not discard old data. Press `Ctrl+R` to pick up likes changed -in another client while the list is open. +in another client while the list is open. Until the like of a track has loaded, +right after start or `Ctrl+R`, `f` asks the server for it instead of changing +it; press `f` again to change it. While a Plex track plays, cliamp reports its timeline position about every 15 seconds, so the Plex dashboard shows what plays. A pause, a resume, and a seek reach Plex at once. Leaving a track, by skipping, stopping, or quitting, ends its session on the dashboard. After at least half of a known-duration track has played, leaving the track records one Plex play and updates Plex history. Short skips do not increment the play count. diff --git a/ui/model/favorites.go b/ui/model/favorites.go index 71a24ad95..13f356548 100644 --- a/ui/model/favorites.go +++ b/ui/model/favorites.go @@ -48,6 +48,12 @@ func (m *Model) favoriteTrackKey(track playlist.Track) tea.Cmd { // Other providers receive a copy of the local favorite change. func (m *Model) toggleTrackFavorite(track playlist.Track) (tea.Cmd, error) { if current, providerOwned := m.providerTrackFavoriteState(track); providerOwned { + if m.trackFavoriteUnknown(track) { + // Toggling an unknown state could like a liked track again. The + // state loads first, and the next f toggles it. + m.status.Warning("Loading the favorite state, press again", statusTTLMedium) + return m.loadTrackFavoritesCmd([]playlist.Track{track}), nil + } favorite := !current cmd := m.syncTrackFavoriteCmd(track, favorite) if cmd == nil { @@ -110,6 +116,20 @@ func (m *Model) providerTrackFavoriteState(track playlist.Track) (favorite, prov return favorite, true } +// trackFavoriteUnknown reports whether the provider that owns the ♥ state of +// track has not loaded it yet, such as just after Ctrl+R or at start. +func (m *Model) trackFavoriteUnknown(track playlist.Track) bool { + state, _ := findCapable(m, func(s provider.TrackFavoriteState) bool { return s.CanFavoriteTrack(track) }) + if state == nil { + return false + } + if _, ok := m.pendingTrackFavorites[track.Path]; ok { + return false + } + _, known := state.FavoriteState(track) + return !known +} + // syncTrackFavoriteCmd copies a favorite change to the provider that owns // track. It returns nil when no provider keeps its own favorite state. The // network call runs in the command, never in Update. The sync queue keeps diff --git a/ui/model/favorites_test.go b/ui/model/favorites_test.go index 02e416a2e..cc2c78ebd 100644 --- a/ui/model/favorites_test.go +++ b/ui/model/favorites_test.go @@ -777,3 +777,53 @@ func TestRefreshReloadsTrackFavorites(t *testing.T) { t.Fatalf("loaded = %v, want the queue track once", loader.loaded) } } + +// loadingAuthoritativeFavoriter knows the ♥ state of a track only after +// LoadFavoriteStates fetched it from server. +type loadingAuthoritativeFavoriter struct { + *fakeAuthoritativeFavoriter + server map[string]bool +} + +func (p *loadingAuthoritativeFavoriter) LoadFavoriteStates(_ context.Context, tracks []playlist.Track) error { + p.mu.Lock() + defer p.mu.Unlock() + if p.liked == nil { + p.liked = make(map[string]bool) + } + for _, t := range tracks { + if liked, ok := p.server[t.Path]; ok { + p.liked[t.Path] = liked + } + } + return nil +} + +// f on a track whose ♥ state has not loaded yet, such as just after Ctrl+R, +// loads it instead of toggling: a liked track would be liked again. The next +// f toggles the loaded state. +func TestUnknownProviderFavoriteLoadsBeforeToggle(t *testing.T) { + m, _ := favoriteKeyTestModel(t) + track := playlist.Track{Path: "fake:track:1", Title: "Remote"} + fake := &loadingAuthoritativeFavoriter{ + fakeAuthoritativeFavoriter: &fakeAuthoritativeFavoriter{fakeTrackFavoriter: &fakeTrackFavoriter{ + commandsTestProvider: commandsTestProvider{name: "Fake"}, + prefix: "fake:", + }}, + server: map[string]bool{track.Path: true}, + } + m.providers = append(m.providers, provider.Entry{Key: "fake", Name: "Fake", Provider: fake}) + + runCmd(m.favoriteTrackKey(track)) + if got := fake.recorded(); len(got) != 0 { + t.Fatalf("provider calls = %v, want none before the state loads", got) + } + if !m.playlistTrackFavorited(track) { + t.Fatal("the loaded state shows no ♥") + } + + runCmd(m.favoriteTrackKey(track)) + if got := fake.recorded(); len(got) != 1 || got[0] != "remove "+track.Path { + t.Fatalf("provider calls = %v, want one remove", got) + } +} From 1bd85013f9eb7ec23f6c35187e5d02ed9c44cee5 Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 8 Nov 2026 16:53:55 +0100 Subject: [PATCH 30/32] fix(plex): give removed tracks a known like Plex answers a metadata batch with 404 when none of its keys exists, such as the tracks of an album removed from the server. The whole batch then failed, its likes stayed unknown, and f on those tracks asked to press again forever. TracksByKey now treats that 404 as no tracks, and LoadFavoriteStates marks a requested track the server left out as not liked. TestProviderLoadFavoriteStatesOfRemovedTracks covers the partial and the empty batch and fails without the fix. Checked live: a restored queue of 100 removed tracks and one live one loads with no error and no unknown like. Verified with make check (fmt, vet, tests). Co-Authored-By: Claude Opus 5.5 (1M context) --- external/plex/client.go | 13 ++++++++- external/plex/provider.go | 7 +++++ external/plex/provider_test.go | 49 ++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 1 deletion(-) diff --git a/external/plex/client.go b/external/plex/client.go index 0e0acef8b..ac0332024 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -237,6 +237,9 @@ type Playlist struct { Smart bool } +// errNotFound reports an HTTP 404: the server has no such item. +var errNotFound = errors.New("HTTP 404 Not Found") + // get issues an authenticated GET request and decodes the JSON response into result. func (c *Client) get(path string, params url.Values, result any) error { return c.request(http.MethodGet, path, params, result) @@ -270,6 +273,8 @@ func (c *Client) request(method, path string, params url.Values, result any) err // ok case http.StatusUnauthorized: return fmt.Errorf("plex: token invalid or expired") + case http.StatusNotFound: + return fmt.Errorf("plex: %s: %w", path, errNotFound) default: return fmt.Errorf("plex: %s: HTTP %s", path, resp.Status) } @@ -623,7 +628,13 @@ func (c *Client) TracksByKey(ratingKeys []string) ([]Track, error) { Metadata []trackJSON `json:"Metadata"` } `json:"MediaContainer"` } - if err := c.get("/library/metadata/"+strings.Join(ratingKeys, ","), nil, &result); err != nil { + err := c.get("/library/metadata/"+strings.Join(ratingKeys, ","), nil, &result) + if errors.Is(err, errNotFound) { + // Plex answers 404 only when none of the keys exists; a batch with + // some removed tracks returns the others. + return nil, nil + } + if err != nil { return nil, err } tracks := make([]Track, 0, len(result.MediaContainer.Metadata)) diff --git a/external/plex/provider.go b/external/plex/provider.go index e2f600733..c2a2fbf97 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -425,6 +425,13 @@ func (p *Provider) LoadFavoriteStates(ctx context.Context, tracks []playlist.Tra } p.albumKeys[t.RatingKey] = t.AlbumKey } + // A track removed from the server has no like. Its state is known, + // so f does not wait for a state that never loads. + for _, id := range batch { + if _, known := p.favorites[id]; !known { + p.favorites[id] = false + } + } p.mu.Unlock() } return nil diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index 3d20bcea8..2edecdb9b 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -1001,6 +1001,55 @@ func TestProviderLoadFavoriteStates(t *testing.T) { } } +// A track removed from the server has no like, and its state is known. Plex +// leaves removed keys out of a batch, and answers 404 when none of them +// exists, as the real server does. +func TestProviderLoadFavoriteStatesOfRemovedTracks(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + keys, _ := strings.CutPrefix(r.URL.Path, "/library/metadata/") + var items []string + for _, k := range strings.Split(keys, ",") { + if k == "1" { + items = append(items, `{"ratingKey":"1","title":"T1","userRating":10}`) + } + } + if len(items) == 0 { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"MediaContainer":{"Metadata":[%s]}}`, strings.Join(items, ",")) + })) + defer srv.Close() + + tests := []struct { + name string + ids []string + liked map[string]bool + }{ + {"some removed", []string{"1", "2"}, map[string]bool{"1": true, "2": false}}, + {"all removed", []string{"2", "3"}, map[string]bool{"2": false, "3": false}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + p := newProvider(NewClient(srv.URL, "tok")) + var tracks []playlist.Track + for _, id := range tt.ids { + tracks = append(tracks, playlist.Track{Path: TrackURIPrefix + id}) + } + if err := p.LoadFavoriteStates(t.Context(), tracks); err != nil { + t.Fatalf("LoadFavoriteStates: %v", err) + } + for id, want := range tt.liked { + got, known := p.FavoriteState(playlist.Track{Path: TrackURIPrefix + id}) + if !known || got != want { + t.Errorf("FavoriteState(%s) = %v, %v; want %v, true", id, got, known, want) + } + } + }) + } +} + // A Plex track names its album as a list that Tracks opens, from its // ProviderMeta or, for a restored track saved without it, from the metadata // LoadFavoriteStates fetched; and it names the filter of its artist. From 0d524cd791101da8620bd1cde48de2d166cfda6f Mon Sep 17 00:00:00 2001 From: maliavko Date: Sun, 8 Nov 2026 16:54:04 +0100 Subject: [PATCH 31/32] docs(plex): refresh station likes from the browser A station is a new play queue each time, so Ctrl+R in its queue does nothing. docs/plex.md now says to press Ctrl+R in the Plex browser to pick up likes changed in another client. Verified with make check (fmt, vet, tests). Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/plex.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/plex.md b/docs/plex.md index 5c4dccc4f..a71a231c9 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -146,7 +146,8 @@ clients. Plex is the source of truth for these hearts. cliamp neither reads nor writes its local `favorites.toml` entry when it draws or toggles a Plex heart. Existing local Plex favorites are left intact but do not control that heart, so the change does not discard old data. Press `Ctrl+R` to pick up likes changed -in another client while the list is open. Until the like of a track has loaded, +in another client while the list is open. A station is a new play queue each +time, so `Ctrl+R` in its queue does nothing; press it in the Plex browser. Until the like of a track has loaded, right after start or `Ctrl+R`, `f` asks the server for it instead of changing it; press `f` again to change it. From 8d2c7f5061e995957fc3f950e7988a19702689f2 Mon Sep 17 00:00:00 2001 From: maliavko Date: Wed, 18 Nov 2026 19:01:02 +0100 Subject: [PATCH 32/32] revert(plex): drop the Ctrl+S save of Plex tracks The maintainer decided in #699 that cliamp adds no new download features, so the Ctrl+S save of Plex files and the TrackDownloader interface leave this branch. This reverts 5b6ed839. Ctrl+S, the save operation and tracksave are as on upstream main again; Plex no longer implements TrackDownloader and its client has no OpenPart. The docs drop the Plex save. Verified: make check (fmt, vet, tests) and staticcheck; tracksave and the save paths in ui/model match upstream/main. Co-Authored-By: Claude Opus 5.5 --- docs/configuration.md | 4 +- docs/keybindings.md | 2 +- docs/plex.md | 5 --- docs/provider-development.md | 1 - external/plex/client.go | 29 -------------- external/plex/provider.go | 34 ---------------- external/plex/provider_test.go | 32 --------------- provider/interfaces.go | 9 ----- tracksave/save.go | 61 +++-------------------------- tracksave/save_test.go | 55 -------------------------- ui/model/commands.go | 3 +- ui/model/download_directory_test.go | 50 ----------------------- ui/model/ipc_extended.go | 9 +---- ui/model/keys.go | 22 +---------- ui/model/update_playback.go | 2 - 15 files changed, 12 insertions(+), 306 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 654d244ab..1cf96c083 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -594,8 +594,8 @@ disk or network mount. ## Download directory -By default, TUI `Ctrl+S` saves yt-dlp downloads, temporary audio files, and the -original files of Plex tracks in `~/Music/cliamp`. To use another directory, add this setting and restart cliamp: +By default, TUI `Ctrl+S` saves yt-dlp downloads and temporary audio files in +`~/Music/cliamp`. To use another directory, add this setting and restart cliamp: ```toml [downloads] diff --git a/docs/keybindings.md b/docs/keybindings.md index 5e9341611..c53b51657 100644 --- a/docs/keybindings.md +++ b/docs/keybindings.md @@ -133,7 +133,7 @@ and `Esc` clears it. | `[` / `]` | Adjust synced-lyrics timing offset (−/+250 ms) while lyrics show timestamped lines | | `i` | From the playlist, open full info for the highlighted item, including Path (`Up`/`Down` or `j`/`k` scroll; `i`/`Esc`/`q` closes) | | `Ctrl+I` | Toggle Metadata below Settings for the highlighted playlist item (remembered in `show_metadata`; requires a terminal that distinguishes Ctrl+I from Tab) | -| `Ctrl+S` | Save track to `[downloads].directory` (default `~/Music/cliamp`). A Plex track saves its original file; one saved before is not downloaded again | +| `Ctrl+S` | Save track to `[downloads].directory` (default `~/Music/cliamp`) | | `w` | Write the highlighted track to a local playlist | | `Alt+O` | Open the album of the highlighted track: the queue becomes the album with the cursor on that track, and playback goes on. `Ctrl+Z` brings the old queue back. Only Plex tracks have an album to open; on other tracks the key does nothing | | `Alt+L` | Show the albums of the highlighted track's artist: open its provider browser filtered to `^Artist — `. Edit the filter as usual; `Esc` clears it. Only Plex tracks name their artist this way; on other tracks the key does nothing | diff --git a/docs/plex.md b/docs/plex.md index a71a231c9..e870d11d1 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -131,11 +131,6 @@ brings the old queue back. `Alt+L` opens the Plex browser filtered to the albums of the track's artist, with the filter `^Artist — `, which you can edit or clear with `Esc`. -`Ctrl+S` saves the playing Plex track: cliamp downloads its original file from -the server, the one it streams, to the [download -directory](configuration.md#download-directory) as `Artist - Title.flac` (or -the file's own extension). A track saved before is not downloaded again. - Press `Ctrl+R` while an open Plex album or playlist is focused to reload it and pick up server-side changes. Album contents are cached for up to five minutes; Plex playlists are always loaded fresh so smart playlists stay current. diff --git a/docs/provider-development.md b/docs/provider-development.md index bfa6e5008..662c3af93 100644 --- a/docs/provider-development.md +++ b/docs/provider-development.md @@ -209,7 +209,6 @@ are in `provider/interfaces.go`. | `TrackFavoriteState` | Make provider metadata authoritative for a track's ♥ state. Local favorites are ignored for tracks claimed by this interface | `CanFavoriteTrack(track)`, `FavoriteState(track)` | | `TrackAlbumResolver` | Name the album of a track as one of the provider's lists, for `Alt+O`. Must not do I/O | `AlbumForTrack(track)` | | `TrackArtistFilter` | Name the list filter that shows a track's artist, for `Alt+L`. Must not do I/O | `ArtistFilter(track)` | -| `TrackDownloader` | Hand over the original file of a streamed track, for `Ctrl+S` and the `save` operation. `CanDownloadTrack` must not do I/O | `CanDownloadTrack(track)`, `OpenTrackFile(ctx, track) (io.ReadCloser, ext, error)` | | `TrackFavoriteLoader` | Fetch the ♥ state of tracks that have none, such as the start playlist restored from the last session. The UI calls it in a `tea.Cmd` at start | `LoadFavoriteStates(ctx, tracks) error` | | `CatalogLoader` | Lazy paging of a large catalog | `LoadCatalogPage(offset, limit)` | | `CatalogSearcher` | Server-side catalog search that fills the pane | `SearchCatalog(query)`, `ClearSearch()`, `IsSearching()` | diff --git a/external/plex/client.go b/external/plex/client.go index ac0332024..128036680 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -670,35 +670,6 @@ func (c *Client) Search(query string) ([]Track, error) { return tracks, nil } -// OpenPart opens the original file of a track part, with the token in a -// request header. The caller closes the body. -func (c *Client) OpenPart(ctx context.Context, partKey string) (io.ReadCloser, error) { - if !strings.HasPrefix(partKey, "/library/parts/") { - return nil, fmt.Errorf("plex: download: invalid part") - } - resp, err := c.send(ctx, httpclient.Streaming, "download", func(baseURL, token string) (*http.Request, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+partKey+"?download=1", nil) - if err != nil { - return nil, err - } - req.Header.Set("X-Plex-Product", "cliamp") - req.Header.Set("X-Plex-Client-Identifier", c.clientID) - req.Header.Set("X-Plex-Token", token) - return req, nil - }) - if err != nil { - return nil, err - } - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - resp.Body.Close() - if resp.StatusCode == http.StatusUnauthorized { - return nil, fmt.Errorf("plex: token invalid or expired") - } - return nil, fmt.Errorf("plex: download: HTTP %s", resp.Status) - } - return resp.Body, nil -} - // StreamURL returns the authenticated HTTP URL for streaming a track part. // partKey is the relative path from the Part element, e.g. "/library/parts/…/file.flac". // The token is appended as a query parameter; Plex accepts it in either header or query form. diff --git a/external/plex/provider.go b/external/plex/provider.go index c2a2fbf97..67e257320 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -4,8 +4,6 @@ import ( "context" "errors" "fmt" - "io" - "path" "slices" "strings" "sync" @@ -54,7 +52,6 @@ var ( _ provider.TrackFavoriteLoader = (*Provider)(nil) _ provider.TrackAlbumResolver = (*Provider)(nil) _ provider.TrackArtistFilter = (*Provider)(nil) - _ provider.TrackDownloader = (*Provider)(nil) _ provider.TimelineReporter = (*Provider)(nil) _ provider.QueueContinuer = (*Provider)(nil) ) @@ -567,37 +564,6 @@ func (p *Provider) ArtistFilter(track playlist.Track) (string, bool) { return "^" + track.Artist + " — ", true } -// CanDownloadTrack reports whether track is a Plex track. It does no I/O. -// Implements provider.TrackDownloader. -func (p *Provider) CanDownloadTrack(track playlist.Track) bool { - return plexTrackID(track) != "" -} - -// OpenTrackFile opens the original file of a Plex track, the one it streams, -// and names its extension from the part path. Implements -// provider.TrackDownloader. -func (p *Provider) OpenTrackFile(ctx context.Context, track playlist.Track) (io.ReadCloser, string, error) { - id := plexTrackID(track) - if id == "" { - return nil, "", fmt.Errorf("plex: %q is not a Plex track", track.Path) - } - p.mu.Lock() - partKey := p.partKeys[id] - p.mu.Unlock() - if partKey == "" { - t, err := p.client.Track(id) - if err != nil { - return nil, "", fmt.Errorf("plex: download track %s: %w", id, err) - } - partKey = t.PartKey - } - body, err := p.client.OpenPart(ctx, partKey) - if err != nil { - return nil, "", err - } - return body, path.Ext(partKey), nil -} - // stationLists returns the radio stations of the music sections as browser // entries, picked and ordered by the stations setting. A section whose // stations cannot be read is skipped: stations are an extra, not the library. diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index 2edecdb9b..0d4e6ed98 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -3,7 +3,6 @@ package plex import ( "context" "fmt" - "io" "net/http" "net/http/httptest" "slices" @@ -1087,34 +1086,3 @@ func TestProviderTrackAlbumAndArtist(t *testing.T) { } } } - -// A Plex track downloads its original part with the token in a header, and -// names the part's extension. -func TestProviderOpenTrackFile(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/library/parts/6/66/Windowpane.flac" || r.URL.Query().Get("download") != "1" { - w.WriteHeader(http.StatusNotFound) - return - } - if r.Header.Get("X-Plex-Token") != "tok" || r.URL.Query().Get("X-Plex-Token") != "" { - t.Errorf("token header %q, query %q; want the header only", r.Header.Get("X-Plex-Token"), r.URL.Query().Get("X-Plex-Token")) - } - fmt.Fprint(w, "flac bytes") - })) - defer srv.Close() - p := newProvider(NewClient(srv.URL, "tok")) - track := p.convertTracks([]Track{{RatingKey: "6", Title: "Windowpane", PartKey: "/library/parts/6/66/Windowpane.flac"}}, 0)[0] - - if !p.CanDownloadTrack(track) || p.CanDownloadTrack(playlist.Track{Path: "/local/song.flac"}) { - t.Fatal("CanDownloadTrack should accept only Plex tracks") - } - body, ext, err := p.OpenTrackFile(t.Context(), track) - if err != nil { - t.Fatalf("OpenTrackFile: %v", err) - } - defer body.Close() - got, _ := io.ReadAll(body) - if ext != ".flac" || string(got) != "flac bytes" { - t.Fatalf("OpenTrackFile = %q, %q; want .flac and the part's bytes", ext, got) - } -} diff --git a/provider/interfaces.go b/provider/interfaces.go index ec7eef54b..b84ad0f10 100644 --- a/provider/interfaces.go +++ b/provider/interfaces.go @@ -2,7 +2,6 @@ package provider import ( "context" - "io" "time" "github.com/gopxl/beep/v2" @@ -504,14 +503,6 @@ type TrackArtistFilter interface { ArtistFilter(track playlist.Track) (string, bool) } -// TrackDownloader is implemented by providers that can download the file of -// one of their streamed tracks, for Ctrl+S. CanDownloadTrack must not do I/O. -// OpenTrackFile returns the file's body and its extension, such as ".flac". -type TrackDownloader interface { - CanDownloadTrack(track playlist.Track) bool - OpenTrackFile(ctx context.Context, track playlist.Track) (io.ReadCloser, string, error) -} - // QueueContinuer is implemented by providers whose lists never end, such as // radio stations, that load them in batches. When the last track of a batch // starts, the UI asks for the next batch and appends it to the queue. diff --git a/tracksave/save.go b/tracksave/save.go index 871bc943f..458bce043 100644 --- a/tracksave/save.go +++ b/tracksave/save.go @@ -4,7 +4,6 @@ package tracksave import ( "context" "fmt" - "io" "os" "path/filepath" "strings" @@ -49,59 +48,6 @@ func SaveTo(ctx context.Context, track playlist.Track, directory string) (string if track.Stream || !insideTempDir(track.Path) { return "", fmt.Errorf("only downloaded tracks can be saved") } - destination := filepath.Join(saveDir, fileName(track)+filepath.Ext(track.Path)) - if err := fileutil.CopyFile(track.Path, destination); err != nil { - return "", err - } - return destination, nil -} - -// Opener opens the file of a streamed track, such as the original file on a -// media server, and names its extension, such as ".flac". -type Opener func(ctx context.Context, track playlist.Track) (body io.ReadCloser, ext string, err error) - -// SaveFrom saves the file that open returns for track in the configured -// directory, as "Artist - Title.ext". When that file exists, it reads nothing -// and reports existed. The download goes to a hidden temporary file first, -// so a failed one leaves no partial track behind. -func SaveFrom(ctx context.Context, track playlist.Track, directory string, open Opener) (path string, existed bool, err error) { - saveDir, err := Directory(directory) - if err != nil { - return "", false, err - } - if err := os.MkdirAll(saveDir, 0o755); err != nil { - return "", false, err - } - body, ext, err := open(ctx, track) - if err != nil { - return "", false, err - } - defer body.Close() - destination := filepath.Join(saveDir, fileName(track)+ext) - if _, err := os.Stat(destination); err == nil { - return destination, true, nil - } - tmp, err := os.CreateTemp(saveDir, ".cliamp-save-*"+ext) - if err != nil { - return "", false, err - } - defer os.Remove(tmp.Name()) - if _, err := io.Copy(tmp, body); err != nil { - tmp.Close() - return "", false, fmt.Errorf("download: %w", err) - } - if err := tmp.Close(); err != nil { - return "", false, err - } - if err := os.Rename(tmp.Name(), destination); err != nil { - return "", false, err - } - return destination, false, nil -} - -// fileName names a saved track "Artist - Title", with the characters that -// file systems reject replaced. -func fileName(track playlist.Track) string { name := track.Title if name == "" { name = strings.TrimSuffix(filepath.Base(track.Path), filepath.Ext(track.Path)) @@ -109,12 +55,17 @@ func fileName(track playlist.Track) string { if track.Artist != "" { name = track.Artist + " - " + name } - return strings.Map(func(r rune) rune { + name = strings.Map(func(r rune) rune { if strings.ContainsRune(`/\\:*?"<>|`, r) { return '_' } return r }, name) + destination := filepath.Join(saveDir, name+filepath.Ext(track.Path)) + if err := fileutil.CopyFile(track.Path, destination); err != nil { + return "", err + } + return destination, nil } // NeedsDownload reports whether SaveTo downloads track with yt-dlp, which can diff --git a/tracksave/save_test.go b/tracksave/save_test.go index cf4bc1e82..c0c2d332a 100644 --- a/tracksave/save_test.go +++ b/tracksave/save_test.go @@ -2,11 +2,8 @@ package tracksave import ( "context" - "errors" - "io" "os" "path/filepath" - "strings" "testing" "github.com/bjarneo/cliamp/playlist" @@ -99,55 +96,3 @@ func TestNeedsDownload(t *testing.T) { }) } } - -// failingReader fails every read, standing in for a download that breaks or -// must not be read at all. -type failingReader struct{ read *bool } - -func (r failingReader) Read([]byte) (int, error) { - *r.read = true - return 0, errors.New("connection reset") -} - -func TestSaveFrom(t *testing.T) { - dir := t.TempDir() - track := playlist.Track{Path: "plex:track:1", Title: "Windowpane", Artist: "Opeth", Stream: true} - open := func(body io.Reader) Opener { - return func(context.Context, playlist.Track) (io.ReadCloser, string, error) { - return io.NopCloser(body), ".flac", nil - } - } - want := filepath.Join(dir, "Opeth - Windowpane.flac") - - path, existed, err := SaveFrom(t.Context(), track, dir, open(strings.NewReader("audio"))) - if err != nil || existed || path != want { - t.Fatalf("SaveFrom = %q, %v, %v; want %q saved", path, existed, err, want) - } - if got, _ := os.ReadFile(want); string(got) != "audio" { - t.Fatalf("saved %q, want audio", got) - } - - // A file saved before stays as it is, and the download is not read. - var read bool - path, existed, err = SaveFrom(t.Context(), track, dir, open(failingReader{&read})) - if err != nil || !existed || path != want || read { - t.Fatalf("SaveFrom again = %q, %v, %v (read %v); want the existing file, nothing read", path, existed, err, read) - } - - // A broken download leaves neither the track nor a temporary file. - other := playlist.Track{Path: "plex:track:2", Title: "Death Whispered a Lullaby", Artist: "Opeth"} - if _, _, err := SaveFrom(t.Context(), other, dir, open(failingReader{&read})); err == nil { - t.Fatal("SaveFrom of a broken download succeeded") - } - if entries, _ := os.ReadDir(dir); len(entries) != 1 { - t.Fatalf("directory holds %d files after a broken download, want only the first track", len(entries)) - } - - // An open that fails reports its error. - failed := func(context.Context, playlist.Track) (io.ReadCloser, string, error) { - return nil, "", errors.New("offline") - } - if _, _, err := SaveFrom(t.Context(), other, dir, failed); err == nil || !strings.Contains(err.Error(), "offline") { - t.Fatalf("SaveFrom with a failing open = %v, want offline", err) - } -} diff --git a/ui/model/commands.go b/ui/model/commands.go index 4268a3b20..391bc8c45 100644 --- a/ui/model/commands.go +++ b/ui/model/commands.go @@ -136,8 +136,7 @@ type ytdlBatchMsg struct { type trackSavedMsg struct { path string err error - download bool // the save downloaded and counts as a pending download - existed bool // the file was saved before, so nothing was downloaded + download bool // the save ran yt-dlp and counts as a pending download } // — Navidrome browser message types — diff --git a/ui/model/download_directory_test.go b/ui/model/download_directory_test.go index f66f65b4c..5ebbf77d3 100644 --- a/ui/model/download_directory_test.go +++ b/ui/model/download_directory_test.go @@ -1,8 +1,6 @@ package model import ( - "context" - "io" "os" "path/filepath" "strings" @@ -10,7 +8,6 @@ import ( "github.com/bjarneo/cliamp/ipc" "github.com/bjarneo/cliamp/playlist" - "github.com/bjarneo/cliamp/provider" ) func TestSaveUsesConfiguredDirectory(t *testing.T) { @@ -169,50 +166,3 @@ func TestSaveTrackStartsDownloadForYTDLTracks(t *testing.T) { }) } } - -// fakeDownloader streams "dl:" tracks and hands over their files as ".flac". -type fakeDownloader struct { - commandsTestProvider - opened int -} - -func (*fakeDownloader) CanDownloadTrack(t playlist.Track) bool { - return strings.HasPrefix(t.Path, "dl:") -} -func (d *fakeDownloader) OpenTrackFile(context.Context, playlist.Track) (io.ReadCloser, string, error) { - d.opened++ - return io.NopCloser(strings.NewReader("original")), ".flac", nil -} - -// Ctrl+S and IPC save a streamed track through its provider's original file, -// and a second save finds the file instead of downloading it again. -func TestSaveDownloadsProviderTrack(t *testing.T) { - directory := t.TempDir() - tracks := playlist.New() - tracks.Add(playlist.Track{Path: "dl:1", Title: "Song", Artist: "Artist", Stream: true}) - downloader := &fakeDownloader{commandsTestProvider: commandsTestProvider{name: "Fake"}} - m := Model{playlist: tracks, providers: []provider.Entry{{Name: "Fake", Provider: downloader}}} - m.SetDownloadsDirectory(directory) - - cmd := m.saveTrack() - if cmd == nil || m.save.pendingDownloads != 1 { - t.Fatalf("Ctrl+S started no download (pending %d)", m.save.pendingDownloads) - } - msg := cmd().(trackSavedMsg) - want := filepath.Join(directory, "Artist - Song.flac") - if data, _ := os.ReadFile(want); msg.err != nil || msg.existed || msg.path != want || string(data) != "original" { - t.Fatalf("saved %+v, file %q; want %s with the original file", msg, data, want) - } - - reply := make(chan ipc.Response, 1) - m.handleIPCSave(ipcSaveRequest{Reply: reply})() - if response := <-reply; !response.OK || response.Output != want { - t.Fatalf("IPC save = %+v, want %s", response, want) - } - - msg = m.saveTrack()().(trackSavedMsg) - m.handleTrackSaved(msg) - if !msg.existed || !strings.Contains(m.status.text, "Already saved to") { - t.Fatalf("second save existed=%v, status %q; want the file found", msg.existed, m.status.text) - } -} diff --git a/ui/model/ipc_extended.go b/ui/model/ipc_extended.go index 23df1d96e..bcfff9e29 100644 --- a/ui/model/ipc_extended.go +++ b/ui/model/ipc_extended.go @@ -155,15 +155,8 @@ func (m *Model) handleIPCSave(request ipcSaveRequest) tea.Cmd { return nil } directory := m.downloadsDirectory - save := func(ctx context.Context, directory string) (string, bool, error) { - path, err := tracksave.SaveTo(ctx, track, directory) - return path, false, err - } - if s, ok := m.providerTrackSave(track); ok { - save = s - } return func() tea.Msg { - path, _, err := save(requestContext(request.Context), directory) + path, err := tracksave.SaveTo(requestContext(request.Context), track, directory) if err != nil { request.Reply <- ipc.Response{OK: false, Error: err.Error()} } else { diff --git a/ui/model/keys.go b/ui/model/keys.go index e5cd16893..fb8c4fb92 100644 --- a/ui/model/keys.go +++ b/ui/model/keys.go @@ -967,38 +967,18 @@ func (m *Model) saveTrack() tea.Cmd { m.status.Warning("Nothing to save", statusTTLShort) return nil } - directory := m.downloadsDirectory - if save, ok := m.providerTrackSave(track); ok { - m.status.Clear() - m.save.startDownload() - return func() tea.Msg { - path, existed, err := save(context.Background(), directory) - return trackSavedMsg{path: path, err: err, download: true, existed: existed} - } - } download := tracksave.NeedsDownload(track) if download { m.status.Clear() m.save.startDownload() } + directory := m.downloadsDirectory return func() tea.Msg { path, err := tracksave.SaveTo(context.Background(), track, directory) return trackSavedMsg{path: path, err: err, download: download} } } -// providerTrackSave returns how to save track through the provider that -// streams it, which hands over the original file, when one can. -func (m *Model) providerTrackSave(track playlist.Track) (func(ctx context.Context, directory string) (string, bool, error), bool) { - d, _ := findCapable(m, func(d provider.TrackDownloader) bool { return d.CanDownloadTrack(track) }) - if d == nil { - return nil, false - } - return func(ctx context.Context, directory string) (string, bool, error) { - return tracksave.SaveFrom(ctx, track, directory, d.OpenTrackFile) - }, true -} - func (m *Model) openJumpMode() { m.jump = jumpState{active: true} } diff --git a/ui/model/update_playback.go b/ui/model/update_playback.go index 5c43fa1cb..c609bdbd3 100644 --- a/ui/model/update_playback.go +++ b/ui/model/update_playback.go @@ -184,8 +184,6 @@ func (m *Model) handleTrackSaved(msg trackSavedMsg) { m.save.finishDownload() } switch { - case msg.err == nil && msg.existed: - m.status.Showf(statusTTLMedium, "Already saved to %s", msg.path) case msg.err == nil: m.status.Showf(statusTTLMedium, "Saved to %s", msg.path) case msg.download: