diff --git a/cmd/setup.go b/cmd/setup.go index d9fe11750..262b26217 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,17 @@ type pickerSpec struct { type pickerOption struct { value string label string + // show, when non-nil, hides the option unless it returns true for the + // config loaded when the provider opens, such as Plex sign-out without + // saved credentials. + show func(config.Config) 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 +252,48 @@ 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"]), } + // A manual setup keeps the saved client_id, so a later + // browser sign-in is the same Plex device. + if v["client_id"] != "" { + kv = append(kv, quotedKV("client_id", v["client_id"])) + } + if v[keyPlexAuth] == "account" { + kv = append(kv, quotedKV("server_id", v["server_id"])) + } if libraries := setupStringList(v["libraries"]); libraries != "" { kv = append(kv, rawKV("libraries", libraries)) } @@ -946,6 +977,26 @@ func setupStringList(value string) string { return "[" + strings.Join(quoted, ", ") + "]" } +// plexSignedIn reports whether [plex] holds a token that sign-out can remove. +func plexSignedIn(cfg config.Config) bool { return cfg.Plex.Token != "" } + +func plexSignedOut(cfg config.Config) bool { return !plexSignedIn(cfg) } + +// 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,15 +1050,31 @@ 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 + // plexPending is a Plex sign-in that the browser approved and setup has + // not saved yet. It is revoked when setup does not save it. + plexPending *plexPendingSignIn + // plexBusy is set while a Plex sign-out or revoke runs; Ctrl+C then + // sets quitRequested and setup quits when the run ends cleanly. + plexBusy bool + quitRequested bool + // sign-in offered after a successful save (Telegram) signInLabel string signInAction func(context.Context) error @@ -1036,6 +1111,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 +1216,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 +1315,49 @@ 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.plexPending = &plexPendingSignIn{token: msg.token, clientID: msg.clientID} + m.authURL = "" + m.authStatus = "Finding reachable Plex servers…" + return m, discoverPlexServersCmd(msg.api, msg.token, msg.clientID) + + case plexSignOutDoneMsg: + return m.finishPlexSignOut(msg) + + case plexDiscardDoneMsg: + return m.finishPlexDiscard(msg) + + case plexAuthDoneMsg: + // A sign-in that was cancelled while discovery ran is already + // being revoked; its late result must not be saved. + if m.plexPending == nil || m.plexPending.token != msg.token { + return m, nil + } + if msg.err != nil { + return m.discardPlexSignIn(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 { + return m.savePlexServer(m.plexServers[0]) + } + m.stage = stagePlexServer + return m, nil } return m, nil } @@ -1209,6 +1404,16 @@ func sanitizePaste(s string) string { func (m *setupModel) handleKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) { if msg.String() == "ctrl+c" { + switch { + case m.plexBusy: + // Finish the sign-out or revoke and its config write first. + m.quitRequested = true + m.authStatus = strings.TrimSuffix(m.authStatus, "…") + "; quitting when done…" + return m, nil + case m.plexPending != nil: + m.quitRequested = true + return m.discardPlexSignIn(nil) + } return m, tea.Quit } @@ -1226,6 +1431,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 +1470,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 +1479,23 @@ 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 + // A Ctrl+C that ended in a warning must not quit a later run. + m.quitRequested = false + + if p := m.provs[idx].picker; p != nil { + m.pickerOpts = m.pickerOpts[:0] + // One snapshot for every option, so the options agree with each + // other. A config that does not load shows the signed-out options. + cfg, _ := config.Load() + for _, opt := range p.options { + if opt.show == nil || opt.show(cfg) { + m.pickerOpts = append(m.pickerOpts, opt) + } + } m.stage = stagePicker } else { m.refreshVisibleFields() @@ -1290,11 +1514,14 @@ 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 + if m.pickerCursor >= len(m.pickerOpts) { + return m, nil + } + 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 +1532,176 @@ 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": + if m.plexPending == nil { + m.stage = stageMenu + return m, nil + } + return m.discardPlexSignIn(nil) + 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 + } + return m.savePlexServer(m.plexServers[m.plexServerCursor]) + } + return m, nil +} + +// savePlexServer saves the approved sign-in with the chosen server. When +// the config cannot be written, the sign-in is revoked, since nothing will +// use it. +func (m *setupModel) savePlexServer(choice plexServerChoice) (tea.Model, tea.Cmd) { + m.applyPlexServer(choice) + m.persistAndDone(false) + if err := m.saveFailed; err != nil { + m.saveFailed = nil + return m.discardPlexSignIn(fmt.Errorf("write config: %w", err)) + } + m.plexPending = nil + 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.plexBusy = false + m.stage = stageResult + if err := config.SaveSection("plex", nil, removed); err != nil { + m.saveFailed = err + return m, nil + } + if m.quitRequested && (msg.err == nil || !msg.account) { + return m, tea.Quit + } + 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 = plexRevokeWarning(msg.err, "Removed the token from [plex]") + m.resultNote = msg.err.Error() + "\n" + plexRemoveDeviceHint + "\n" + restart + } + return m, nil +} + +const plexRemoveDeviceHint = "Check Authorized Devices in your Plex account and remove this device if it is listed." + +// plexRevokeWarning names what is known after a failed revoke: plex.tv +// still accepting the token means it was not revoked; any other failure +// leaves it unknown. +func plexRevokeWarning(err error, done string) string { + if errors.Is(err, plex.ErrTokenStillAccepted) { + return done + ", but Plex did not revoke the token" + } + return done + ", but could not confirm that Plex revoked the token" +} + +// plexPendingSignIn is an approved Plex sign-in that is not saved yet. +type plexPendingSignIn struct { + token string + clientID string +} + +// plexDiscardDoneMsg ends the revoke of an approved sign-in that setup did +// not save. cause is why it was not saved; nil means the user cancelled. +type plexDiscardDoneMsg struct { + cause error + err error +} + +// plexDiscardCmd revokes a token that browser sign-in approved but setup +// will not save, so no unused device stays in the Plex account. +func plexDiscardCmd(pending plexPendingSignIn, cause error) tea.Cmd { + return func() tea.Msg { + ctx, cancel := context.WithTimeout(context.Background(), plexSignOutTimeout) + defer cancel() + return plexDiscardDoneMsg{cause: cause, err: plexSignOut(ctx, pending.token, pending.clientID)} + } +} + +// discardPlexSignIn starts the revoke of the pending sign-in. +func (m *setupModel) discardPlexSignIn(cause error) (tea.Model, tea.Cmd) { + pending := *m.plexPending + m.plexPending = nil + m.plexServers = nil + m.plexBusy = true + m.stage = stageValidating + m.spinFrame = 0 + m.authURL = "" + m.authStatus = "Revoking the unused Plex sign-in…" + if m.quitRequested { + m.authStatus = "Revoking the unused Plex sign-in; quitting when done…" + } + return m, tea.Batch(spinTickCmd(), plexDiscardCmd(pending, cause)) +} + +// finishPlexDiscard shows how the revoke ended. A quit request ends setup +// only when the revoke is confirmed; otherwise the warning stays on screen. +func (m *setupModel) finishPlexDiscard(msg plexDiscardDoneMsg) (tea.Model, tea.Cmd) { + m.plexBusy = false + if m.quitRequested && msg.err == nil && msg.cause == nil { + return m, tea.Quit + } + m.stage = stageResult + m.awaitingSave = false + m.resultErr = msg.cause + m.resultText = "Plex sign-in cancelled." + m.resultNote = "Plex revoked the new token; nothing was saved." + m.resultWarning = false + if msg.err != nil { + what := "Plex sign-in cancelled" + if msg.cause != nil { + what = "Plex sign-in not saved" + } + m.resultErr = nil + m.resultWarning = true + m.warnText = plexRevokeWarning(msg.err, what) + m.resultNote = msg.err.Error() + "\n" + plexRemoveDeviceHint + if msg.cause != nil { + m.resultNote = msg.cause.Error() + "\n" + m.resultNote + } + } + 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 +2019,40 @@ 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.plexBusy = true + 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)) + } + + if spec.section == "plex" && m.values[keyPlexAuth] == "manual" { + if cfg, err := config.Load(); err == nil { + m.values["client_id"] = cfg.Plex.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 +2234,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 +2291,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 +2459,83 @@ 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") + first, last := plexServerWindow(len(m.plexServers), m.plexServerCursor, m.h) + if first > 0 { + b.WriteString(dimStyle.Render(fmt.Sprintf(" ↑ %d more", first))) + b.WriteString("\n") + } + urlWidth := min(maxCardWidth, m.viewWidth()) - 10 + for i := first; i < last; i++ { + choice := m.plexServers[i] + 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(truncateRunes(choice.server.URL, urlWidth))) + b.WriteString("\n") + } + if more := len(m.plexServers) - last; more > 0 { + b.WriteString(dimStyle.Render(fmt.Sprintf(" ↓ %d more", more))) + } + return m.card(strings.TrimRight(b.String(), "\n")) +} + +// plexServerChrome is the screen height around the server rows: the logo, +// the card border and padding, the title, the scroll markers and the footer. +const plexServerChrome = 12 + +// plexServerWindow returns the rows [first, last) of the server list that +// fit a terminal of the given height, two lines per server, with the cursor +// always inside. An unknown height shows every row. +func plexServerWindow(count, cursor, height int) (first, last int) { + rows := (height - plexServerChrome) / 2 + if height <= 0 || rows >= count { + return 0, count + } + rows = max(rows, 1) + first = min(max(cursor-rows/2, 0), count-rows) + return first, first + rows +} + +// truncateRunes shortens s to width runes, ending with an ellipsis, so a +// long server URL takes one line. +func truncateRunes(s string, width int) string { + r := []rune(s) + if width < 2 || len(r) <= width { + return s + } + return string(r[:width-1]) + "…" +} + func (m *setupModel) viewResult() string { spec := m.provs[m.pidx] var b strings.Builder @@ -2061,16 +2566,28 @@ func (m *setupModel) viewResult() string { b.WriteString(errStyle.Render("✗ ")) b.WriteString(m.resultErr.Error()) b.WriteString("\n\n") + if m.resultNote != "" { + b.WriteString(m.resultNote) + b.WriteString("\n\n") + } b.WriteString(hintStyle.Render("Press Enter or Esc to return to the menu, or q to quit.")) return m.card(b.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 +2625,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..a86ede1ec 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 keeps client_id and drops server_id", + section: "plex", + values: map[string]string{keyPlexAuth: "manual", "url": "http://plex.local:32400", "token": "manual-token", "client_id": "client-1"}, + 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\"\nclient_id = \"client-1\"\n", + }, { name: "no config file", section: "qobuz", diff --git a/cmd/setup_test.go b/cmd/setup_test.go index cbfaf21bb..f2f2e6cdb 100644 --- a/cmd/setup_test.go +++ b/cmd/setup_test.go @@ -1,15 +1,21 @@ package cmd import ( + "context" "errors" + "fmt" + "net/http" + "net/http/httptest" "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 +106,140 @@ 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 := plexSetupIndex(t, m) + + 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() + m.pidx = plexSetupIndex(t, m) + m.values = map[string]string{keyPlexAuth: "account", "libraries": "Music"} + m.stage = stageValidating + m.plexPending = &plexPendingSignIn{token: "account-token", clientID: "client-1"} + + 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) + } +} + +// Ctrl+C while servers are being found revokes the approved sign-in, and +// the discovery result that arrives later is not saved. +func TestPlexQuitDuringDiscoveryRevokes(t *testing.T) { + dir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", dir) + revoked := "" + orig := plexSignOut + plexSignOut = func(_ context.Context, token, clientID string) error { + revoked = token + "/" + clientID + return nil + } + t.Cleanup(func() { plexSignOut = orig }) + + m := newSetupModel() + m.pidx = plexSetupIndex(t, m) + m.values = map[string]string{keyPlexAuth: "account"} + m.stage = stageValidating + m.Update(plexAuthApprovedMsg{api: plex.NewAccountAPI(), clientID: "client-1", token: "account-token"}) + _, cmd := m.handleKey(tea.KeyPressMsg(tea.Key{Code: 'c', Mod: tea.ModCtrl})) + if cmd == nil || m.stage != stageValidating { + t.Fatalf("stage = %v, want the revoke to run", m.stage) + } + m.Update(plexAuthDoneMsg{clientID: "client-1", token: "account-token", servers: []plex.ReachableServer{ + {Name: "Home", ClientIdentifier: "home", URL: "https://home.plex.direct:32400", Owned: true}, + }}) + if _, err := os.Stat(filepath.Join(dir, "config.toml")); !os.IsNotExist(err) { + t.Fatalf("a cancelled sign-in was saved: %v", err) + } + var quit bool + for _, c := range cmd().(tea.BatchMsg) { + if msg, ok := c().(plexDiscardDoneMsg); ok { + if _, next := m.Update(msg); next != nil { + _, quit = next().(tea.QuitMsg) + } + } + } + if revoked != "account-token/client-1" || !quit { + t.Fatalf("revoked %q, quit %v; want the approved token revoked, then quit", revoked, quit) + } +} + +func TestPlexAuthApprovalShowsServerDiscovery(t *testing.T) { + m := newSetupModel() + m.pidx = plexSetupIndex(t, m) + 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 +1128,432 @@ 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 + // wantWarnText is part of the warning title. + wantWarnText string + }{ + {name: "browser sign-in", config: account, wantRevoke: true, wantClient: "client-1"}, + {name: "revoke unconfirmed", config: account, revokeErr: errors.New("offline"), wantRevoke: true, wantClient: "client-1", wantWarn: true, wantWarnText: "could not confirm that Plex revoked the token"}, + {name: "token still accepted", config: account, revokeErr: plex.ErrTokenStillAccepted, wantRevoke: true, wantClient: "client-1", wantWarn: true, wantWarnText: "Plex did not revoke the token"}, + {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 !strings.Contains(m.warnText, tt.wantWarnText) { + t.Fatalf("warning = %q, want it to say %q", m.warnText, tt.wantWarnText) + } + if view := m.viewResult(); !strings.Contains(view, "Restart cliamp") { + t.Fatalf("result does not mention the restart:\n%s", view) + } + }) + } +} + +// A sign-in that Plex approved but setup does not save is revoked, so no +// unused device stays in the account: when no server is reachable, on Esc +// and on Ctrl+C at the server choice. +func TestPlexDiscardsUnsavedSignIn(t *testing.T) { + 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"}, + } + for _, tt := range []struct { + name string + done plexAuthDoneMsg + key tea.KeyPressMsg + revokeErr error + wantErr string + wantWarn string + wantQuit bool + }{ + {name: "no reachable server", done: plexAuthDoneMsg{clientID: "client-1", token: "account-token", err: errors.New("none reachable")}, wantErr: "none reachable"}, + {name: "esc at server choice", done: plexAuthDoneMsg{clientID: "client-1", token: "account-token", servers: servers}, key: keyPress(tea.KeyEscape, "")}, + {name: "ctrl+c at server choice", done: plexAuthDoneMsg{clientID: "client-1", token: "account-token", servers: servers}, key: tea.KeyPressMsg(tea.Key{Code: 'c', Mod: tea.ModCtrl}), wantQuit: true}, + {name: "revoke unconfirmed", done: plexAuthDoneMsg{clientID: "client-1", token: "account-token", servers: servers}, key: keyPress(tea.KeyEscape, ""), revokeErr: errors.New("offline"), wantWarn: "could not confirm"}, + {name: "ctrl+c, revoke unconfirmed", done: plexAuthDoneMsg{clientID: "client-1", token: "account-token", servers: servers}, key: tea.KeyPressMsg(tea.Key{Code: 'c', Mod: tea.ModCtrl}), revokeErr: errors.New("offline"), wantWarn: "could not confirm"}, + } { + t.Run(tt.name, func(t *testing.T) { + dir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", dir) + 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.pidx = plexSetupIndex(t, m) + m.values = map[string]string{keyPlexAuth: "account"} + m.stage = stageValidating + m.plexPending = &plexPendingSignIn{token: tt.done.token, clientID: tt.done.clientID} + _, cmd := m.Update(tt.done) + if tt.key.Code != 0 { + if m.stage != stagePlexServer { + t.Fatalf("stage = %v, want stagePlexServer", m.stage) + } + _, cmd = m.handleKey(tt.key) + } + if m.stage != stageValidating || cmd == nil { + t.Fatalf("stage = %v, want the revoke to run", m.stage) + } + var quit bool + for _, c := range cmd().(tea.BatchMsg) { + if msg, ok := c().(plexDiscardDoneMsg); ok { + _, next := m.Update(msg) + if next != nil { + _, quit = next().(tea.QuitMsg) + } + } + } + if revoked != "account-token/client-1" { + t.Fatalf("revoked %q, want the approved token", revoked) + } + if quit != tt.wantQuit { + t.Fatalf("quit = %v, want %v", quit, tt.wantQuit) + } + if _, err := os.Stat(filepath.Join(dir, "config.toml")); !os.IsNotExist(err) { + t.Fatalf("config written: %v", err) + } + if tt.wantQuit { + return + } + if m.stage != stageResult { + t.Fatalf("stage = %v, want stageResult", m.stage) + } + view := m.viewResult() + if tt.wantErr != "" && !strings.Contains(view, tt.wantErr) { + t.Fatalf("result does not show %q:\n%s", tt.wantErr, view) + } + if tt.wantWarn != "" && (!m.resultWarning || !strings.Contains(m.warnText, tt.wantWarn)) { + t.Fatalf("warning = %v %q, want %q", m.resultWarning, m.warnText, tt.wantWarn) + } + if tt.wantWarn == "" && tt.wantErr == "" && !strings.Contains(view, "Plex revoked the new token") { + t.Fatalf("result does not confirm the revoke:\n%s", view) + } + }) + } +} + +// A manual setup keeps the client_id of an earlier browser sign-in, so the +// next browser sign-in is the same Plex device. +func TestPlexManualSetupKeepsClientID(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"MediaContainer":{"friendlyName":"Home"}}`)) + })) + defer srv.Close() + dir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", dir) + if err := os.WriteFile(filepath.Join(dir, "config.toml"), []byte("[plex]\nclient_id = \"client-1\"\n"), 0o600); err != nil { + t.Fatal(err) + } + + m := newSetupModel() + m.startProvider(plexSetupIndex(t, m)) + m.pickerCursor = slices.IndexFunc(m.pickerOpts, func(o pickerOption) bool { return o.value == "manual" }) + m.handleKey(keyPress(tea.KeyEnter, "")) + m.values["url"] = srv.URL + m.values["token"] = "manual-token" + _, cmd := m.submitForm() + for cmd != nil { + msg := cmd() + if batch, ok := msg.(tea.BatchMsg); ok { + cmd = nil + for _, c := range batch { + if c == nil { + continue + } + if next := c(); next != nil { + if _, tick := next.(spinTickMsg); !tick { + _, cmd = m.Update(next) + } + } + } + continue + } + _, cmd = m.Update(msg) + } + + cfg, err := config.Load() + if err != nil { + t.Fatalf("Load: %v", err) + } + if cfg.Plex.URL != srv.URL || cfg.Plex.Token != "manual-token" || cfg.Plex.ClientID != "client-1" || cfg.Plex.ServerID != "" { + t.Fatalf("Plex config = %+v, want the manual setup with client-1", cfg.Plex) + } +} + +// The server list shows the rows that fit the terminal, with the cursor +// always among them. +func TestPlexServerWindow(t *testing.T) { + for _, tt := range []struct { + count, cursor, height int + first, last int + }{ + {count: 3, cursor: 0, height: 0, first: 0, last: 3}, + {count: 3, cursor: 2, height: 40, first: 0, last: 3}, + {count: 12, cursor: 0, height: 24, first: 0, last: 6}, + {count: 12, cursor: 6, height: 24, first: 3, last: 9}, + {count: 12, cursor: 11, height: 24, first: 6, last: 12}, + {count: 12, cursor: 5, height: 10, first: 5, last: 6}, + } { + first, last := plexServerWindow(tt.count, tt.cursor, tt.height) + if first != tt.first || last != tt.last { + t.Errorf("plexServerWindow(%d, %d, %d) = %d, %d; want %d, %d", tt.count, tt.cursor, tt.height, first, last, tt.first, tt.last) + } + if tt.cursor < first || tt.cursor >= last { + t.Errorf("plexServerWindow(%d, %d, %d) hides the cursor", tt.count, tt.cursor, tt.height) + } + } + + m := newSetupModel() + m.h = 24 + m.stage = stagePlexServer + for i := range 12 { + m.plexServers = append(m.plexServers, plexServerChoice{server: plex.ReachableServer{Name: fmt.Sprintf("Server %02d", i), URL: "https://" + strings.Repeat("a", 120)}}) + } + m.plexServerCursor = 11 + view := m.View().Content + if lines := strings.Count(view, "\n") + 1; lines > m.h { + t.Fatalf("view has %d lines for a %d-line terminal:\n%s", lines, m.h, view) + } + if !strings.Contains(view, "Server 11") || strings.Contains(view, "Server 00") { + t.Fatalf("view does not follow the cursor:\n%s", view) + } +} + +// When the config cannot be written, the approved sign-in is revoked and +// the write error stays visible. +func TestPlexRevokesSignInWhenSaveFails(t *testing.T) { + notDir := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(notDir, nil, 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("CLIAMP_CONFIG_DIR", filepath.Join(notDir, "cliamp")) + revoked := "" + orig := plexSignOut + plexSignOut = func(_ context.Context, token, clientID string) error { + revoked = token + "/" + clientID + return nil + } + t.Cleanup(func() { plexSignOut = orig }) + + m := newSetupModel() + m.pidx = plexSetupIndex(t, m) + m.values = map[string]string{keyPlexAuth: "account"} + m.stage = stageValidating + m.plexPending = &plexPendingSignIn{token: "account-token", clientID: "client-1"} + _, cmd := m.Update(plexAuthDoneMsg{clientID: "client-1", token: "account-token", servers: []plex.ReachableServer{ + {Name: "Home", ClientIdentifier: "home", URL: "https://home.plex.direct:32400", Owned: true}, + }}) + if cmd == nil || m.stage != stageValidating { + t.Fatalf("stage = %v, saveFailed = %v; want the revoke to run", m.stage, m.saveFailed) + } + for _, c := range cmd().(tea.BatchMsg) { + if msg, ok := c().(plexDiscardDoneMsg); ok { + m.Update(msg) + } + } + if revoked != "account-token/client-1" { + t.Fatalf("revoked %q, want the approved token", revoked) + } + view := m.viewResult() + if !strings.Contains(view, "write config") || !strings.Contains(view, "Plex revoked the new token") { + t.Fatalf("result does not show the write error and the revoke:\n%s", view) + } +} + +// Ctrl+C during sign-out waits for the revoke and the config write, so a +// revoked token does not stay in the config. +func TestPlexSignOutFinishesBeforeQuit(t *testing.T) { + dir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", dir) + const account = "[plex]\nurl = \"https://home.plex.direct:32400\"\ntoken = \"account-token\"\nclient_id = \"client-1\"\nserver_id = \"server-1\"\n" + if err := os.WriteFile(filepath.Join(dir, "config.toml"), []byte(account), 0o600); err != nil { + t.Fatal(err) + } + orig := plexSignOut + plexSignOut = func(context.Context, string, string) error { return nil } + 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 _, early := m.handleKey(tea.KeyPressMsg(tea.Key{Code: 'c', Mod: tea.ModCtrl})); early != nil { + t.Fatal("Ctrl+C quit before the sign-out finished") + } + var quit bool + for _, c := range cmd().(tea.BatchMsg) { + if msg, ok := c().(plexSignOutDoneMsg); ok { + if _, next := m.Update(msg); next != nil { + _, quit = next().(tea.QuitMsg) + } + } + } + cfg, err := config.Load() + if err != nil { + t.Fatalf("Load: %v", err) + } + if cfg.Plex.Token != "" || !quit { + t.Fatalf("token left = %v, quit = %v; want the token removed, then quit", cfg.Plex.Token != "", quit) + } +} + +// Ctrl+C whose revoke was not confirmed leaves setup open with a warning. +// A later sign-in cancelled with Esc must then stay open too. +func TestPlexQuitRequestDoesNotOutliveItsRun(t *testing.T) { + t.Setenv("CLIAMP_CONFIG_DIR", t.TempDir()) + revokeErr := errors.New("offline") + orig := plexSignOut + plexSignOut = func(context.Context, string, string) error { return revokeErr } + t.Cleanup(func() { plexSignOut = orig }) + 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"}, + } + // reachServerChoice approves a sign-in and shows the server choice. + reachServerChoice := func(m *setupModel) { + m.values = map[string]string{keyPlexAuth: "account"} + m.stage = stageValidating + m.plexPending = &plexPendingSignIn{token: "account-token", clientID: "client-1"} + m.Update(plexAuthDoneMsg{clientID: "client-1", token: "account-token", servers: servers}) + if m.stage != stagePlexServer { + t.Fatalf("stage = %v, want stagePlexServer", m.stage) + } + } + // finish runs the revoke and reports whether setup quit. + finish := func(m *setupModel, cmd tea.Cmd) (quit bool) { + for _, c := range cmd().(tea.BatchMsg) { + if msg, ok := c().(plexDiscardDoneMsg); ok { + if _, next := m.Update(msg); next != nil { + _, quit = next().(tea.QuitMsg) + } + } + } + return quit + } + + m := newSetupModel() + plexIdx := plexSetupIndex(t, m) + m.startProvider(plexIdx) + reachServerChoice(m) + _, cmd := m.handleKey(tea.KeyPressMsg(tea.Key{Code: 'c', Mod: tea.ModCtrl})) + if finish(m, cmd) || !m.resultWarning { + t.Fatalf("an unconfirmed revoke must keep setup open with a warning; warning = %v", m.resultWarning) + } + + revokeErr = nil + m.startProvider(plexIdx) + reachServerChoice(m) + _, cmd = m.handleKey(keyPress(tea.KeyEscape, "")) + if finish(m, cmd) { + t.Fatal("Esc quit setup: the earlier Ctrl+C was remembered") + } + if m.stage != stageResult { + t.Fatalf("stage = %v, want stageResult", m.stage) + } +} diff --git a/config.toml.example b/config.toml.example index 305ddacb4..a493ba05d 100644 --- a/config.toml.example +++ b/config.toml.example @@ -306,6 +306,10 @@ eq = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # [plex] # url = "http://192.168.1.10:32400" # token = "xxxxxxxxxxxxxxxxxxxx" +# Browser sign-in through `cliamp setup` also writes these fields. They let +# cliamp rediscover the selected server when its local or remote address changes. +# client_id = "generated-per-installation-id" +# server_id = "selected-server-id" # # Restrict to specific music libraries (comma-separated, case-insensitive). # When omitted or empty, all music libraries are loaded. diff --git a/config/config.go b/config/config.go index efb142d86..d74fa8544 100644 --- a/config/config.go +++ b/config/config.go @@ -663,18 +663,22 @@ func (y *YandexConfig) set(key, val string) { } } -// PlexConfig holds credentials for a Plex Media Server. -// Both URL and Token must be non-empty for a client to be constructed. +// PlexConfig holds credentials for a Plex Media Server. ClientID and ServerID +// identify browser-authorized account setups; configs without them retain the +// manual URL-and-token behavior. // Enable rule: credentials. type PlexConfig struct { URL string // e.g. "http://192.168.1.10:32400" Token string // X-Plex-Token + ClientID string // stable identifier of this cliamp installation + ServerID string // selected Plex Media Server clientIdentifier Libraries []string // optional: restrict to these music library names } -// IsSet reports whether both Plex credentials are present. +// IsSet reports whether a manual URL or an account-discovery server is +// configured together with a token. func (p PlexConfig) IsSet() bool { - return p.URL != "" && p.Token != "" + return p.Token != "" && (p.URL != "" || (p.ClientID != "" && p.ServerID != "")) } // set applies one key of the [plex] section. @@ -684,6 +688,10 @@ func (p *PlexConfig) set(key, val string) { p.URL = parseString(val) case "token": p.Token = parseString(val) + case "client_id": + p.ClientID = parseString(val) + case "server_id": + p.ServerID = parseString(val) case "libraries": p.Libraries = parseStringSlice(val) } diff --git a/config/config_golden_test.go b/config/config_golden_test.go index b37974a10..705f4721f 100644 --- a/config/config_golden_test.go +++ b/config/config_golden_test.go @@ -379,7 +379,13 @@ func TestLoadGolden(t *testing.T) { UserID: "optional-account-user-id", } allWant.Yandex = YandexConfig{Enabled: true, Token: "y0_YourPersonalOAuthToken"} - allWant.Plex = PlexConfig{URL: "http://192.168.1.10:32400", Token: "xxxxxxxxxxxxxxxxxxxx", Libraries: []string{"Music", "Jazz"}} + allWant.Plex = PlexConfig{ + URL: "http://192.168.1.10:32400", + Token: "xxxxxxxxxxxxxxxxxxxx", + ClientID: "generated-per-installation-id", + ServerID: "selected-server-id", + Libraries: []string{"Music", "Jazz"}, + } allWant.Jellyfin = JellyfinConfig{ URL: "https://jellyfin.example.com", Token: "optional-api-token", diff --git a/config/config_test.go b/config/config_test.go index 96d6ea4f2..7e7562943 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -716,6 +716,7 @@ func TestPlexIsSet(t *testing.T) { want bool }{ {"both set", PlexConfig{URL: "http://x", Token: "t"}, true}, + {"account discovery", PlexConfig{Token: "t", ClientID: "client", ServerID: "server"}, true}, {"no URL", PlexConfig{Token: "t"}, false}, {"no token", PlexConfig{URL: "http://x"}, false}, {"empty", PlexConfig{}, false}, @@ -729,6 +730,15 @@ func TestPlexIsSet(t *testing.T) { } } +func TestPlexAccountFields(t *testing.T) { + var cfg PlexConfig + cfg.set("client_id", `"client-1"`) + cfg.set("server_id", `"server-1"`) + if cfg.ClientID != "client-1" || cfg.ServerID != "server-1" { + t.Fatalf("Plex account fields = %+v", cfg) + } +} + func TestJellyfinIsSet(t *testing.T) { tests := []struct { name string diff --git a/docs/cli.md b/docs/cli.md index 727e2b94c..efddae1eb 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -161,7 +161,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/plex.md b/docs/plex.md index 66177b642..87bd0743d 100644 --- a/docs/plex.md +++ b/docs/plex.md @@ -2,15 +2,71 @@ 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. Before each track starts, cliamp checks the address with one small +request, so playback moves on to the next track without a restart or +`Ctrl+R`. A manual setup has one fixed URL and makes no such check. + +A local address can be plain HTTP when the server offers no secure one. The +token then travels unencrypted inside the local network. Before each request +to such an address, cliamp first asks it, without the token, whether it is +still the selected server; another host at the same address gets no token. +A secure address needs no such check: its certificate belongs to the server. + +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,6 +83,8 @@ Add a `[plex]` section to `~/.config/cliamp/config.toml`: [plex] url = "http://192.168.1.10:32400" token = "xxxxxxxxxxxxxxxxxxxx" +client_id = "generated-per-installation-id" +server_id = "selected-server-id" libraries = ["Music", "Jazz"] ``` @@ -34,9 +92,13 @@ libraries = ["Music", "Jazz"] |-----|-------------| | `url` | Plex Media Server base URL, including port (default `32400`) | | `token` | `X-Plex-Token` for authentication | +| `client_id` | Stable cliamp installation ID written by browser sign-in | +| `server_id` | Selected Plex Media Server ID written by browser sign-in | | `libraries` | Optional comma-separated music library names to load. If omitted, cliamp loads all music libraries. Name matching is case-insensitive. | -If you access Plex remotely through `app.plex.tv`, use a direct server URL when remote access is enabled. You can also use the server `plex.direct` URL from the Plex Web address bar. +`client_id` and `server_id` enable account discovery. Omit both for a fixed +manual URL. Do not copy them between installations; rerun browser sign-in on +the other computer so Plex lists it as a separate authorized device. ## Usage @@ -70,13 +132,13 @@ provider = "plex" ## How it works -cliamp calls the Plex HTTP API to list audio playlists (`/playlists`) and music library albums. When you select an entry, cliamp gets its track list from the playlist-items or album-children endpoint. It then creates authenticated streaming URLs in this form: +cliamp calls the Plex HTTP API to list audio playlists (`/playlists`) and music library albums. When you select an entry, cliamp gets its track list from the playlist-items or album-children endpoint. Queues, playlists, favorites, history, resume state and IPC keep only a token-free path: ``` -http://:32400/library/parts///file.?X-Plex-Token= +plex:track: ``` -These URLs serve files directly. Plex serves the original file without transcoding. cliamp handles playback through its HTTP streaming pipeline. cliamp can play MP3, FLAC, AAC, OGG, OPUS, WAV, and other supported source formats. +When playback starts, cliamp resolves that path to the Plex part URL in memory and adds your token to the request. The token is not written into new track paths. Entries saved by an earlier cliamp version keep the full stream URL, token included, until you remove them. The part URLs serve files directly. Plex serves the original file without transcoding. cliamp handles playback through its HTTP streaming pipeline. cliamp can play MP3, FLAC, AAC, OGG, OPUS, WAV, and other supported source formats. ## Troubleshooting diff --git a/external/plex/account.go b/external/plex/account.go new file mode 100644 index 000000000..8d105e5f1 --- /dev/null +++ b/external/plex/account.go @@ -0,0 +1,503 @@ +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. A +// network failure or a server error from plex.tv is retried on the next +// poll; any other HTTP error ends the sign-in. +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"` + } + err := s.api.doJSON(ctx, http.MethodGet, path, s.clientID, "", &pin) + if err != nil && (ctx.Err() != nil || !transient(err)) { + 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 { + // The scheme of the URI decides: it is what the request uses, and the + // protocol field can disagree with it. + u, err := url.Parse(connection.URI) + if err != nil { + return 100 + } + secure := u.Scheme == "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.sameOriginClient().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.sameOriginClient().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.sameOriginClient().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 &statusError{code: resp.StatusCode, status: 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) + } +} + +// sameOriginClient returns the account HTTP client with a redirect rule: +// it follows a redirect only to the same scheme and host. Go copies custom +// headers such as X-Plex-Token to a redirect target, and a probe that +// followed a redirect would vouch for the original address with another +// host's identity. A refused redirect returns the 3xx response, which the +// callers treat as an error. +func (a *AccountAPI) sameOriginClient() *http.Client { + client := *a.client + client.CheckRedirect = func(req *http.Request, via []*http.Request) error { + first := via[0].URL + if req.URL.Scheme != first.Scheme || !strings.EqualFold(req.URL.Host, first.Host) { + return http.ErrUseLastResponse + } + if len(via) >= 10 { + return errors.New("stopped after 10 redirects") + } + return nil + } + return &client +} + +// statusError is an HTTP error response from plex.tv. +type statusError struct { + code int + status string +} + +func (e *statusError) Error() string { return "HTTP " + e.status } + +// transient reports whether a plex.tv request may succeed when sent again: +// a network failure or a server error. +func transient(err error) bool { + if se, ok := errors.AsType[*statusError](err); ok { + return se.code >= 500 + } + return true +} diff --git a/external/plex/account_test.go b/external/plex/account_test.go new file mode 100644 index 000000000..0ad553a2a --- /dev/null +++ b/external/plex/account_test.go @@ -0,0 +1,458 @@ +package plex + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +func TestAccountSignIn(t *testing.T) { + var polls atomic.Int32 + 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": + n := polls.Add(1) + if got := r.URL.Query().Get("code"); got != "long-code" { + t.Errorf("code = %q, want long-code", got) + } + if n == 1 { + w.Write([]byte(`{"authToken":null}`)) + } else { + w.Write([]byte(`{"authToken":"account-token"}`)) + } + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.String()) + http.Error(w, "unexpected request", http.StatusBadRequest) + } + })) + 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.Errorf("path = %q", r.URL.Path) + http.NotFound(w, r) + return + } + 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) { + // The remote route answers only after the local one has, so the test + // does not depend on which loopback server the scheduler runs first. + localAnswered := make(chan struct{}) + var once sync.Once + local := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + identityHandler("server-1")(w, r) + once.Do(func() { close(localAnswered) }) + })) + defer local.Close() + + secure := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-localAnswered: + case <-r.Context().Done(): + return + } + identityHandler("server-1")(w, r) + })) + defer secure.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) + } +} + +// A public plain-HTTP route is never probed, even when the server would +// answer as the right one, and even when its metadata claims https. +func TestReachableConnectionRejectsPublicHTTP(t *testing.T) { + for _, protocol := range []string{"http", "https"} { + t.Run(protocol, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("public HTTP route got a request: %s", r.URL.Path) + identityHandler("server-1")(w, r) + })) + defer srv.Close() + + api := &AccountAPI{baseURL: "unused", client: srv.Client(), pollInterval: time.Millisecond} + _, _, err := api.ReachableConnection(context.Background(), AccountServer{ + Name: "Unsafe", + ClientIdentifier: "server-1", + Connections: []AccountConnection{{URI: srv.URL, Protocol: protocol}}, + }, "account-token", "client-1") + if err == nil || !strings.Contains(err.Error(), "no reachable secure connection") { + t.Fatalf("error = %v", err) + } + }) + } +} + +// A probe does not follow a redirect to another host: the original address +// has not shown that it is the server. +func TestReachableConnectionRejectsRedirectedIdentity(t *testing.T) { + target := httptest.NewServer(identityHandler("server-1")) + defer target.Close() + redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target.URL+"/identity", http.StatusFound) + })) + defer redirector.Close() + + api := &AccountAPI{baseURL: "unused", client: redirector.Client(), pollInterval: time.Millisecond} + _, _, err := api.ReachableConnection(t.Context(), AccountServer{ + Name: "Home", + ClientIdentifier: "server-1", + Connections: []AccountConnection{{URI: redirector.URL, Protocol: "http", Local: true}}, + }, "account-token", "client-1") + if err == nil { + t.Fatal("a redirected identity was accepted") + } +} + +// The account token never follows a redirect off the plex.tv origin. +func TestAccountKeepsTokenOnOrigin(t *testing.T) { + other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("redirect target got a request, token %q", r.Header.Get("X-Plex-Token")) + w.Write([]byte(`[]`)) + })) + defer other.Close() + tv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, other.URL+r.URL.Path, http.StatusTemporaryRedirect) + })) + defer tv.Close() + + api := &AccountAPI{baseURL: tv.URL, client: tv.Client(), pollInterval: time.Millisecond} + if _, err := api.Servers(t.Context(), "account-token", "client-1"); err == nil { + t.Fatal("Servers: a cross-origin redirect was followed") + } + if err := api.SignOut(t.Context(), "account-token", "client-1"); err == nil { + t.Fatal("SignOut: a cross-origin redirect was followed") + } +} + +// A failed poll while the user approves the PIN does not end the sign-in; +// an HTTP client error such as an expired PIN does. +func TestAccountSignInRetriesTransientPolls(t *testing.T) { + for _, tc := range []struct { + name string + failure int + wantErr bool + }{ + {"server error", http.StatusBadGateway, false}, + {"expired PIN", http.StatusNotFound, true}, + } { + t.Run(tc.name, func(t *testing.T) { + var polls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if polls.Add(1) == 1 { + w.WriteHeader(tc.failure) + return + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"authToken":"account-token"}`)) + })) + defer srv.Close() + + api := &AccountAPI{baseURL: srv.URL, client: srv.Client(), pollInterval: time.Millisecond} + session := &SignInSession{api: api, id: 42, code: "code", clientID: "client-1"} + token, err := session.Wait(t.Context()) + if tc.wantErr { + if err == nil { + t.Fatalf("Wait = %q, want an error", token) + } + return + } + if err != nil || token != "account-token" { + t.Fatalf("Wait = %q, %v; want account-token", token, err) + } + }) + } +} + +// A dropped connection during a poll is retried too. +func TestAccountSignInRetriesNetworkFailure(t *testing.T) { + var polls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if polls.Add(1) == 1 { + conn, _, err := w.(http.Hijacker).Hijack() + if err == nil { + conn.Close() + } + return + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"authToken":"account-token"}`)) + })) + defer srv.Close() + + api := &AccountAPI{baseURL: srv.URL, client: srv.Client(), pollInterval: time.Millisecond} + session := &SignInSession{api: api, id: 42, code: "code", clientID: "client-1"} + if token, err := session.Wait(t.Context()); err != nil || token != "account-token" { + t.Fatalf("Wait = %q, %v; want account-token", token, 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) { + var checks atomic.Int32 + 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.Add(1) + w.WriteHeader(tt.user) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL) + http.Error(w, "unexpected request", http.StatusBadRequest) + } + })) + 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 got := int(checks.Load()); got != tt.wantChecks { + t.Fatalf("token checks = %d, want %d", got, 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..40bc193c8 100644 --- a/external/plex/client.go +++ b/external/plex/client.go @@ -2,13 +2,19 @@ package plex import ( + "context" + "errors" "fmt" + "io" "net/http" "net/url" "strconv" "strings" + "sync" + "sync/atomic" "time" + "github.com/bjarneo/cliamp/applog" "github.com/bjarneo/cliamp/internal/httpclient" "github.com/bjarneo/cliamp/internal/netdiag" ) @@ -22,16 +28,243 @@ 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 + // refresh asks endpoint to rediscover the route. RefreshConnection sets + // it without c.mu, which endpoint holds for a whole discovery, so the + // UI goroutine never waits on plex.tv. + refresh atomic.Bool +} + +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.refresh.Swap(false) { + c.account.connected = false + } + 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. +// +// On a plain-HTTP route of an account-backed client, send first checks +// without the token that the address still answers as the server: after a +// network change another host can hold it. An HTTPS route needs no check, +// since its certificate belongs to the server. A failed check counts as an +// unreachable route. +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) + } + err = c.verifyPlainRoute(ctx, baseURL) + if err == nil { + var resp *http.Response + if resp, err = c.do(client, req); 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 + } + // The route goes even when this was the retry, so the next request + // does not wait on it again. + if ctx.Err() != nil || !c.dropRoute(baseURL) || retried { + return nil, fmt.Errorf("plex: %s: server unreachable: %w", label, netdiag.Explain(err)) + } + applog.Info("plex: %s: %v; finding another server route", label, netdiag.Explain(err)) + } +} + +// dropRoute makes the next request rediscover the route when baseURL is still +// the current one. It reports whether rediscovery is possible: manual clients +// have only their configured URL. +func (c *Client) dropRoute(baseURL string) bool { + c.mu.Lock() + defer c.mu.Unlock() + if c.account == nil { + return false + } + if c.baseURL == baseURL { + c.account.connected = false + } + return true +} + +// do sends one request. An account-backed client bounds the wait for +// headers, so it can move to another route; a manual client has no other +// route and keeps the client's own timeout. +func (c *Client) do(client *http.Client, req *http.Request) (*http.Response, error) { + c.mu.Lock() + account := c.account != nil + c.mu.Unlock() + if !account { + return client.Do(req) + } + return doWithHeaderDeadline(client, req) +} + +// doWithHeaderDeadline sends req and cancels it when no response headers +// arrive within responseHeaderTimeout. The body read is not limited by it. +// When the deadline fires, the request fails even if headers arrived at the +// same moment: the cancel may already be on its way to the body. +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 && fired { + resp.Body.Close() + } + if err != nil || fired { + cancel() + if fired && req.Context().Err() == nil { + return nil, fmt.Errorf("no response in %s", timeout) + } + if err == nil { + err = req.Context().Err() + } + 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 +} + +// CheckRoute makes sure an account-backed client has a route that answers +// as its server. A stream goes to the player, not through send, so a route +// that died during playback is found here, before the next track's URL is +// built on it. The check sends no token: after a network change the cached +// local address can belong to another host. When the route fails, CheckRoute +// rediscovers once. A manual client has no other route and makes no request. +func (c *Client) CheckRoute() error { + c.mu.Lock() + account := c.account + c.mu.Unlock() + if account == nil { + return nil + } + ctx := context.Background() + for retried := false; ; retried = true { + baseURL, _, err := c.endpoint(ctx) + if err != nil { + return fmt.Errorf("plex: connect account server: %w", err) + } + err = account.verify(ctx, baseURL) + if err == nil { + return nil + } + c.dropRoute(baseURL) + if retried { + return fmt.Errorf("plex: check server route: %w", netdiag.Explain(err)) + } + applog.Info("plex: check server route: %v; finding another server route", netdiag.Explain(err)) + } +} + +// verify checks without a token that baseURL answers as the selected +// server. The error does not name the URL. +func (a *accountBinding) verify(ctx context.Context, baseURL string) error { + ctx, cancel := context.WithTimeout(ctx, responseHeaderTimeout) + defer cancel() + err := a.api.probe(ctx, baseURL, a.serverID, a.clientID) + if uerr, ok := errors.AsType[*url.Error](err); ok { + return uerr.Err + } + return err +} + +// verifyPlainRoute runs verify for an account-backed client on a route +// that is not HTTPS. Other routes need no check and return nil. +func (c *Client) verifyPlainRoute(ctx context.Context, baseURL string) error { + if c.account == nil || strings.HasPrefix(baseURL, "https://") { + return nil + } + return c.account.verify(ctx, baseURL) +} + +// RefreshConnection makes an account-backed client rediscover its route on +// the next request. Manual clients keep their configured URL unchanged. It +// does not block: the UI goroutine calls it, also while a discovery runs. +func (c *Client) RefreshConnection() { + c.refresh.Store(true) } // Section represents a Plex library section (e.g. a music library). @@ -73,22 +306,23 @@ type Playlist struct { // get issues an authenticated GET request and decodes the JSON response into result. func (c *Client) get(path string, params url.Values, result any) error { - 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") - - resp, err := apiClient.Do(req) + resp, err := c.send(context.Background(), apiClient, path, func(baseURL, token string) (*http.Request, error) { + query := url.Values{} + for k, v := range params { + query[k] = v + } + query.Set("X-Plex-Token", token) + req, err := http.NewRequest(http.MethodGet, 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() @@ -374,10 +608,28 @@ func (c *Client) Search(query string) ([]Track, error) { return tracks, nil } +// Track returns one track by its ratingKey. +func (c *Client) Track(ratingKey string) (Track, error) { + var result struct { + MediaContainer struct { + Metadata []trackJSON `json:"Metadata"` + } `json:"MediaContainer"` + } + if err := c.get("/library/metadata/"+ratingKey, nil, &result); err != nil { + return Track{}, err + } + if len(result.MediaContainer.Metadata) == 0 { + return Track{}, fmt.Errorf("plex: track %s not found", ratingKey) + } + return trackFromJSON(result.MediaContainer.Metadata[0]), nil +} + // StreamURL returns the authenticated HTTP URL for streaming a track part. // partKey is the relative path from the Part element, e.g. "/library/parts/…/file.flac". // The token is appended as a query parameter; Plex accepts it in either header or query form. func (c *Client) StreamURL(partKey string) string { + c.mu.Lock() + defer c.mu.Unlock() return c.baseURL + partKey + "?X-Plex-Token=" + url.QueryEscape(c.token) } diff --git a/external/plex/client_test.go b/external/plex/client_test.go index 2c9cf224c..659c06513 100644 --- a/external/plex/client_test.go +++ b/external/plex/client_test.go @@ -3,12 +3,15 @@ package plex import ( "errors" "fmt" + "io" "net/http" "net/http/httptest" "slices" "strconv" "strings" + "sync/atomic" "testing" + "time" "github.com/bjarneo/cliamp/internal/httpclient" ) @@ -720,3 +723,407 @@ func TestPingRejectsOversizedBody(t *testing.T) { t.Fatalf("Ping() error = %v, want httpclient.ErrTooLarge", err) } } + +func TestAccountClientRediscoversSelectedServer(t *testing.T) { + var serverRequests atomic.Int32 + media := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + serverRequests.Add(1) + 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() + + var discoveries atomic.Int32 + account := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + discoveries.Add(1) + 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 got := discoveries.Load(); got != 2 { + t.Fatalf("resource discoveries = %d, want 2", got) + } + // Each Ping on this plain-HTTP route: the discovery probe, the + // tokenless check before the token is sent, and the request. + if got := serverRequests.Load(); got != 6 { + t.Fatalf("server requests = %d, want 6", got) + } +} + +func failoverFixture(t *testing.T, dead *httptest.Server) (*Client, *httptest.Server, *atomic.Int32) { + 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 "/library/metadata/200": + w.Write([]byte(`{"MediaContainer":{"Metadata":[{"ratingKey":"200","Media":[{"Part":[{"key":"/library/parts/1/111/file.flac"}]}]}]}}`)) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(alive.Close) + discoveries := new(atomic.Int32) + tv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + discoveries.Add(1) + 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.Load() != 1 { + t.Fatalf("route = %q after %d discoveries, want %q after 1", c.baseURL, discoveries.Load(), 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) + } + }) +} + +func TestClientKeepsRouteOnHTTPError(t *testing.T) { + failing := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/identity" { + identityHandler("server-1")(w, r) + return + } + 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.Load() != 0 || c.baseURL != failing.URL { + t.Fatalf("an HTTP error rediscovered the route: %d discoveries, route %q", discoveries.Load(), 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 +} + +// A route that died while a track played is found before the next track: +// ResolveSource builds its URL on the route that answers. +func TestResolveSourceMovesOffDeadRoute(t *testing.T) { + dead := httptest.NewServer(http.NotFoundHandler()) + dead.Close() + c, alive, discoveries := failoverFixture(t, dead) + p := newProvider(c) + p.partKeys = map[string]string{"200": "/library/parts/1/111/file.flac"} + + got, err := p.ResolveSource(TrackURIPrefix + "200") + if err != nil { + t.Fatalf("ResolveSource: %v", err) + } + if !strings.HasPrefix(got, alive.URL+"/library/parts/1/111/file.flac?") || discoveries.Load() != 1 { + t.Fatalf("ResolveSource = %q after %d discoveries, want the live route after 1", got, discoveries.Load()) + } +} + +// A manual client checks no route before a track. +func TestManualResolveSourceSendsNoRequest(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("unexpected request %s", r.URL.Path) + })) + defer srv.Close() + p := newProvider(NewClient(srv.URL, "tok")) + p.partKeys = map[string]string{"200": "/library/parts/1/111/file.flac"} + if _, err := p.ResolveSource(TrackURIPrefix + "200"); err != nil { + t.Fatalf("ResolveSource: %v", err) + } +} + +// After a network change the cached plain-HTTP address can belong to +// another Plex server. No request sends it the token: not a library request, +// not the metadata lookup of a track whose part is unknown, not the check +// before a track. Each moves to the route that answers as the selected +// server. +func TestPlainRouteGetsNoTokenFromAnotherServer(t *testing.T) { + for _, tt := range []struct { + name string + run func(t *testing.T, c *Client) string + }{ + {"library request", func(t *testing.T, c *Client) string { + sections, err := c.MusicSections() + if err != nil || len(sections) != 1 { + t.Fatalf("MusicSections = %v, %v", sections, err) + } + return "" + }}, + {"track with a known part", func(t *testing.T, c *Client) string { + p := newProvider(c) + p.partKeys = map[string]string{"200": "/library/parts/1/111/file.flac"} + got, err := p.ResolveSource(TrackURIPrefix + "200") + if err != nil { + t.Fatalf("ResolveSource: %v", err) + } + return got + }}, + {"track after a restart", func(t *testing.T, c *Client) string { + got, err := newProvider(c).ResolveSource(TrackURIPrefix + "200") + if err != nil { + t.Fatalf("ResolveSource: %v", err) + } + return got + }}, + } { + t.Run(tt.name, func(t *testing.T) { + stranger := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.URL.Query().Get("X-Plex-Token") + r.Header.Get("X-Plex-Token"); got != "" { + t.Errorf("other server got token %q on %s", got, r.URL.Path) + } + identityHandler("other-server")(w, r) + })) + t.Cleanup(stranger.Close) + c, alive, discoveries := failoverFixture(t, stranger) + + got := tt.run(t, c) + if got != "" && !strings.HasPrefix(got, alive.URL+"/library/parts/1/111/file.flac?") { + t.Fatalf("stream URL = %q, want the selected server", got) + } + if c.baseURL != alive.URL || discoveries.Load() != 1 { + t.Fatalf("route = %q after %d discoveries, want %q after 1", c.baseURL, discoveries.Load(), alive.URL) + } + }) + } +} + +// An HTTPS route needs no identity check: its certificate belongs to the +// server. A manual client makes none either. +func TestVerifyPlainRouteSkipsHTTPSAndManual(t *testing.T) { + probed := false + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + probed = true + })) + defer srv.Close() + api := &AccountAPI{baseURL: "unused", client: srv.Client(), pollInterval: time.Millisecond} + account := newAccountClient("", "account-token", "client-1", "server-1", api) + if err := account.verifyPlainRoute(t.Context(), "https://192-168-1-10.abc.plex.direct:32400"); err != nil { + t.Fatalf("https route: %v", err) + } + if err := NewClient(srv.URL, "tok").verifyPlainRoute(t.Context(), srv.URL); err != nil || probed { + t.Fatalf("manual client: err = %v, probed = %v", err, probed) + } + if err := account.verifyPlainRoute(t.Context(), srv.URL); err == nil { + t.Fatal("plain route with no identity passed the check") + } +} + +// Ctrl+R calls RefreshConnection on the UI goroutine. It returns at once +// even while a discovery holds the client, and the next request rediscovers. +func TestRefreshConnectionDoesNotWaitForDiscovery(t *testing.T) { + media := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/identity" { + identityHandler("server-1")(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"MediaContainer":{"friendlyName":"Home"}}`)) + })) + defer media.Close() + var discoveries atomic.Int32 + entered := make(chan struct{}) + release := make(chan struct{}) + tv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if discoveries.Add(1) == 1 { + close(entered) + <-release + } + 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 tv.Close() + api := &AccountAPI{baseURL: tv.URL, client: tv.Client(), pollInterval: time.Millisecond} + c := newAccountClient("http://stale.invalid", "account-token", "client-1", "server-1", api) + + pinged := make(chan error, 1) + go func() { pinged <- c.Ping() }() + <-entered + refreshed := make(chan struct{}) + go func() { + c.RefreshConnection() + close(refreshed) + }() + select { + case <-refreshed: + case <-time.After(2 * time.Second): + close(release) + t.Fatal("RefreshConnection waited for the discovery") + } + close(release) + if err := <-pinged; err != nil { + t.Fatalf("first Ping: %v", err) + } + if err := c.Ping(); err != nil { + t.Fatalf("second Ping: %v", err) + } + if got := discoveries.Load(); got != 2 { + t.Fatalf("discoveries = %d, want 2: the refresh must reach the next request", got) + } +} + +// When the retry fails too, its route is dropped as well, so the next +// request rediscovers instead of waiting on a known dead route. +func TestClientDropsRouteWhenRetryFails(t *testing.T) { + dead := httptest.NewServer(http.NotFoundHandler()) + dead.Close() + flaky := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/identity" { + identityHandler("server-1")(w, r) + return + } + if conn, _, err := w.(http.Hijacker).Hijack(); err == nil { + conn.Close() + } + })) + t.Cleanup(flaky.Close) + tv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + 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}]}]`, flaky.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) + c.account.connected = true + + if _, err := c.MusicSections(); err == nil { + t.Fatal("MusicSections: want an error from the failing retry") + } + if c.account.connected { + t.Fatalf("route %q stays connected after the retry failed", c.baseURL) + } +} + +// A manual client has no other route, so a slow server keeps the full API +// timeout instead of the account client's header deadline. +func TestManualClientWaitsPastHeaderDeadline(t *testing.T) { + old := responseHeaderTimeout + responseHeaderTimeout = 20 * time.Millisecond + t.Cleanup(func() { responseHeaderTimeout = old }) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + time.Sleep(100 * time.Millisecond) + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"MediaContainer":{"friendlyName":"Home"}}`)) + })) + defer srv.Close() + if err := NewClient(srv.URL, "tok").Ping(); err != nil { + t.Fatalf("Ping: %v", err) + } +} + +// lateTransport returns a response after the header deadline has fired, +// ignoring the cancel, as a response that races the timer would. +type lateTransport struct{ delay time.Duration } + +func (lt lateTransport) RoundTrip(req *http.Request) (*http.Response, error) { + time.Sleep(lt.delay) + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("{}")), Request: req}, nil +} + +// A response that arrives after the deadline fired is not returned: its +// body could already be cancelled. +func TestHeaderDeadlineWinsOverLateResponse(t *testing.T) { + old := responseHeaderTimeout + responseHeaderTimeout = 10 * time.Millisecond + t.Cleanup(func() { responseHeaderTimeout = old }) + client := &http.Client{Transport: lateTransport{delay: 50 * time.Millisecond}} + resp, err := doWithHeaderDeadline(client, mustRequest(t, "http://plex.invalid/")) + if err == nil { + resp.Body.Close() + t.Fatal("a response after the deadline was returned") + } + if err.Error() != "no response in 10ms" { + t.Fatalf("error = %v, want no response in 10ms", err) + } +} diff --git a/external/plex/provider.go b/external/plex/provider.go index ad5c60220..bd468e897 100644 --- a/external/plex/provider.go +++ b/external/plex/provider.go @@ -16,6 +16,9 @@ import ( // the browse view. Playlist IDs are prefixed so they can be told apart from // album ratingKeys (both live in the same server-side metadata key space). const ( + // TrackURIPrefix starts the token-free path that queues, history, + // favorites, playlists, resume state and IPC keep for a Plex track. + TrackURIPrefix = "plex:track:" prefixPlaylist = "pl:" sectionAlbums = "Albums" sectionPlaylists = "Playlists" @@ -37,6 +40,7 @@ type Provider struct { mu sync.Mutex playlistCache []playlist.PlaylistInfo trackCache map[string][]playlist.Track + partKeys map[string]string // ratingKey to stream part } // newProvider returns a Provider backed by the given Client. @@ -44,11 +48,16 @@ func newProvider(client *Client) *Provider { return &Provider{client: client} } -// NewFromConfig returns a Provider from a PlexConfig, or nil if URL or Token is missing. +// NewFromConfig returns a Provider from a PlexConfig, or nil when it holds no +// credentials. A browser sign-in, with client_id and server_id, finds the +// server's route through plex.tv; a manual setup uses its URL. func NewFromConfig(cfg config.PlexConfig) *Provider { if !cfg.IsSet() { return nil } + if cfg.ClientID != "" && cfg.ServerID != "" { + return newProvider(NewAccountClient(cfg.URL, cfg.Token, cfg.ClientID, cfg.ServerID, cfg.Libraries...)) + } return newProvider(NewClient(cfg.URL, cfg.Token, cfg.Libraries...)) } @@ -119,21 +128,25 @@ func (p *Provider) Playlists() ([]playlist.PlaylistInfo, error) { } // Refresh clears cached playlist and track data so the next call re-fetches -// from the server. Implements playlist.Refresher. +// from the server. A browser sign-in also finds the server's route again. +// Implements playlist.Refresher. func (p *Provider) Refresh() { p.mu.Lock() p.playlistCache = nil p.trackCache = nil + p.partKeys = nil p.mu.Unlock() + p.client.RefreshConnection() } // Tracks returns the tracks for the playlist or album identified by // playlistID. Playlist IDs (prefixed "pl:") load via the server playlists // endpoint; album IDs load via the album children endpoint. Each track's Path -// is a complete authenticated HTTP URL ready for the player. Tracks with no -// streamable part (missing Media/Part data) are silently skipped. Album tracks -// are cached per album ID; playlist tracks are intentionally not cached so -// smart playlists always reflect their current server contents. +// is a token-free plex:track: URI that ResolveSource turns into a +// stream URL at play time. Tracks with no streamable part (missing Media/Part +// data) are silently skipped. Album tracks are cached per album ID; playlist +// tracks are intentionally not cached so smart playlists always reflect their +// current server contents. func (p *Provider) Tracks(playlistID string) ([]playlist.Track, error) { isPlaylist := strings.HasPrefix(playlistID, prefixPlaylist) @@ -184,15 +197,23 @@ func (p *Provider) SearchTracks(_ context.Context, query string, limit int) ([]p } // convertTracks converts Plex tracks to playlist tracks, skipping entries -// without a streamable part. If limit > 0, at most limit tracks are returned. +// without a valid ratingKey or a streamable part. If limit > 0, at most limit +// tracks are returned. Each Path is a token-free plex:track: URI; +// ResolveSource adds the token when playback starts. func (p *Provider) convertTracks(plexTracks []Track, limit int) []playlist.Track { tracks := make([]playlist.Track, 0, len(plexTracks)) + p.mu.Lock() + defer p.mu.Unlock() for _, t := range plexTracks { - if t.PartKey == "" { + if !validRatingKey(t.RatingKey) || t.PartKey == "" { continue } + if p.partKeys == nil { + p.partKeys = make(map[string]string) + } + p.partKeys[t.RatingKey] = t.PartKey tracks = append(tracks, playlist.Track{ - Path: p.client.StreamURL(t.PartKey), + Path: TrackURIPrefix + t.RatingKey, Title: t.Title, Artist: t.ArtistName, Album: t.AlbumName, @@ -208,6 +229,55 @@ func (p *Provider) convertTracks(plexTracks []Track, limit int) []playlist.Track return tracks } +// ResolveSource turns a plex:track: URI into an authenticated stream URL when +// playback starts. After a restart the part is not known yet, so it reads +// the track's metadata once. +func (p *Provider) ResolveSource(uri string) (string, error) { + id, ok := strings.CutPrefix(uri, TrackURIPrefix) + if !ok || !validRatingKey(id) { + return "", fmt.Errorf("plex: invalid track uri %q", uri) + } + // The route may have died while the last track played. The check comes + // before any request that carries the token. + if err := p.client.CheckRoute(); err != nil { + return "", fmt.Errorf("plex: resolve track %s: %w", id, err) + } + p.mu.Lock() + partKey := p.partKeys[id] + p.mu.Unlock() + if partKey == "" { + track, err := p.client.Track(id) + if err != nil { + return "", fmt.Errorf("plex: resolve track %s: %w", id, err) + } + if track.PartKey == "" { + return "", fmt.Errorf("plex: track %s has no streamable part", id) + } + partKey = track.PartKey + p.mu.Lock() + if p.partKeys == nil { + p.partKeys = make(map[string]string) + } + p.partKeys[id] = partKey + p.mu.Unlock() + } + return p.client.StreamURL(partKey), nil +} + +// validRatingKey reports whether id is safe to put in a metadata path. +func validRatingKey(id string) bool { + if id == "" { + return false + } + for _, r := range id { + if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && + (r < '0' || r > '9') && r != '-' && r != '_' { + return false + } + } + return true +} + // AlbumTracks returns the tracks for the given album (ratingKey). // Implements provider.AlbumTrackLoader. func (p *Provider) AlbumTracks(albumID string) ([]playlist.Track, error) { diff --git a/external/plex/provider_test.go b/external/plex/provider_test.go index 466e97a17..0ccda3745 100644 --- a/external/plex/provider_test.go +++ b/external/plex/provider_test.go @@ -220,14 +220,15 @@ func TestProvider_Tracks(t *testing.T) { if !tr.Stream { t.Error("Stream = false, want true") } - if !strings.HasPrefix(tr.Path, srv.URL) { - t.Errorf("Path %q does not start with server URL", tr.Path) + if tr.Path != TrackURIPrefix+"200" { + t.Errorf("Path = %q, want %q", tr.Path, TrackURIPrefix+"200") } - if !strings.Contains(tr.Path, "X-Plex-Token=tok") { - t.Errorf("Path %q missing X-Plex-Token", tr.Path) + got, err := p.ResolveSource(tr.Path) + if err != nil { + t.Fatalf("ResolveSource: %v", err) } - if !strings.Contains(tr.Path, "/library/parts/1/111/SoWhat.flac") { - t.Errorf("Path %q missing part key", tr.Path) + if !strings.HasPrefix(got, srv.URL+"/library/parts/1/111/SoWhat.flac?") || !strings.Contains(got, "X-Plex-Token=tok") { + t.Errorf("ResolveSource = %q, want the authenticated part URL", got) } } @@ -264,11 +265,72 @@ func TestProvider_Tracks_Playlist(t *testing.T) { if !tr.Stream { t.Error("Stream = false, want true") } - if !strings.Contains(tr.Path, "X-Plex-Token=tok") { - t.Errorf("Path %q missing X-Plex-Token", tr.Path) + if tr.Path != TrackURIPrefix+"300" { + t.Errorf("Path = %q, want %q", tr.Path, TrackURIPrefix+"300") + } +} + +// After a restart the queue holds only plex:track: paths. ResolveSource +// reads the track's part from the server and adds the token. +func TestProviderResolveSourceRestoresAfterRestart(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/library/metadata/200" { + t.Errorf("path = %q, want the metadata lookup", r.URL.Path) + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"MediaContainer":{"Metadata":[{"ratingKey":"200","Media":[{"Part":[{"key":"/library/parts/1/111/file.flac"}]}]}]}}`)) + })) + defer srv.Close() + + p := newProvider(NewClient(srv.URL, "tok")) + got, err := p.ResolveSource(TrackURIPrefix + "200") + if err != nil { + t.Fatalf("ResolveSource: %v", err) + } + if !strings.HasPrefix(got, srv.URL+"/library/parts/1/111/file.flac?") || !strings.Contains(got, "X-Plex-Token=tok") { + t.Fatalf("ResolveSource = %q, want the authenticated part URL", got) + } +} + +// Refresh forgets the cached parts: a file replaced in Plex keeps its +// ratingKey but gets a new part, and the next play must use the new one. +func TestProviderRefreshForgetsParts(t *testing.T) { + part := "/library/parts/1/111/old.flac" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"MediaContainer":{"Metadata":[{"ratingKey":"200","Media":[{"Part":[{"key":"` + part + `"}]}]}]}}`)) + })) + defer srv.Close() + + p := newProvider(NewClient(srv.URL, "tok")) + if _, err := p.ResolveSource(TrackURIPrefix + "200"); err != nil { + t.Fatalf("ResolveSource: %v", err) + } + part = "/library/parts/2/222/new.flac" + p.Refresh() + got, err := p.ResolveSource(TrackURIPrefix + "200") + if err != nil { + t.Fatalf("ResolveSource after Refresh: %v", err) + } + if !strings.HasPrefix(got, srv.URL+part+"?") { + t.Fatalf("ResolveSource after Refresh = %q, want the new part", got) } - if !strings.Contains(tr.Path, "/library/parts/3/333/HighwayToHell.flac") { - t.Errorf("Path %q missing part key", tr.Path) +} + +// A path that is not a plain ratingKey never reaches the server. +func TestProviderResolveSourceRejectsBadPaths(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("unexpected request %s", r.URL.Path) + })) + defer srv.Close() + + p := newProvider(NewClient(srv.URL, "tok")) + for _, path := range []string{TrackURIPrefix, TrackURIPrefix + "../200", TrackURIPrefix + "200?x=1", "yandex:track:200"} { + if _, err := p.ResolveSource(path); err == nil { + t.Errorf("ResolveSource(%q): got no error", path) + } } } @@ -450,3 +512,15 @@ func TestNewFromConfig_LibrariesWired(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") + } +} diff --git a/providers.go b/providers.go index 60f3140e6..c927b2214 100644 --- a/providers.go +++ b/providers.go @@ -369,6 +369,16 @@ func (s *providerSet) registerPlayerHooks(p *player.Player) { } } switch prov := e.Provider.(type) { + case *plex.Provider: + // Plex tracks carry token-free plex:track: URIs; the provider + // adds the token in memory when playback starts. + p.RegisterSourceResolver(plex.TrackURIPrefix, func(uri string) (player.ResolvedSource, error) { + u, err := prov.ResolveSource(uri) + if err != nil { + return player.ResolvedSource{}, fmt.Errorf("resolve Plex source: %w", err) + } + return player.ResolvedSource{URL: u, Buffered: true}, nil + }) case *yandex.Provider: // Yandex tracks carry yandex:track: URIs; the provider resolves them // to a fresh signed stream URL when playback starts. diff --git a/providers_test.go b/providers_test.go index d2f4c4d48..96fa62752 100644 --- a/providers_test.go +++ b/providers_test.go @@ -18,6 +18,7 @@ import ( "github.com/bjarneo/cliamp/external/emby" "github.com/bjarneo/cliamp/external/jellyfin" "github.com/bjarneo/cliamp/external/navidrome" + "github.com/bjarneo/cliamp/external/plex" "github.com/bjarneo/cliamp/favorites" "github.com/bjarneo/cliamp/history" "github.com/bjarneo/cliamp/internal/resume" @@ -209,6 +210,16 @@ func TestProviderSetUsesCapabilities(t *testing.T) { } } +func TestProviderSetRegistersPlexSourceResolver(t *testing.T) { + prov := plex.NewFromConfig(config.PlexConfig{URL: "http://127.0.0.1:1", Token: "token"}) + set := &providerSet{entries: []provider.Entry{{Key: "plex", Name: "Plex", Provider: prov}}} + engine := &player.Player{} + set.registerPlayerHooks(engine) + if !engine.HasSourceResolver(plex.TrackURIPrefix + "42") { + t.Fatal("Plex source resolver was not registered") + } +} + // A page URL that playlist.IsYTDL accepts opens through yt-dlp, also when a // Jellyfin server registers a source resolver for every https URL. func TestPlayerHooksSendYTDLPagesToYTDLP(t *testing.T) { diff --git a/site/index.html b/site/index.html index f9ff9cb51..016628e1b 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 sign-in · remote discovery"}, {name:"Jellyfin",kind:"self-hosted",note:"API key / password, gapless, resume"}, {name:"Emby",kind:"self-hosted",note:"API key / password, resume"}, {name:"Navidrome",kind:"self-hosted",note:"Subsonic API · lyrics"},