Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions docs/plex.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

```
http://<server>:32400/library/parts/<partID>/<timestamp>/file.<ext>?X-Plex-Token=<token>
plex:track:<ratingKey>
```

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

Expand Down
16 changes: 16 additions & 0 deletions external/plex/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
72 changes: 65 additions & 7 deletions external/plex/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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.
Expand Down Expand Up @@ -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:<ratingKey> 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)

Expand Down Expand Up @@ -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,
Expand All @@ -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) {
Expand Down
82 changes: 72 additions & 10 deletions external/plex/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down Expand Up @@ -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)
}
}
}

Expand Down
10 changes: 10 additions & 0 deletions providers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
11 changes: 11 additions & 0 deletions providers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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) {
Expand Down
Loading