diff --git a/CLAUDE.md b/CLAUDE.md index fda1f9610..a5955220d 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/cmd/setup.go b/cmd/setup.go index d9fe11750..79a63940d 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. @@ -134,12 +135,16 @@ 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 // 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 +251,46 @@ 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{ + // 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{ - {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: "libraries", label: "Music libraries (optional)", help: "comma-separated names to include; blank loads every music library"}, + {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", + onlyIf: func(v map[string]string) bool { return v[keyPlexAuth] != "signout" }}, }, 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 +974,29 @@ 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 + } + return plex.NewClientIdentifier() +} + // ----- Bubbletea model ---------------------------------------------------- type stage int @@ -957,9 +1008,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 @@ -972,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 @@ -991,12 +1050,20 @@ type setupModel struct { chatNames map[string]string // peer key -> title, for the form summary // validating - spinFrame int + spinFrame int + authURL string + authStatus string + + // Plex account server selection + plexServers []plexServerChoice + plexServerCursor int // result state 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 @@ -1036,6 +1103,27 @@ 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 +} + +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{} }) } @@ -1120,6 +1208,62 @@ 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) + 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} + } +} + +// 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) + return nil + } +} + // ----- Update ------------------------------------------------------------- func (m *setupModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { @@ -1163,6 +1307,41 @@ 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() + 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 plexSignOutDoneMsg: + return m.finishPlexSignOut(msg) + + 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 +1405,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) } @@ -1263,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 @@ -1270,8 +1453,18 @@ 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 - - if m.provs[idx].picker != nil { + m.authURL = "" + m.authStatus = "" + m.plexServers = nil + m.plexServerCursor = 0 + + 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() @@ -1290,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 { @@ -1305,6 +1498,75 @@ 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" +} + +// 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 + 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 +1884,33 @@ 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 { + m.resultErr = err + m.stage = stageResult + return m, nil + } + m.stage = stageValidating + m.spinFrame = 0 + m.authURL = "" + m.authStatus = "Starting Plex sign-in…" + 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 +2092,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() } @@ -1858,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 { @@ -2026,11 +2317,46 @@ 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" || m.values[keyPlexAuth] == "signout") { + 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 + } + } + 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 @@ -2066,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 { @@ -2108,6 +2442,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..d0afa100d 100644 --- a/cmd/setup_test.go +++ b/cmd/setup_test.go @@ -1,15 +1,18 @@ package cmd import ( + "context" "errors" "os" "path/filepath" + "slices" "strings" "testing" 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 +103,132 @@ 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 { + 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 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) + 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) { @@ -988,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/config.toml.example b/config.toml.example index 305ddacb4..90818e707 100644 --- a/config.toml.example +++ b/config.toml.example @@ -306,10 +306,20 @@ 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. # 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 efb142d86..451013a1e 100644 --- a/config/config.go +++ b/config/config.go @@ -663,18 +663,25 @@ 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 + // 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 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,8 +691,14 @@ 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) + case "stations": + p.Stations = parseStringSlice(val) } } diff --git a/config/config_golden_test.go b/config/config_golden_test.go index b37974a10..aeaab4f78 100644 --- a/config/config_golden_test.go +++ b/config/config_golden_test.go @@ -379,7 +379,14 @@ 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"}, + Stations: []string{"Library Radio", "Random Album Radio"}, + } 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..95ea2975f 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 @@ -1114,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/cli.md b/docs/cli.md index eec6b4a37..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. 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/configuration.md b/docs/configuration.md index 3853b1248..1cf96c083 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/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/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/keybindings.md b/docs/keybindings.md index 5c492df2b..c53b51657 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) | @@ -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. 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/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 66177b642..e870d11d1 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -2,15 +2,63 @@ 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. + +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. + +## 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 +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,22 +75,31 @@ 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"] +stations = ["Library Radio", "Random Album Radio"] ``` | Key | Description | |-----|-------------| | `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. | +| `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. | -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 After configuration, **Plex** appears in the cliamp provider list. -The provider shows audio playlists and the music library under two headers: +The provider shows audio playlists, the library radio stations, and the music +library under three headers: ```text ── Playlists ── @@ -50,12 +107,59 @@ GOOD All Music drums +── Radio ── +Library Radio +Deep Cuts Radio +Time Travel Radio +Random Album Radio + ── Albums ── 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. + +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. + +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. 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. + +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, +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 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). + Start cliamp with Plex as the default provider: ```bash @@ -70,13 +174,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 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 @@ -88,7 +192,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/docs/provider-development.md b/docs/provider-development.md index d4b3e45a8..662c3af93 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,10 +201,15 @@ 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` | | `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()` | | `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/account.go b/external/plex/account.go new file mode 100644 index 000000000..fdfd21726 --- /dev/null +++ b/external/plex/account.go @@ -0,0 +1,456 @@ +package plex + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "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 + connectionSelectGrace = 100 * time.Millisecond +) + +// 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 + } + 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 + } + server := servers[result.index] + reachableByIndex[result.index] = &ReachableServer{ + Name: server.Name, + ClientIdentifier: server.ClientIdentifier, + 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 { + 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) + }) + valid := candidates[:0] + for _, connection := range candidates { + connection.URI = strings.TrimRight(connection.URI, "/") + if connectionRank(connection) >= 100 || !looksLikeServerURL(connection.URI) { + continue + } + 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, server.ClientIdentifier, 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) +} + +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") +} + +// 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, "") + 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) + } + 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 +} + +// 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 { + 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..9a7a8ed5e --- /dev/null +++ b/external/plex/account_test.go @@ -0,0 +1,326 @@ +package plex + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "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) + } +} + +// 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(identityHandler("server-1")) + defer secure.Close() + + local := httptest.NewServer(identityHandler("server-1")) + defer local.Close() + + api := &AccountAPI{baseURL: "unused", client: secure.Client(), pollInterval: time.Millisecond} + server := AccountServer{ + Name: "Home", + ClientIdentifier: "server-1", + 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 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(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", + ClientIdentifier: "server-1", + 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-Client-Identifier"); got != "client-1" { + t.Errorf("client identifier = %q, want client-1", got) + } + identityHandler("server-1")(w, r) + })) + 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", + ClientIdentifier: "server-1", + 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) + } +} + +// 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 { + 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) + } +} + +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/external/plex/client.go b/external/plex/client.go index 1a8eacc16..128036680 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -2,13 +2,19 @@ package plex import ( + "context" + "errors" "fmt" + "io" + "net" "net/http" "net/url" "strconv" "strings" + "sync" "time" + "github.com/bjarneo/cliamp/applog" "github.com/bjarneo/cliamp/internal/httpclient" "github.com/bjarneo/cliamp/internal/netdiag" ) @@ -22,16 +28,167 @@ 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 + machineID string // server identifier for play queue URIs, read once +} + +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 +} + +// 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 + } + // 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) || !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. +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()) + timeout := responseHeaderTimeout + timer := time.AfterFunc(timeout, cancel) + resp, err := client.Do(req.WithContext(ctx)) + 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} + 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() { + 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). @@ -56,10 +213,19 @@ 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 PartKey string // relative path, e.g. "/library/parts/67890/1234567890/file.flac" + 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. @@ -71,24 +237,34 @@ 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 { - if params == nil { - params = url.Values{} - } - params.Set("X-Plex-Token", c.token) - - req, err := http.NewRequest(http.MethodGet, c.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") + return c.request(http.MethodGet, path, params, result) +} - resp, err := apiClient.Do(req) +// 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 { + 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() @@ -97,6 +273,8 @@ func (c *Client) get(path string, params url.Values, result any) error { // 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) } @@ -107,6 +285,80 @@ 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) +} + +// 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") + } + // 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}, + "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 { + 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 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 +600,50 @@ 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 +} + +// 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"` + } + 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)) + 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) { @@ -377,8 +673,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 { - return c.baseURL + partKey + "?X-Plex-Token=" + url.QueryEscape(c.token) + c.mu.Lock() + defer c.mu.Unlock() + 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 @@ -394,14 +697,16 @@ 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 + 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 + Duration int `json:"duration"` // milliseconds + UserRating float64 `json:"userRating"` Media []struct { Part []struct { Key string `json:"key"` @@ -423,9 +728,134 @@ 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, PartKey: partKey, + 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/client_test.go b/external/plex/client_test.go index 2c9cf224c..83322f5a1 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" @@ -8,11 +9,98 @@ import ( "slices" "strconv" "strings" + "sync/atomic" "testing" + "time" "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) + } + }) + } +} + +func TestReportTimeline(t *testing.T) { + 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", tt.position, tt.duration); 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") @@ -542,6 +630,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"}]}] }, { @@ -589,6 +678,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) } @@ -622,7 +714,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) } @@ -636,6 +728,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" { @@ -694,6 +805,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 != "" { + t.Errorf("probe token = %q, want none", got) + } + identityHandler("server-1")(w, r) + 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) { @@ -720,3 +884,174 @@ 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") + } +} + +// 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) + + 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.MusicSections(); err != nil { + t.Fatalf("MusicSections: %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) + } + }) +} + +// 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) + })) + 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, "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 +} diff --git a/external/plex/provider.go b/external/plex/provider.go index ad5c60220..67e257320 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -2,11 +2,14 @@ package plex import ( "context" + "errors" "fmt" "slices" "strings" "sync" + "time" + "github.com/bjarneo/cliamp/applog" "github.com/bjarneo/cliamp/config" "github.com/bjarneo/cliamp/playlist" "github.com/bjarneo/cliamp/provider" @@ -16,15 +19,41 @@ 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:" + prefixStation = "st:" sectionAlbums = "Albums" sectionPlaylists = "Playlists" + 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 + // favoriteBatch is how many tracks one request asks the rating of. + favoriteBatch = 100 + 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) + _ playlist.RefreshablePlaylist = (*Provider)(nil) + _ provider.Searcher = (*Provider)(nil) + _ provider.AlbumTrackLoader = (*Provider)(nil) + _ provider.TrackFavoriter = (*Provider)(nil) + _ provider.TrackFavoriteState = (*Provider)(nil) + _ provider.TrackFavoriteLoader = (*Provider)(nil) + _ provider.TrackAlbumResolver = (*Provider)(nil) + _ provider.TrackArtistFilter = (*Provider)(nil) + _ provider.TimelineReporter = (*Provider)(nil) + _ provider.QueueContinuer = (*Provider)(nil) ) // Provider implements playlist.Provider for a Plex Media Server. @@ -36,12 +65,28 @@ type Provider struct { client *Client mu sync.Mutex playlistCache []playlist.PlaylistInfo - trackCache map[string][]playlist.Track + trackCache map[string]trackCacheEntry + partKeys map[string]string + favorites map[string]bool + // 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 + 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} + return &Provider{client: client, now: time.Now} } // NewFromConfig returns a Provider from a PlexConfig, or nil if URL or Token is missing. @@ -49,7 +94,14 @@ func NewFromConfig(cfg config.PlexConfig) *Provider { if !cfg.IsSet() { return nil } - return newProvider(NewClient(cfg.URL, cfg.Token, cfg.Libraries...)) + var p *Provider + if cfg.ClientID != "" && cfg.ServerID != "" { + p = newProvider(NewAccountClient(cfg.URL, cfg.Token, cfg.ClientID, cfg.ServerID, cfg.Libraries...)) + } else { + p = newProvider(NewClient(cfg.URL, cfg.Token, cfg.Libraries...)) + } + p.stations = cfg.Stations + return p } // Name returns the display name used in the provider selector. @@ -88,6 +140,8 @@ func (p *Provider) Playlists() ([]playlist.PlaylistInfo, error) { if err != nil { return nil, err } + // 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 { @@ -124,25 +178,45 @@ func (p *Provider) Refresh() { p.mu.Lock() p.playlistCache = nil p.trackCache = nil + p.partKeys = nil + p.favorites = nil p.mu.Unlock() + p.client.RefreshConnection() +} + +// 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. 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. +// 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 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() 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() @@ -164,9 +238,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() } @@ -188,11 +262,21 @@ 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 + 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: p.client.StreamURL(t.PartKey), + Path: TrackURIPrefix + t.RatingKey, Title: t.Title, Artist: t.ArtistName, Album: t.AlbumName, @@ -200,6 +284,7 @@ func (p *Provider) convertTracks(plexTracks []Track, limit int) []playlist.Track TrackNumber: t.TrackNumber, DurationSecs: t.Duration / 1000, Stream: true, + ProviderMeta: trackMeta(t), }) if limit > 0 && len(tracks) >= limit { break @@ -208,6 +293,385 @@ 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 + if p.favorites == nil { + p.favorites = make(map[string]bool) + } + 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 +} + +// 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) { + 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) != "" +} + +// 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() + defer p.mu.Unlock() + if id == "" { + return false, false + } + favorite, known = p.favorites[id] + 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) + } + 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 + } + // 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 +} + +// 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 == "" { + return fmt.Errorf("plex: track has no rating key") + } + rating := float64(0) + if favorite { + rating = 10 + } + 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 +} + +// 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 +} + +// 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 +} + +// 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. +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 + } + id, _ := trackIDFromPath(track.Path) + 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)) +} + +// 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) + 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 466e97a17..0d4e6ed98 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -1,12 +1,20 @@ package plex import ( + "context" + "fmt" "net/http" "net/http/httptest" + "slices" + "strconv" "strings" + "sync" "testing" + "time" "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 @@ -22,7 +30,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"}]}] } ] @@ -73,6 +81,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) @@ -220,14 +230,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 +271,114 @@ 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) + } + if favorite, known := p.FavoriteState(tr); !favorite || !known { + t.Error("Plex userRating=10 was not exposed as a favorite") + } +} + +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","userRating":10,"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?download=1&X-Plex-Token=tok" + 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) { + 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 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) { + 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.ReportPaused(track, 31*time.Second); err != nil { + t.Fatalf("ReportPaused: %v", err) } - if !strings.Contains(tr.Path, "/library/parts/3/333/HighwayToHell.flac") { - t.Errorf("Path %q missing part key", tr.Path) + 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,paused,stopped,stopped" { + t.Fatalf("timeline states = %q", got) + } + if scrobbleCount != 1 { + t.Fatalf("scrobble count = %d, want 1", scrobbleCount) } } @@ -348,6 +458,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) @@ -386,6 +578,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 @@ -450,3 +654,435 @@ 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") + } + }) + } +} + +// 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":[{"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": + 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) + } + // 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 !slices.Equal(sections, want) { + t.Fatalf("section order = %v, want %v", sections, want) + } + }) + } +} + +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) + } + 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) + } + } + }) + } +} + +// 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") + } +} + +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())) + } +} + +// 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. +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/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/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..5299e8126 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" @@ -181,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 { @@ -202,7 +202,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 +397,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 +418,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, string), 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, playlistID := resumeContext() + resume.SaveState(resume.State{ + Path: path, PositionSec: secs, Playlist: playlistName, + Context: tracks, ContextIndex: index, PlaylistID: playlistID, + }) + return + } } resume.Save(path, secs, playlistName) } diff --git a/main_test.go b/main_test.go index bf89d6720..e0904988a 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,17 +77,36 @@ 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, - want: resume.State{Path: stream, PositionSec: 95, Playlist: "Mix", Context: tracks, ContextIndex: 1}, + 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, 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, PlaylistID: "4242"}, + }, + { + 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, @@ -102,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 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/provider/interfaces.go b/provider/interfaces.go index 38b9e85ab..b84ad0f10 100644 --- a/provider/interfaces.go +++ b/provider/interfaces.go @@ -158,6 +158,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 { @@ -331,9 +345,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 +367,23 @@ type TrackRater interface { SetTrackRating(ctx context.Context, track playlist.Track, rating int) error } +// 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 + 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 { @@ -459,6 +489,30 @@ 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. +// 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/provider/types.go b/provider/types.go index 4d5a31143..d5ea8dbfc 100644 --- a/provider/types.go +++ b/provider/types.go @@ -72,6 +72,9 @@ func YearFromDate(date string) int { // ProviderMeta key constants used across providers and the UI. 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/providers.go b/providers.go index 60f3140e6..c7698b8e9 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) { @@ -369,6 +378,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. @@ -485,22 +504,23 @@ 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 { - return func(track playlist.Track, positionSec int, context []playlist.Track, contextIndex int) { +func serverResumeSaver(server contextServer) model.ResumeSaver { + 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, }) } } -// 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 d2f4c4d48..4dd99a4f9 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" @@ -99,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) } @@ -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) { @@ -282,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/site/index.html b/site/index.html index d480de71c..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:"server token"}, + {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/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/command_registry.go b/ui/model/command_registry.go index ab6ffae32..4d6b27831 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/favorites.go b/ui/model/favorites.go index 0ca0eac6a..13f356548 100644 --- a/ui/model/favorites.go +++ b/ui/model/favorites.go @@ -3,10 +3,12 @@ package model import ( "context" "errors" + "maps" "time" 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" @@ -21,14 +23,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,26 +43,56 @@ 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. 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 { + 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 { + 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 } - 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() + 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()) } - // 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 } // findTrackFavoriter returns the first registered provider that owns track @@ -67,6 +101,35 @@ 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, providerOwned bool) { + state, _ := findCapable(m, func(s provider.TrackFavoriteState) bool { return s.CanFavoriteTrack(track) }) + if state == nil { + return false, false + } + 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 +} + +// 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 @@ -89,13 +152,56 @@ 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. +// 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. 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 fd45a5fb4..cc2c78ebd 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,28 @@ 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 } +// 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] + return favorite, known +} + func (p *fakeTrackFavoriter) recorded() []string { p.mu.Lock() defer p.mu.Unlock() @@ -304,6 +324,180 @@ func TestTrackFavoriteSyncRouting(t *testing.T) { } } +func TestProviderFavoriteStateIsDisplayedAndToggled(t *testing.T) { + m, store := favoriteKeyTestModel(t) + track := playlist.Track{Path: "fake:track:liked", Title: "Liked"} + 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}) + + 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") + } + 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") + } + 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 := &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 // provider ends with the local state. func TestTrackFavoriteSyncKeepsLastState(t *testing.T) { @@ -518,3 +712,118 @@ 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) + } +} + +// 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) + } +} + +// 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) + } +} diff --git a/ui/model/init.go b/ui/model/init.go index f1b262db1..e0e03c423 100644 --- a/ui/model/init.go +++ b/ui/model/init.go @@ -276,6 +276,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 @@ -313,9 +319,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. @@ -351,6 +358,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/keys.go b/ui/model/keys.go index e5db50e94..fb8c4fb92 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() } } @@ -283,6 +284,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 +767,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/keys_radio.go b/ui/model/keys_radio.go index c2d05d951..a6ecccf95 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, providerOwned := m.providerTrackFavoriteState(track); providerOwned { + 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, 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..afa494706 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 @@ -444,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. @@ -476,6 +480,7 @@ type Model struct { playlist string context []playlist.Track contextIndex int + playlistID string } // preloading is true while a preloadStreamCmd goroutine is in-flight. @@ -540,6 +545,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 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 { diff --git a/ui/model/playback.go b/ui/model/playback.go index 9b44909aa..991e02c98 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 } @@ -386,7 +395,19 @@ 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 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 + } if m.plCursor >= m.playlist.Len() { m.plCursor = max(0, m.playlist.Len()-1) } @@ -569,7 +590,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/playback_context_test.go b/ui/model/playback_context_test.go index 05e5d88e3..1d07563d7 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) } @@ -247,7 +248,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") } @@ -272,7 +273,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 0e561e034..eccebb231 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/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/providers.go b/ui/model/providers.go index 1b257303c..f1c78c0db 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 { @@ -230,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 diff --git a/ui/model/queue_continue.go b/ui/model/queue_continue.go new file mode 100644 index 000000000..9b1c66d23 --- /dev/null +++ b/ui/model/queue_continue.go @@ -0,0 +1,57 @@ +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. +// 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 nil + } + if len(msg.tracks) == 0 || m.playlist == nil { + return nil + } + tracks := m.playlist.Tracks() + if len(tracks) == 0 || tracks[len(tracks)-1].Path != msg.after { + return nil + } + m.playlist.Add(msg.tracks...) + return m.rearmStalePreload() +} 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/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) } diff --git a/ui/model/state.go b/ui/model/state.go index cce4de723..223f77fd3 100644 --- a/ui/model/state.go +++ b/ui/model/state.go @@ -37,6 +37,14 @@ 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 + // 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/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..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 { @@ -616,3 +618,74 @@ 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) + } + }) + } +} + +// 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/track_jumps.go b/ui/model/track_jumps.go new file mode 100644 index 000000000..3022567d7 --- /dev/null +++ b/ui/model/track_jumps.go @@ -0,0 +1,171 @@ +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() + 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 { + 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 + } + // 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(undo) + 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..899c584af --- /dev/null +++ b/ui/model/track_jumps_test.go @@ -0,0 +1,229 @@ +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) + } +} + +// 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) { + 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/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") + } +} diff --git a/ui/model/update.go b/ui/model/update.go index d6e1ecacf..b696e859f 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 @@ -184,6 +187,9 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { m.handleCatalogSearch(msg) return m, nil + case queueContinuedMsg: + return m, m.handleQueueContinued(msg) + case ytdlBatchMsg: cmd := m.handleYTDLBatch(msg) return m, cmd @@ -384,6 +390,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 { diff --git a/ui/model/view.go b/ui/model/view.go index bed74e09f..d249d1a1d 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) }