diff --git a/docs/plex.md b/docs/plex.md index 66177b642..4b8d6943b 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -70,13 +70,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 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 adds your token to the request. The token is not written into new track paths. Entries saved by an earlier cliamp version keep the full stream URL, token included, until you remove them. The part 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. ## Troubleshooting diff --git a/external/plex/client.go b/external/plex/client.go index 1a8eacc16..e4876e740 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -374,6 +374,22 @@ func (c *Client) Search(query string) ([]Track, error) { return tracks, nil } +// Track returns one track by its ratingKey. +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 +} + // 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 ad5c60220..a395df1e8 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 starts the token-free path that queues, history, + // favorites, playlists, resume state and IPC keep for a Plex track. + TrackURIPrefix = "plex:track:" prefixPlaylist = "pl:" sectionAlbums = "Albums" sectionPlaylists = "Playlists" @@ -37,6 +40,7 @@ type Provider struct { mu sync.Mutex playlistCache []playlist.PlaylistInfo trackCache map[string][]playlist.Track + partKeys map[string]string // ratingKey to stream part } // newProvider returns a Provider backed by the given Client. @@ -124,16 +128,18 @@ func (p *Provider) Refresh() { p.mu.Lock() p.playlistCache = nil p.trackCache = nil + p.partKeys = nil p.mu.Unlock() } // 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 -// are cached per album ID; playlist tracks are intentionally not cached so -// smart playlists always reflect their current server contents. +// is a token-free plex:track: URI that ResolveSource turns into a +// stream URL at play time. Tracks with no streamable part (missing Media/Part +// data) are silently skipped. 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) { isPlaylist := strings.HasPrefix(playlistID, prefixPlaylist) @@ -184,15 +190,23 @@ func (p *Provider) SearchTracks(_ context.Context, query string, limit int) ([]p } // convertTracks converts Plex tracks to playlist tracks, skipping entries -// without a streamable part. If limit > 0, at most limit tracks are returned. +// without a valid ratingKey or a streamable part. If limit > 0, at most limit +// tracks are returned. Each Path is a token-free plex:track: URI; +// ResolveSource adds the token when playback starts. func (p *Provider) convertTracks(plexTracks []Track, limit int) []playlist.Track { tracks := make([]playlist.Track, 0, len(plexTracks)) + p.mu.Lock() + defer p.mu.Unlock() for _, t := range plexTracks { - if t.PartKey == "" { + if !validRatingKey(t.RatingKey) || t.PartKey == "" { continue } + if p.partKeys == nil { + p.partKeys = make(map[string]string) + } + p.partKeys[t.RatingKey] = t.PartKey tracks = append(tracks, playlist.Track{ - Path: p.client.StreamURL(t.PartKey), + Path: TrackURIPrefix + t.RatingKey, Title: t.Title, Artist: t.ArtistName, Album: t.AlbumName, @@ -208,6 +222,50 @@ func (p *Provider) convertTracks(plexTracks []Track, limit int) []playlist.Track return tracks } +// ResolveSource turns a plex:track: URI into an authenticated stream URL when +// playback starts. After a restart the part is not known yet, so it reads +// the track's metadata once. +func (p *Provider) ResolveSource(uri string) (string, error) { + id, ok := strings.CutPrefix(uri, TrackURIPrefix) + if !ok || !validRatingKey(id) { + 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 +} + +// validRatingKey reports whether id is safe to put in a metadata path. +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 +} + // 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..cffe628c4 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -220,14 +220,15 @@ 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 %q", tr.Path, TrackURIPrefix+"200") } - if !strings.Contains(tr.Path, "X-Plex-Token=tok") { - t.Errorf("Path %q missing X-Plex-Token", tr.Path) + got, err := p.ResolveSource(tr.Path) + if err != nil { + t.Fatalf("ResolveSource: %v", err) } - if !strings.Contains(tr.Path, "/library/parts/1/111/SoWhat.flac") { - t.Errorf("Path %q missing part key", tr.Path) + if !strings.HasPrefix(got, srv.URL+"/library/parts/1/111/SoWhat.flac?") || !strings.Contains(got, "X-Plex-Token=tok") { + t.Errorf("ResolveSource = %q, want the authenticated part URL", got) } } @@ -264,11 +265,72 @@ 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 %q", tr.Path, TrackURIPrefix+"300") } - if !strings.Contains(tr.Path, "/library/parts/3/333/HighwayToHell.flac") { - t.Errorf("Path %q missing part key", tr.Path) +} + +// After a restart the queue holds only plex:track: paths. ResolveSource +// reads the track's part from the server and adds the token. +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.Errorf("path = %q, want the metadata lookup", r.URL.Path) + http.NotFound(w, r) + return + } + 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) + } + if !strings.HasPrefix(got, srv.URL+"/library/parts/1/111/file.flac?") || !strings.Contains(got, "X-Plex-Token=tok") { + t.Fatalf("ResolveSource = %q, want the authenticated part URL", got) + } +} + +// Refresh forgets the cached parts: a file replaced in Plex keeps its +// ratingKey but gets a new part, and the next play must use the new one. +func TestProviderRefreshForgetsParts(t *testing.T) { + part := "/library/parts/1/111/old.flac" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"MediaContainer":{"Metadata":[{"ratingKey":"200","Media":[{"Part":[{"key":"` + part + `"}]}]}]}}`)) + })) + defer srv.Close() + + p := newProvider(NewClient(srv.URL, "tok")) + if _, err := p.ResolveSource(TrackURIPrefix + "200"); err != nil { + t.Fatalf("ResolveSource: %v", err) + } + part = "/library/parts/2/222/new.flac" + p.Refresh() + got, err := p.ResolveSource(TrackURIPrefix + "200") + if err != nil { + t.Fatalf("ResolveSource after Refresh: %v", err) + } + if !strings.HasPrefix(got, srv.URL+part+"?") { + t.Fatalf("ResolveSource after Refresh = %q, want the new part", got) + } +} + +// A path that is not a plain ratingKey never reaches the server. +func TestProviderResolveSourceRejectsBadPaths(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("unexpected request %s", r.URL.Path) + })) + defer srv.Close() + + p := newProvider(NewClient(srv.URL, "tok")) + for _, path := range []string{TrackURIPrefix, TrackURIPrefix + "../200", TrackURIPrefix + "200?x=1", "yandex:track:200"} { + if _, err := p.ResolveSource(path); err == nil { + t.Errorf("ResolveSource(%q): got no error", path) + } } } diff --git a/providers.go b/providers.go index 60f3140e6..c927b2214 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: + // Plex tracks carry token-free plex:track: URIs; the provider + // adds the 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) {