diff --git a/CHANGELOG.md b/CHANGELOG.md index d5682fe..e1acb5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] +### Fixed +- Preserve saved scenes on failed volume/mute reads and report grouping or audio-setting failures when applying scenes. Thanks @SebTardif. +- Report missing queue positions after enqueueing without starting unrelated playback; explain how to recover without enqueueing twice. Thanks @SebTardif. +- Honor explicit speaker IPs when saving and applying scenes. + +### Changed +- Use Go 1.27.4 for build, CI, Docker and release tooling while retaining Go 1.26 compatibility; update pflag to 1.1.0. + ## [0.3.5] - 2026-10-23 **Highlights:** Fix the reachable crypto/x509 vulnerability GO-2026-6809 with Go 1.27.3, explain SMAPI API-client identity rejections, and correctly label initial watch events. diff --git a/Dockerfile b/Dockerfile index cb2196e..9fae0a2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ # syntax=docker/dockerfile:1.27.0 -ARG GO_VERSION=1.27.3 +ARG GO_VERSION=1.27.4 FROM golang:${GO_VERSION}-bookworm AS build WORKDIR /src diff --git a/docs/commands/sonos-scene.md b/docs/commands/sonos-scene.md index 42a4736..de08e3f 100644 --- a/docs/commands/sonos-scene.md +++ b/docs/commands/sonos-scene.md @@ -41,7 +41,7 @@ sonos scene apply evening --only "Kitchen" # experimental | --- | --- | | `--only string` | Restore only the saved state for one room (experimental). | -Apply is best-effort and idempotent — if a member is offline, that step is skipped and the rest of the scene is still applied. +Apply is idempotent. Speakers absent from the current topology are skipped; a failed command to a visible speaker stops the operation with an error. Completed changes are not rolled back. ## `sonos scene delete` @@ -52,3 +52,5 @@ sonos scene delete evening ## See also - [Scenes](../scenes.md) — what's captured, what isn't, and how apply works under the hood. + +Save preserves the existing file when a volume or mute read fails. Save and apply accept `--ip ` to bypass discovery for the topology query. diff --git a/docs/install.md b/docs/install.md index b0fcfcb..7ae04b5 100644 --- a/docs/install.md +++ b/docs/install.md @@ -28,7 +28,7 @@ go install github.com/steipete/sonoscli/cmd/sonos@latest sonos --version ``` -Source builds retain Go 1.26 as the minimum and prefer Go 1.27.3 via `go.mod`. CI and Docker builds use the same preferred patch version. +Source builds retain Go 1.26 as the minimum and prefer Go 1.27.4 via `go.mod`. CI and Docker builds use the same preferred patch version. The binary lands in `$(go env GOBIN)` (defaults to `$HOME/go/bin`) — make sure that's on your `PATH`. diff --git a/docs/scenes.md b/docs/scenes.md index d533325..eb6692d 100644 --- a/docs/scenes.md +++ b/docs/scenes.md @@ -23,7 +23,7 @@ sonos scene apply evening sonos scene delete evening ``` -Apply is best-effort and idempotent — running `sonos scene apply evening` twice is safe. +Apply is idempotent. It stops and reports any speaker command failure; already completed changes are not rolled back. ## Targeting one room (experimental) @@ -62,14 +62,16 @@ sonos open --name "Living Room" spotify:playlist:37i9dQZF1DXcBWIGoYBM5M 4. Re-create the saved groups (each member joins the saved coordinator). 5. Re-apply per-room volume and mute. -If a speaker named in the scene has gone offline, the corresponding step is logged and skipped — the rest of the scene still applies. +Speakers absent from the current topology are skipped. A command failure on a visible speaker stops the apply operation and returns an error. ## File layout Scenes live alongside your config: ``` -~/.config/sonoscli/scenes/.json +/sonoscli/scenes.json ``` The format is intentionally readable and stable; you can hand-edit a scene file if you really want to. + +Saving a scene fails without replacing the saved file if any volume or mute read fails. Use `--ip ` with save or apply to read topology directly from that speaker, bypassing discovery. diff --git a/docs/testing.md b/docs/testing.md index 0017e46..be20f5c 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -28,7 +28,7 @@ Expected: - All commands exit `0` - CI should match `.github/workflows/ci.yml` (`gofmt`, coverage, `golangci-lint`, race tests, `go vet`) - CI enforces a minimum total coverage of `75%` (statement coverage across `./...`) and a focused `85%` floor for the stream proxy package. -- The main CI job uses the preferred Go 1.27.3 toolchain from `go.mod`; a separate job tests the Go 1.26.0 source minimum with automatic toolchain switching disabled. Docker and release builds use the same patched toolchain. +- The main CI job uses the preferred Go 1.27.4 toolchain from `go.mod`; a separate job tests the Go 1.26.0 source minimum with automatic toolchain switching disabled. Docker and release builds use the same patched toolchain. - To verify release builds without publishing or creating tags, dispatch `release-unified.yml` on `main` with the current version and `dry_run: true`. ## Live network test plan (manual) diff --git a/go.mod b/go.mod index d17f3b8..e94c5b7 100644 --- a/go.mod +++ b/go.mod @@ -2,11 +2,11 @@ module github.com/steipete/sonoscli go 1.26 -toolchain go1.27.3 +toolchain go1.27.4 require github.com/spf13/cobra v1.10.2 require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/spf13/pflag v1.0.10 // indirect + github.com/spf13/pflag v1.1.0 // indirect ) diff --git a/go.sum b/go.sum index ef5d78d..63e85d7 100644 --- a/go.sum +++ b/go.sum @@ -5,7 +5,7 @@ github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQD github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= -github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag= +github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/cli/scene.go b/internal/cli/scene.go index 3397adb..7fdb8c9 100644 --- a/internal/cli/scene.go +++ b/internal/cli/scene.go @@ -46,6 +46,13 @@ var newSceneSpeakerClient = func(ip string, timeout time.Duration) sceneSpeakerC return sonos.NewClient(ip, timeout) } +func sceneTopologyClient(ctx context.Context, flags *rootFlags) (sceneTopologyGetter, error) { + if strings.TrimSpace(flags.IP) != "" { + return sonos.NewClient(strings.TrimSpace(flags.IP), flags.Timeout), nil + } + return newSceneTopologyGetter(ctx, flags.Timeout) +} + func newSceneCmd(flags *rootFlags) *cobra.Command { cmd := &cobra.Command{ Use: "scene", @@ -116,7 +123,7 @@ func newSceneSaveCmd(flags *rootFlags) *cobra.Command { if err != nil { return err } - tg, err := newSceneTopologyGetter(cmd.Context(), flags.Timeout) + tg, err := sceneTopologyClient(cmd.Context(), flags) if err != nil { return err } @@ -165,8 +172,14 @@ func newSceneSaveCmd(flags *rootFlags) *cobra.Command { } seen[m.UUID] = true c := newSceneSpeakerClient(m.IP, flags.Timeout) - vol, _ := c.GetVolume(cmd.Context()) - mute, _ := c.GetMute(cmd.Context()) + vol, err := c.GetVolume(cmd.Context()) + if err != nil { + return fmt.Errorf("get volume for %s: %w", m.Name, err) + } + mute, err := c.GetMute(cmd.Context()) + if err != nil { + return fmt.Errorf("get mute for %s: %w", m.Name, err) + } scene.Devices = append(scene.Devices, scenes.SceneDevice{ UUID: m.UUID, Name: m.Name, @@ -213,7 +226,7 @@ func newSceneApplyCmd(flags *rootFlags) *cobra.Command { return errors.New("scene not found: " + name) } - tg, err := newSceneTopologyGetter(cmd.Context(), flags.Timeout) + tg, err := sceneTopologyClient(cmd.Context(), flags) if err != nil { return err } @@ -285,7 +298,9 @@ func newSceneApplyCmd(flags *rootFlags) *cobra.Command { if ip == "" { continue } - _ = newSceneSpeakerClient(ip, flags.Timeout).LeaveGroup(cmd.Context()) + if err := newSceneSpeakerClient(ip, flags.Timeout).LeaveGroup(cmd.Context()); err != nil { + return fmt.Errorf("leave group for %s: %w", dev.Name, err) + } } // Step 2: rebuild groups. @@ -342,8 +357,12 @@ func newSceneApplyCmd(flags *rootFlags) *cobra.Command { continue } c := newSceneSpeakerClient(ip, flags.Timeout) - _ = c.SetMute(cmd.Context(), dev.Mute) - _ = c.SetVolume(cmd.Context(), dev.Volume) + if err := c.SetMute(cmd.Context(), dev.Mute); err != nil { + return fmt.Errorf("set mute for %s: %w", dev.Name, err) + } + if err := c.SetVolume(cmd.Context(), dev.Volume); err != nil { + return fmt.Errorf("set volume for %s: %w", dev.Name, err) + } } return writeOK(cmd, flags, "scene.apply", map[string]any{"name": scene.Name, "only": strings.TrimSpace(only)}) diff --git a/internal/cli/scene_test.go b/internal/cli/scene_test.go index 7aaf01a..494f05e 100644 --- a/internal/cli/scene_test.go +++ b/internal/cli/scene_test.go @@ -71,14 +71,20 @@ type fakeSceneSpeaker struct { setVolCalls int setVolValue int + setVolErr error setMuteCalls int setMuteValue bool + setMuteErr error + + leaveErr error + volumeErr error + muteErr error } func (f *fakeSceneSpeaker) LeaveGroup(ctx context.Context) error { f.leaveCalls++ - return nil + return f.leaveErr } func (f *fakeSceneSpeaker) JoinGroup(ctx context.Context, coordinatorUUID string) error { @@ -87,17 +93,35 @@ func (f *fakeSceneSpeaker) JoinGroup(ctx context.Context, coordinatorUUID string return nil } -func (f *fakeSceneSpeaker) GetVolume(ctx context.Context) (int, error) { return f.volume, nil } +func (f *fakeSceneSpeaker) GetVolume(ctx context.Context) (int, error) { return f.volume, f.volumeErr } + func (f *fakeSceneSpeaker) SetVolume(ctx context.Context, volume int) error { f.setVolCalls++ f.setVolValue = volume - return nil + return f.setVolErr } -func (f *fakeSceneSpeaker) GetMute(ctx context.Context) (bool, error) { return f.mute, nil } +func (f *fakeSceneSpeaker) GetMute(ctx context.Context) (bool, error) { return f.mute, f.muteErr } func (f *fakeSceneSpeaker) SetMute(ctx context.Context, mute bool) error { f.setMuteCalls++ f.setMuteValue = mute - return nil + return f.setMuteErr +} + +func TestSceneTopologyExplicitIPBypassesDiscovery(t *testing.T) { + orig := newSceneTopologyGetter + t.Cleanup(func() { newSceneTopologyGetter = orig }) + newSceneTopologyGetter = func(context.Context, time.Duration) (sceneTopologyGetter, error) { + t.Fatal("explicit IP must bypass discovery") + return nil, nil + } + getter, err := sceneTopologyClient(context.Background(), &rootFlags{IP: "127.0.0.1", Timeout: time.Second}) + if err != nil { + t.Fatal(err) + } + client, ok := getter.(*sonos.Client) + if !ok || client.IP != "127.0.0.1" { + t.Fatalf("unexpected direct topology client: %#v", getter) + } } func TestSceneSaveCapturesGroupsAndDeviceAudio(t *testing.T) { @@ -269,6 +293,75 @@ func TestSceneApplyUngroupsJoinsAndRestoresAudio(t *testing.T) { } } +func TestSceneApplyReportsLeaveAndLevelErrors(t *testing.T) { + flags := &rootFlags{Timeout: 2 * time.Second, Format: formatJSON} + scene := scenes.Scene{ + Name: "Work", + Groups: []scenes.SceneGroup{{ + CoordinatorUUID: "RINCON_A1400", + MemberUUIDs: []string{"RINCON_A1400", "RINCON_B1400"}, + }}, + Devices: []scenes.SceneDevice{ + {UUID: "RINCON_A1400", Name: "A", IP: "192.168.1.10", Volume: 5, Mute: false}, + {UUID: "RINCON_B1400", Name: "B", IP: "192.168.1.11", Volume: 15, Mute: true}, + }, + } + top := sonos.Topology{ + ByIP: map[string]sonos.Member{ + "192.168.1.10": {Name: "A", IP: "192.168.1.10", UUID: "RINCON_A1400", IsVisible: true}, + "192.168.1.11": {Name: "B", IP: "192.168.1.11", UUID: "RINCON_B1400", IsVisible: true}, + }, + } + origStore := newSceneStore + origTG := newSceneTopologyGetter + origClient := newSceneSpeakerClient + t.Cleanup(func() { + newSceneStore = origStore + newSceneTopologyGetter = origTG + newSceneSpeakerClient = origClient + }) + newSceneTopologyGetter = func(ctx context.Context, timeout time.Duration) (sceneTopologyGetter, error) { + return &fakeSceneTopologyGetter{top: top}, nil + } + + cases := []struct { + name string + speaker *fakeSceneSpeaker + want string + }{ + {name: "leave", speaker: &fakeSceneSpeaker{ip: "192.168.1.10", leaveErr: errors.New("busy")}, want: "leave group for A"}, + {name: "mute", speaker: &fakeSceneSpeaker{ip: "192.168.1.10", setMuteErr: errors.New("busy")}, want: "set mute for A"}, + {name: "volume", speaker: &fakeSceneSpeaker{ip: "192.168.1.10", setVolErr: errors.New("busy")}, want: "set volume for A"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + store := &fakeSceneStore{scenes: map[string]scenes.Scene{"Work": scene}} + speakers := map[string]*fakeSceneSpeaker{ + "192.168.1.10": tc.speaker, + "192.168.1.11": {ip: "192.168.1.11"}, + } + newSceneStore = func() (scenes.Store, error) { return store, nil } + newSceneSpeakerClient = func(ip string, timeout time.Duration) sceneSpeakerClient { + return speakers[ip] + } + cmd := newSceneCmd(flags) + var out strings.Builder + cmd.SetOut(&out) + cmd.SetErr(newDiscardWriter()) + cmd.SetArgs([]string{"apply", "Work"}) + cmd.SilenceErrors = true + cmd.SilenceUsage = true + err := cmd.ExecuteContext(context.Background()) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("error = %v, want %q", err, tc.want) + } + if strings.Contains(out.String(), "scene.apply") { + t.Fatalf("printed success: %s", out.String()) + } + }) + } +} + func TestSceneApplyMissingScene(t *testing.T) { flags := &rootFlags{Timeout: 2 * time.Second} cmd := newSceneCmd(flags) @@ -354,3 +447,139 @@ func TestSceneDeleteJSON(t *testing.T) { t.Fatalf("unexpected output: %q", out.String()) } } + +func TestSceneSaveDoesNotStoreZeroWhenLevelReadFails(t *testing.T) { + flags := &rootFlags{Timeout: 2 * time.Second} + top := sonos.Topology{ + Groups: []sonos.Group{ + { + ID: "G1", + Coordinator: sonos.Member{ + Name: "Living Room", IP: "192.168.1.10", UUID: "RINCON_LR1400", + IsCoordinator: true, IsVisible: true, + }, + Members: []sonos.Member{ + {Name: "Living Room", IP: "192.168.1.10", UUID: "RINCON_LR1400", IsCoordinator: true, IsVisible: true}, + {Name: "Kitchen", IP: "192.168.1.11", UUID: "RINCON_K1400", IsVisible: true}, + }, + }, + }, + } + + origStore := newSceneStore + origTG := newSceneTopologyGetter + origClient := newSceneSpeakerClient + t.Cleanup(func() { + newSceneStore = origStore + newSceneTopologyGetter = origTG + newSceneSpeakerClient = origClient + }) + newSceneTopologyGetter = func(ctx context.Context, timeout time.Duration) (sceneTopologyGetter, error) { + return &fakeSceneTopologyGetter{top: top}, nil + } + + cases := []struct { + name string + speaker *fakeSceneSpeaker + want string + }{ + { + name: "volume", + speaker: &fakeSceneSpeaker{ip: "192.168.1.11", volumeErr: errors.New("timeout")}, + want: "get volume for Kitchen", + }, + { + name: "mute", + speaker: &fakeSceneSpeaker{ip: "192.168.1.11", volume: 20, muteErr: errors.New("timeout")}, + want: "get mute for Kitchen", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + store := &fakeSceneStore{} + speakers := map[string]*fakeSceneSpeaker{ + "192.168.1.10": {ip: "192.168.1.10", volume: 15}, + "192.168.1.11": tc.speaker, + } + newSceneStore = func() (scenes.Store, error) { return store, nil } + newSceneSpeakerClient = func(ip string, timeout time.Duration) sceneSpeakerClient { + return speakers[ip] + } + + cmd := newSceneCmd(flags) + cmd.SetOut(newDiscardWriter()) + cmd.SetErr(newDiscardWriter()) + cmd.SetArgs([]string{"save", "Morning"}) + cmd.SilenceErrors = true + cmd.SilenceUsage = true + err := cmd.ExecuteContext(context.Background()) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("error = %v, want %q", err, tc.want) + } + if store.put.Name != "" { + t.Fatalf("stored scene %q with volume %d mute %v", store.put.Name, firstVolume(store.put), firstMute(store.put)) + } + }) + } +} + +func TestSceneSaveKeepsAReportedZeroVolume(t *testing.T) { + flags := &rootFlags{Timeout: 2 * time.Second} + top := sonos.Topology{ + Groups: []sonos.Group{ + { + ID: "G1", + Coordinator: sonos.Member{ + Name: "Living Room", IP: "192.168.1.10", UUID: "RINCON_LR1400", + IsCoordinator: true, IsVisible: true, + }, + Members: []sonos.Member{ + {Name: "Living Room", IP: "192.168.1.10", UUID: "RINCON_LR1400", IsCoordinator: true, IsVisible: true}, + }, + }, + }, + } + store := &fakeSceneStore{} + origStore := newSceneStore + origTG := newSceneTopologyGetter + origClient := newSceneSpeakerClient + t.Cleanup(func() { + newSceneStore = origStore + newSceneTopologyGetter = origTG + newSceneSpeakerClient = origClient + }) + newSceneStore = func() (scenes.Store, error) { return store, nil } + newSceneTopologyGetter = func(ctx context.Context, timeout time.Duration) (sceneTopologyGetter, error) { + return &fakeSceneTopologyGetter{top: top}, nil + } + newSceneSpeakerClient = func(ip string, timeout time.Duration) sceneSpeakerClient { + return &fakeSceneSpeaker{ip: ip, volume: 0, mute: false} + } + + cmd := newSceneCmd(flags) + cmd.SetOut(newDiscardWriter()) + cmd.SetErr(newDiscardWriter()) + cmd.SetArgs([]string{"save", "Quiet"}) + cmd.SilenceErrors = true + cmd.SilenceUsage = true + if err := cmd.ExecuteContext(context.Background()); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(store.put.Devices) != 1 || store.put.Devices[0].Volume != 0 || store.put.Devices[0].Mute { + t.Fatalf("device = %+v", store.put.Devices) + } +} + +func firstVolume(scene scenes.Scene) int { + if len(scene.Devices) == 0 { + return -1 + } + return scene.Devices[0].Volume +} + +func firstMute(scene scenes.Scene) bool { + if len(scene.Devices) == 0 { + return false + } + return scene.Devices[0].Mute +} diff --git a/internal/sonos/queue.go b/internal/sonos/queue.go index 679dea7..9e85277 100644 --- a/internal/sonos/queue.go +++ b/internal/sonos/queue.go @@ -72,6 +72,14 @@ func (c *Client) PlayFromQueueTrack(ctx context.Context, oneBasedTrackNumber int return c.playFromQueueTrack(ctx, oneBasedTrackNumber) } +func (c *Client) startEnqueuedPlayback(ctx context.Context, firstTrack int) error { + if firstTrack <= 0 { + // The queue was not cleared, so track 1 can be an older item. + return errors.New("playback was not started because the speaker did not report the new queue position; the track is already on the queue. Run sonos queue list, then sonos queue play for this speaker. Do not enqueue the track again") + } + return c.playFromQueueTrack(ctx, firstTrack) +} + func (c *Client) playFromQueueTrack(ctx context.Context, oneBasedTrackNumber int) error { dd, err := c.GetDeviceDescription(ctx) if err != nil { diff --git a/internal/sonos/smapi_enqueue.go b/internal/sonos/smapi_enqueue.go index 351d5f4..94254f5 100644 --- a/internal/sonos/smapi_enqueue.go +++ b/internal/sonos/smapi_enqueue.go @@ -42,12 +42,10 @@ func (c *Client) EnqueueSMAPIItem(ctx context.Context, svc MusicServiceDescripto if err != nil { return 0, err } - if opts.PlayNow && first > 0 { - if err := c.playFromQueueTrack(ctx, first); err != nil { + if opts.PlayNow { + if err := c.startEnqueuedPlayback(ctx, first); err != nil { return first, err } - } else if opts.PlayNow { - _ = c.Play(ctx) } return first, nil } diff --git a/internal/sonos/smapi_enqueue_test.go b/internal/sonos/smapi_enqueue_test.go index 0d46825..8a8ff8b 100644 --- a/internal/sonos/smapi_enqueue_test.go +++ b/internal/sonos/smapi_enqueue_test.go @@ -68,6 +68,41 @@ func TestEnqueueSMAPIItem(t *testing.T) { } } +func TestEnqueueSMAPIItem_PlayNowMissingTrackNumber(t *testing.T) { + t.Parallel() + + var actions []string + c := &Client{ + IP: "192.0.2.1", + HTTP: &http.Client{Transport: roundTripperFunc(func(r *http.Request) (*http.Response, error) { + action := r.Header.Get("SOAPACTION") + actions = append(actions, action) + if strings.Contains(action, "AddURIToQueue") { + return httpResponse(200, ``), nil + } + if strings.Contains(action, "Play") { + return httpResponse(200, ``), nil + } + t.Fatalf("unexpected action %s", action) + return nil, nil + })}, + } + + _, err := c.EnqueueSMAPIItem(context.Background(), + MusicServiceDescriptor{ID: "2311", Name: "Spotify"}, + SMAPIItem{ID: "track-1", Title: "Song"}, + EnqueueOptions{PlayNow: true}, + ) + if err == nil || !enqueueMissingPositionMessage(err) { + t.Fatalf("error = %v", err) + } + for _, action := range actions { + if strings.Contains(action, "Play") { + t.Fatalf("started playback without a track number: %v", actions) + } + } +} + func TestEnqueueSMAPIItemValidation(t *testing.T) { t.Parallel() diff --git a/internal/sonos/spotify.go b/internal/sonos/spotify.go index 11dee37..bb3ab41 100644 --- a/internal/sonos/spotify.go +++ b/internal/sonos/spotify.go @@ -122,13 +122,10 @@ func (c *Client) EnqueueSpotify(ctx context.Context, input string, opts EnqueueO lastErr = err continue } - if opts.PlayNow && first > 0 { - if err := c.playFromQueueTrack(ctx, first); err != nil { + if opts.PlayNow { + if err := c.startEnqueuedPlayback(ctx, first); err != nil { return first, err } - } else if opts.PlayNow { - // If the speaker doesn't report a first track number, just call Play. - _ = c.Play(ctx) } return first, nil } diff --git a/internal/sonos/spotify_enqueue_test.go b/internal/sonos/spotify_enqueue_test.go index c060d9e..bb7694c 100644 --- a/internal/sonos/spotify_enqueue_test.go +++ b/internal/sonos/spotify_enqueue_test.go @@ -195,3 +195,56 @@ func TestClientEnqueueSpotify_TrackFallbacksToLegacyURI(t *testing.T) { t.Fatalf("attempted URIs mismatch: got %v want %v", attemptedURIs, expected) } } + +func TestClientEnqueueSpotify_PlayNowMissingTrackNumber(t *testing.T) { + t.Parallel() + + var actions []string + c := &Client{ + IP: "192.0.2.1", + HTTP: &http.Client{Transport: roundTripperFunc(func(r *http.Request) (*http.Response, error) { + if r.Method == http.MethodGet { + return httpResponse(200, `uuid:RINCON_ABC1400`), nil + } + action := r.Header.Get("SOAPACTION") + actions = append(actions, action) + if strings.Contains(action, "#AddURIToQueue") { + return httpResponse(200, ``), nil + } + if strings.Contains(action, "#Play") { + return httpResponse(200, ``), nil + } + t.Fatalf("unexpected SOAPACTION %q", action) + return nil, nil + })}, + } + + _, err := c.EnqueueSpotify(context.Background(), "spotify:track:abc123", EnqueueOptions{PlayNow: true}) + if err == nil || !enqueueMissingPositionMessage(err) { + t.Fatalf("error = %v", err) + } + for _, action := range actions { + if strings.Contains(action, "#Play") || strings.Contains(action, "#Seek") { + t.Fatalf("started playback without a track number: %v", actions) + } + } +} + +func enqueueMissingPositionMessage(err error) bool { + if err == nil { + return false + } + msg := err.Error() + for _, part := range []string{ + "playback was not started", + "already on the queue", + "sonos queue list", + "sonos queue play ", + "Do not enqueue the track again", + } { + if !strings.Contains(msg, part) { + return false + } + } + return true +}