mirror of
https://github.com/gesellix/Bose-SoundTouch.git
synced 2026-09-07 15:07:17 +00:00
Compare commits
205
Commits
@@ -86,7 +86,7 @@ body:
|
||||
attributes:
|
||||
label: AfterTouch version
|
||||
description: Shown in the admin UI footer, or via the binary's `--version`.
|
||||
placeholder: "v0.111.2"
|
||||
placeholder: "v0.123.0"
|
||||
validations:
|
||||
required: false
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# CodeQL configuration
|
||||
# https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning
|
||||
|
||||
name: "JavaScript/TypeScript Security Analysis"
|
||||
|
||||
disable-default-queries: false
|
||||
|
||||
queries:
|
||||
- uses: security-extended
|
||||
- uses: security-and-quality
|
||||
|
||||
# Paths to exclude from analysis
|
||||
paths-ignore:
|
||||
- "**/node_modules/**"
|
||||
# The minified es-module-shims distribution currently triggers findings in
|
||||
# third-party code. Keep this exception file-specific so Preact, HTM, and
|
||||
# future files under static/lib remain covered.
|
||||
- "pkg/service/soundtouchweb/static/lib/es-module-shims.js"
|
||||
@@ -0,0 +1,57 @@
|
||||
name: Browser Compatibility Tests
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
test-browser:
|
||||
name: Player browser tests
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version-file: "go.mod"
|
||||
|
||||
- name: Cache Go modules
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.cache/go-build
|
||||
~/go/pkg/mod
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.mod') }}-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-go-
|
||||
|
||||
- name: Download dependencies
|
||||
run: go mod download
|
||||
|
||||
- name: Verify a Chrome/Chromium binary is available
|
||||
# chromedp (used by the browsertest-tagged tests) discovers Chrome on
|
||||
# PATH or in a standard install location; GitHub's ubuntu-latest
|
||||
# runner image ships Google Chrome preinstalled. Fail fast here with a
|
||||
# clear message instead of a cryptic chromedp allocator error if that
|
||||
# image ever stops including it.
|
||||
run: google-chrome --version
|
||||
|
||||
- name: Run browser-level player compatibility tests
|
||||
run: make test-browser
|
||||
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: '24'
|
||||
|
||||
- name: Run frontend unit tests
|
||||
run: make test-frontend
|
||||
@@ -197,7 +197,7 @@ jobs:
|
||||
- name: Check documentation links
|
||||
run: |
|
||||
npm install -g markdown-link-check
|
||||
find . -name "*.md" -not -path "./tests/*" -not -path "./node_modules/*" -print0 | xargs -0 -n1 markdown-link-check -q -v -c .github/markdown-link-check.json
|
||||
./scripts/check-doc-links.sh
|
||||
|
||||
- name: Warn on pending images
|
||||
run: |
|
||||
@@ -308,7 +308,7 @@ jobs:
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
|
||||
uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4.3.0
|
||||
|
||||
- name: Set build date
|
||||
id: build_date
|
||||
|
||||
@@ -40,17 +40,17 @@ jobs:
|
||||
run: sudo apt-get install -y libpcap-dev
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@f205ea1c3313d32999d8d6a48b4f6530d4437b38 # v4.37.4
|
||||
uses: github/codeql-action/init@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4.37.9
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ matrix.build-mode }}
|
||||
config-file: ${{ matrix.language == 'go' && './.github/codeql-config.yml' || '' }}
|
||||
config-file: ${{ matrix.language == 'go' && './.github/codeql-config.yml' || matrix.language == 'javascript-typescript' && './.github/codeql-config-js.yml' || '' }}
|
||||
|
||||
- name: Build Go (required for manual build-mode)
|
||||
if: matrix.language == 'go'
|
||||
run: go build ./...
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@f205ea1c3313d32999d8d6a48b4f6530d4437b38 # v4.37.4
|
||||
uses: github/codeql-action/analyze@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4.37.9
|
||||
with:
|
||||
category: "/language:${{ matrix.language }}"
|
||||
|
||||
@@ -346,6 +346,14 @@ jobs:
|
||||
TAG_NAME="${{ needs.validate.outputs.tag }}"
|
||||
VERSION="${TAG_NAME#v}"
|
||||
|
||||
# Real per-platform links for the two most-used tools, generated
|
||||
# from the deterministic `<binary>-<tag>-<os>-<arch>[.exe]` asset
|
||||
# naming convention (see scripts/release/quick-downloads.sh),
|
||||
# instead of requiring a scroll through the flat, alphabetical
|
||||
# Assets list. Inline checksum link per row (à la Helm's release
|
||||
# notes) instead of sending people to the combined checksums file.
|
||||
QUICK_DOWNLOADS="$(scripts/release/quick-downloads.sh "$TAG_NAME" "${{ github.repository }}")"
|
||||
|
||||
# Short, accurate header. GitHub's auto-generated "What's Changed"
|
||||
# + "Full Changelog" are appended after this (generate_release_notes).
|
||||
cat > release_notes.md << EOF
|
||||
@@ -353,13 +361,15 @@ jobs:
|
||||
|
||||
**Bose SoundTouch Toolkit.** Keep your Bose SoundTouch speakers alive after the Bose cloud shutdown. No Bose infrastructure required.
|
||||
|
||||
$QUICK_DOWNLOADS
|
||||
|
||||
## What's included
|
||||
|
||||
Pre-built binaries for Linux (amd64, arm64, armv7), macOS (Intel & Apple Silicon), Windows (amd64), and FreeBSD (amd64):
|
||||
|
||||
- **soundtouch-service**: local server that replaces the Bose cloud. Point your speaker at it and you keep full control; the built-in web UI on port 8000 handles setup.
|
||||
- **soundtouch-service** (see above)
|
||||
- **soundtouch-cli** (see above)
|
||||
- **soundtouch-player**: standalone LAN web UI for device control: play/pause, volume, presets, live status. (Formerly \`soundtouch-web\`.)
|
||||
- **soundtouch-cli**: command-line control of any device: playback, presets, sources, multiroom zones, discovery, and migration. Good for scripting and home automation.
|
||||
- **soundtouch-backup**: back up your Bose cloud account and each speaker's local state. \`soundtouch-backup all\` captures everything in one step.
|
||||
|
||||
Not sure which file to grab? The [Downloads page](https://gesellix.github.io/Bose-SoundTouch/docs/downloads/) explains which tool you need and which \`<os>-<arch>\` build matches your computer.
|
||||
@@ -388,7 +398,7 @@ jobs:
|
||||
echo "release_notes_file=release_notes.md" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3.0.2
|
||||
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
|
||||
with:
|
||||
tag_name: ${{ needs.validate.outputs.tag }}
|
||||
name: ${{ needs.validate.outputs.tag }}
|
||||
@@ -414,14 +424,64 @@ jobs:
|
||||
if: github.event_name == 'release' && github.event.action == 'published'
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ needs.validate.outputs.tag }}
|
||||
|
||||
- name: Download release assets
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: release-assets
|
||||
path: ./release-assets
|
||||
|
||||
- name: Upgrade the Downloads footer with direct per-platform links
|
||||
# This is the path real releases take: a maintainer hand-writes
|
||||
# "Noteworthy" notes and publishes via the GitHub web UI, which
|
||||
# fires this job, not create_release (workflow_dispatch only).
|
||||
# _/releases/_TEMPLATE.md's convention is a trailing footer line:
|
||||
# ---
|
||||
# 📦 **Downloads / installation:** <downloads page URL>
|
||||
# Drop that line (if present) and append the quick-downloads
|
||||
# block in its place. Always goes through the same append path
|
||||
# (strip block + strip footer + append), whether or not a
|
||||
# footer line is still there, so re-runs stay byte-for-byte
|
||||
# idempotent instead of drifting on the 2nd run.
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
TAG_NAME="${{ needs.validate.outputs.tag }}"
|
||||
|
||||
scripts/release/quick-downloads.sh "$TAG_NAME" "${{ github.repository }}" > quick_downloads.md
|
||||
gh release view "$TAG_NAME" --json body -q .body > existing_body.md
|
||||
|
||||
python3 - << 'PYEOF'
|
||||
import re
|
||||
|
||||
with open("existing_body.md") as f:
|
||||
body = f.read()
|
||||
with open("quick_downloads.md") as f:
|
||||
block = f.read().rstrip("\n")
|
||||
|
||||
# Drop a block this automation inserted on a previous run.
|
||||
body = re.sub(r"\n*<!-- quick-downloads:start -->.*?<!-- quick-downloads:end -->\n*", "\n", body, flags=re.DOTALL)
|
||||
|
||||
# Drop the hand-authored footer line (first run only) so both
|
||||
# cases converge on the same append below and re-runs stay
|
||||
# byte-for-byte idempotent.
|
||||
footer = re.compile(r"^📦 \*\*Downloads / installation:\*\*.*\n?", re.MULTILINE)
|
||||
body = footer.sub("", body, count=1)
|
||||
|
||||
body = body.rstrip("\n") + "\n\n" + block + "\n"
|
||||
|
||||
with open("combined_notes.md", "w") as f:
|
||||
f.write(body)
|
||||
PYEOF
|
||||
|
||||
gh release edit "$TAG_NAME" --notes-file combined_notes.md
|
||||
|
||||
- name: Upload additional assets to existing release
|
||||
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3.0.2
|
||||
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
|
||||
with:
|
||||
tag_name: ${{ needs.validate.outputs.tag }}
|
||||
files: |
|
||||
@@ -454,7 +514,7 @@ jobs:
|
||||
echo "commit=$(git rev-parse HEAD)" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
|
||||
uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4.3.0
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||
|
||||
@@ -78,7 +78,7 @@ jobs:
|
||||
|
||||
- name: Upload Semgrep SARIF results
|
||||
if: always()
|
||||
uses: github/codeql-action/upload-sarif@f205ea1c3313d32999d8d6a48b4f6530d4437b38 # v4.37.4
|
||||
uses: github/codeql-action/upload-sarif@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4.37.9
|
||||
with:
|
||||
sarif_file: semgrep.sarif
|
||||
continue-on-error: true
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
# golangci-lint configuration for Bose SoundTouch Go Library
|
||||
# Compatible with golangci-lint v2.8.0
|
||||
# Compatible with golangci-lint v2.13.1
|
||||
# See: https://golangci-lint.run/usage/configuration/
|
||||
|
||||
version: "2"
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
# Build stage
|
||||
FROM --platform=$BUILDPLATFORM golang:1.26.5-alpine AS builder
|
||||
FROM --platform=$BUILDPLATFORM golang:1.27.1-alpine AS builder
|
||||
|
||||
# Declare automatic platform ARGs to make them available in build stage
|
||||
# See https://docs.docker.com/reference/dockerfile#automatic-platform-args-in-the-global-scope
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
.PHONY: all build build-cli test test-coverage test-http-client test-http-client-rotate check fmt vet lint clean dev help screenshots build-stockholm-image prepare-stockholm update-static-deps dev-docs dev-docs-tidy hugo
|
||||
.PHONY: all build build-cli test test-coverage test-browser test-frontend test-http-client test-http-client-rotate check fmt vet lint clean dev help screenshots build-stockholm-image prepare-stockholm update-static-deps dev-docs dev-docs-tidy hugo
|
||||
|
||||
# Load .env if present (simple KEY=VALUE format, no shell quoting)
|
||||
-include .env
|
||||
@@ -147,6 +147,23 @@ test-coverage:
|
||||
$(GOCMD) tool cover -html=coverage.out -o coverage.html
|
||||
@echo "Coverage report generated: coverage.html"
|
||||
|
||||
# Browser-level regression tests for the embedded player's static assets
|
||||
# (see pkg/service/soundtouchweb/browser_compatibility_test.go). Opt-in via
|
||||
# the "browsertest" build tag, not part of `test`/`check`, since they need a
|
||||
# Chrome/Chromium binary that chromedp can find on PATH or in a standard
|
||||
# install location.
|
||||
test-browser:
|
||||
@echo "Running browser-level compatibility tests..."
|
||||
$(GOTEST) -tags browsertest -v ./pkg/service/soundtouchweb/...
|
||||
|
||||
# Unit tests for the embedded player's static JS modules (see
|
||||
# pkg/service/soundtouchweb/frontend_test/), run via Node's built-in test
|
||||
# runner. Not part of `test`/`check`, since they need a Node binary matching
|
||||
# package.json's engines field, same reasoning as test-browser needing Chrome.
|
||||
test-frontend:
|
||||
@echo "Running frontend unit tests..."
|
||||
node --test pkg/service/soundtouchweb/frontend_test/*.test.mjs
|
||||
|
||||
check: fmt vet test test-http-client
|
||||
|
||||
# Archive any existing tests/integration/testdata/ to a timestamped sibling
|
||||
@@ -165,9 +182,16 @@ test-http-client-rotate:
|
||||
|
||||
test-http-client:
|
||||
@echo "Starting services with docker compose (waiting for healthchecks)..."
|
||||
@docker compose -f docker-compose.yml -f docker-compose.ci.yml up -d --build --wait
|
||||
@echo "Running .http tests..."
|
||||
@docker run --rm --network soundtouch-test-net \
|
||||
@docker compose -f docker-compose.yml -f docker-compose.ci.yml up -d --build --wait; \
|
||||
UP_EXIT_CODE=$$?; \
|
||||
if [ $$UP_EXIT_CODE -ne 0 ]; then \
|
||||
echo "docker compose up failed (exit $$UP_EXIT_CODE); dumping container logs:"; \
|
||||
docker compose -f docker-compose.yml -f docker-compose.ci.yml logs; \
|
||||
docker compose -f docker-compose.yml -f docker-compose.ci.yml down; \
|
||||
exit $$UP_EXIT_CODE; \
|
||||
fi; \
|
||||
echo "Running .http tests..."; \
|
||||
docker run --rm --network soundtouch-test-net \
|
||||
-v "$(PWD)/tests/integration/http-client:/workdir" \
|
||||
jetbrains/intellij-http-client:2026.1 \
|
||||
--env-file /workdir/http-client.env.json \
|
||||
@@ -227,9 +251,7 @@ test-http-client:
|
||||
/workdir/unregister_device.http \
|
||||
--report; \
|
||||
EXIT_CODE=$$?; \
|
||||
docker compose -f docker-compose.yml -f docker-compose.ci.yml logs soundtouch-service; \
|
||||
docker compose -f docker-compose.yml -f docker-compose.ci.yml logs spotify-mock; \
|
||||
docker compose -f docker-compose.yml -f docker-compose.ci.yml logs amazon-mock; \
|
||||
docker compose -f docker-compose.yml -f docker-compose.ci.yml logs; \
|
||||
docker compose -f docker-compose.yml -f docker-compose.ci.yml down; \
|
||||
exit $$EXIT_CODE
|
||||
|
||||
@@ -243,7 +265,7 @@ vet:
|
||||
|
||||
lint:
|
||||
@echo "Running golangci-lint..."
|
||||
@which golangci-lint > /dev/null || (echo "golangci-lint not found. Install with: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest" && exit 1)
|
||||
@which golangci-lint > /dev/null || (echo "golangci-lint not found. Install with: go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest" && exit 1)
|
||||
golangci-lint run
|
||||
|
||||
tidy:
|
||||
@@ -501,6 +523,8 @@ help:
|
||||
@echo " build-linux-armv7 - Build for Linux ARMv7 (kernel 3.14+ compatible, CGO_ENABLED=0)"
|
||||
@echo " test - Run tests"
|
||||
@echo " test-coverage - Run tests with coverage report"
|
||||
@echo " test-browser - Run browser-level (chromedp) player compatibility tests"
|
||||
@echo " test-frontend - Run player static JS unit tests (Node's test runner)"
|
||||
@echo " test-http-client - Run .http integration tests via Docker Compose"
|
||||
@echo " test-http-client-rotate - Archive tests/integration/testdata/ before a fresh run (non-destructive)"
|
||||
@echo " check - Run fmt, vet, and tests"
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
<p style="margin-top: -10px; font-style: italic; color: #666;">Bose SoundTouch Toolkit</p>
|
||||
|
||||
[](https://pkg.go.dev/github.com/gesellix/bose-soundtouch)
|
||||
[](https://goreportcard.com/report/github.com/gesellix/bose-soundtouch)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
|
||||
> Independent project. **Not affiliated with, endorsed by, sponsored
|
||||
@@ -113,6 +112,7 @@ See the [API Reference](https://gesellix.github.io/Bose-SoundTouch/docs/referenc
|
||||
- **[SoundTouch Plus](https://github.com/thlucas1/homeassistantcomponent_soundtouchplus)** (Todd Lucas) — Home Assistant integration; extensive undocumented API documentation
|
||||
- **[ÜberBöse API](https://github.com/julius-d/ueberboese-api)** (Julius) — API research and advanced endpoint discovery
|
||||
- **[Bose SoundTouch Hook](https://github.com/CodeFinder2/bose-soundtouch-hook)** (Adrian Böckenkamp) — `LD_PRELOAD` hooking for reverse engineering device internals
|
||||
- **[STR, SoundTouch Reborn](https://github.com/JRpersonal/streborn)** ([st-reborn.de](https://st-reborn.de)) — on-device agent plus desktop app; its published `iptables` REDIRECT technique is what makes AfterTouch's on-device install reachable over the LAN on co-processor chassis (see [Model Support Matrix](https://gesellix.github.io/Bose-SoundTouch/docs/reference/MODEL-SUPPORT-MATRIX/))
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package main
|
||||
|
||||
import "strings"
|
||||
|
||||
// sanitizeLog strips newline characters from s to prevent log-injection
|
||||
// (CodeQL go/log-injection). Values from HTTP requests may contain
|
||||
// attacker-controlled newlines.
|
||||
func sanitizeLog(s string) string {
|
||||
s = strings.ReplaceAll(s, "\n", `\n`)
|
||||
s = strings.ReplaceAll(s, "\r", `\r`)
|
||||
|
||||
return s
|
||||
}
|
||||
@@ -654,8 +654,8 @@ func withAccessLog(logger *slog.Logger, next http.Handler) http.Handler {
|
||||
r.Body = io.NopCloser(bytes.NewReader(body))
|
||||
|
||||
browseAttrs = []any{
|
||||
"objectID", between(string(body), "<ObjectID>", "</ObjectID>"),
|
||||
"browseFlag", between(string(body), "<BrowseFlag>", "</BrowseFlag>"),
|
||||
"objectID", sanitizeLog(between(string(body), "<ObjectID>", "</ObjectID>")),
|
||||
"browseFlag", sanitizeLog(between(string(body), "<BrowseFlag>", "</BrowseFlag>")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -664,7 +664,7 @@ func withAccessLog(logger *slog.Logger, next http.Handler) http.Handler {
|
||||
|
||||
attrs := []any{
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"path", sanitizeLog(r.URL.Path),
|
||||
"status", rec.status,
|
||||
"bytes", rec.bytes,
|
||||
"from", r.RemoteAddr,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/updatecheck"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
// updateCheckRepo is the GitHub repo checked for newer releases, matching
|
||||
// soundtouch-service's periodic background check (#591,
|
||||
// _/i591/design-update-check.md).
|
||||
const updateCheckRepo = "gesellix/Bose-SoundTouch"
|
||||
|
||||
// updateCheckCommand assembles the on-demand `soundtouch-backup
|
||||
// update-check` command, the CLI-side answer to that design doc's open
|
||||
// question 2 (CLI-only users get no update notice from the service's
|
||||
// background checker). Unlike the service's opt-in periodic check, running
|
||||
// this command *is* the opt-in: no config flag, no persisted state, just
|
||||
// one GitHub API request each time it's invoked.
|
||||
func updateCheckCommand() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "update-check",
|
||||
Usage: "Check GitHub for a newer soundtouch-backup release",
|
||||
Action: runUpdateCheck,
|
||||
}
|
||||
}
|
||||
|
||||
func runUpdateCheck(c *cli.Context) error {
|
||||
checker := updatecheck.NewChecker(nil, updateCheckRepo, version)
|
||||
|
||||
result, err := checker.CheckNow(c.Context)
|
||||
if err != nil {
|
||||
return fmt.Errorf("update check failed: %w", err)
|
||||
}
|
||||
|
||||
printUpdateCheckResult(result)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func printUpdateCheckResult(result updatecheck.Result) {
|
||||
if result.LatestVersion == "" {
|
||||
fmt.Printf("Running %s, not a released version, skipping comparison.\n", result.CurrentVersion)
|
||||
return
|
||||
}
|
||||
|
||||
if result.Available {
|
||||
fmt.Printf("A newer version is available: %s (you're on %s)\n", result.LatestVersion, result.CurrentVersion)
|
||||
fmt.Println(result.ReleaseURL)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("You're on the latest version (%s).\n", result.CurrentVersion)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/updatecheck"
|
||||
)
|
||||
|
||||
// TestUpdateCheckCommand_Registered checks the command is wired up with the
|
||||
// expected name and an Action, without making any real GitHub API calls.
|
||||
func TestUpdateCheckCommand_Registered(t *testing.T) {
|
||||
cmd := updateCheckCommand()
|
||||
|
||||
if cmd.Name != "update-check" {
|
||||
t.Errorf("command name = %q; want %q", cmd.Name, "update-check")
|
||||
}
|
||||
|
||||
if cmd.Action == nil {
|
||||
t.Error("expected an Action to be set")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrintUpdateCheckResult_DoesNotPanic exercises all three result shapes
|
||||
// (unparseable current version, update available, up to date) purely for
|
||||
// the "does not panic" guarantee; updatecheck.Checker's own tests already
|
||||
// cover the comparison logic itself.
|
||||
func TestPrintUpdateCheckResult_DoesNotPanic(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
result updatecheck.Result
|
||||
}{
|
||||
{"unparseable current version", updatecheck.Result{CurrentVersion: "dev"}},
|
||||
{"update available", updatecheck.Result{CurrentVersion: "v1.0.0", LatestVersion: "v1.1.0", Available: true, ReleaseURL: "https://example.invalid"}},
|
||||
{"up to date", updatecheck.Result{CurrentVersion: "v1.1.0", LatestVersion: "v1.1.0", Available: false}},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
printUpdateCheckResult(tc.result)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,7 @@ func main() {
|
||||
allCommand(),
|
||||
cloudCommand(),
|
||||
localCommand(),
|
||||
updateCheckCommand(),
|
||||
},
|
||||
}
|
||||
if err := app.Run(os.Args); err != nil {
|
||||
|
||||
+192
-256
@@ -3,11 +3,10 @@ package main
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
"net/http"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/client"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/speaker"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/stereopair"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
@@ -16,32 +15,26 @@ func getGroupStatus(c *cli.Context) error {
|
||||
clientConfig := GetClientConfig(c)
|
||||
PrintDeviceHeader("Getting group information", clientConfig.Host, clientConfig.Port)
|
||||
|
||||
client, err := CreateSoundTouchClient(clientConfig)
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("Failed to create client: %v", err))
|
||||
return err
|
||||
}
|
||||
|
||||
group, err := client.GetGroup()
|
||||
result, err := newGroupCoordinator(clientConfig).Inspect(clientConfig.Host)
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("Failed to get group: %v", err))
|
||||
printGroupResultDetails(result)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
if group.IsEmpty() {
|
||||
if result.Group == nil || result.Group.IsEmpty() {
|
||||
fmt.Println("Device is not in a stereo pair")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
printGroup(group)
|
||||
printGroup(result.Group)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// createGroup forms a stereo pair by POSTing /addGroup to both speakers in
|
||||
// parallel. LEFT is the master. Addressing each speaker directly (instead of
|
||||
// only the master and letting it propagate via marge) sidesteps the
|
||||
// inter-device round-trip that surfaced as client timeouts in #252.
|
||||
// createGroup forms and verifies a stereo pair. LEFT is always the master.
|
||||
func createGroup(c *cli.Context) error {
|
||||
leftIP := c.String("left")
|
||||
rightIP := c.String("right")
|
||||
@@ -49,283 +42,117 @@ func createGroup(c *cli.Context) error {
|
||||
|
||||
if net.ParseIP(leftIP) == nil {
|
||||
PrintError(fmt.Sprintf("Invalid left IP address: %s", leftIP))
|
||||
|
||||
return fmt.Errorf("invalid left IP: %s", leftIP)
|
||||
}
|
||||
|
||||
if net.ParseIP(rightIP) == nil {
|
||||
PrintError(fmt.Sprintf("Invalid right IP address: %s", rightIP))
|
||||
|
||||
return fmt.Errorf("invalid right IP: %s", rightIP)
|
||||
}
|
||||
|
||||
PrintDeviceHeader(fmt.Sprintf("Creating stereo pair: LEFT=%s RIGHT=%s", leftIP, rightIP), leftIP, speaker.HTTPPort)
|
||||
clientConfig := GetClientConfig(c)
|
||||
PrintDeviceHeader(fmt.Sprintf("Creating stereo pair: LEFT=%s RIGHT=%s", leftIP, rightIP), leftIP, clientConfig.Port)
|
||||
|
||||
leftInfo, err := fetchDeviceInfo(c, leftIP)
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("Failed to read LEFT device info: %v", err))
|
||||
return err
|
||||
}
|
||||
|
||||
rightInfo, err := fetchDeviceInfo(c, rightIP)
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("Failed to read RIGHT device info: %v", err))
|
||||
return err
|
||||
}
|
||||
|
||||
if name == "" {
|
||||
name = fmt.Sprintf("%s + %s", leftInfo.Name, rightInfo.Name)
|
||||
}
|
||||
|
||||
req := &models.Group{
|
||||
result, err := newGroupCoordinator(clientConfig).Create(stereopair.CreateRequest{
|
||||
LeftIPAddress: leftIP,
|
||||
RightIPAddress: rightIP,
|
||||
Name: name,
|
||||
MasterDeviceID: leftInfo.DeviceID,
|
||||
Roles: models.GroupRoles{
|
||||
Roles: []models.GroupRole{
|
||||
{DeviceID: leftInfo.DeviceID, Role: "LEFT", IPAddress: leftIP},
|
||||
{DeviceID: rightInfo.DeviceID, Role: "RIGHT", IPAddress: rightIP},
|
||||
},
|
||||
},
|
||||
// SenderIPAddress is intentionally omitted on the base request.
|
||||
// propagateAddGroup adds it to the slave's copy only — see comment there.
|
||||
}
|
||||
|
||||
leftClient, err := clientForHost(c, leftIP)
|
||||
})
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("Failed to create client for LEFT: %v", err))
|
||||
PrintError(fmt.Sprintf("Failed to create stereo pair: %v", err))
|
||||
printGroupResultDetails(result)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
rightClient, err := clientForHost(c, rightIP)
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("Failed to create client for RIGHT: %v", err))
|
||||
return err
|
||||
}
|
||||
|
||||
leftOut, rightOut := propagateAddGroup(leftClient, rightClient, leftIP, rightIP, req)
|
||||
|
||||
if leftOut.err != nil {
|
||||
PrintError(fmt.Sprintf("LEFT (%s) /addGroup failed: %v", leftIP, leftOut.err))
|
||||
}
|
||||
|
||||
if rightOut.err != nil {
|
||||
PrintError(fmt.Sprintf("RIGHT (%s) /addGroup failed: %v", rightIP, rightOut.err))
|
||||
}
|
||||
|
||||
if leftOut.err != nil || rightOut.err != nil {
|
||||
if (leftOut.err == nil) != (rightOut.err == nil) {
|
||||
succeeded := leftIP
|
||||
if leftOut.err != nil {
|
||||
succeeded = rightIP
|
||||
}
|
||||
|
||||
PrintError(fmt.Sprintf("Partial group state on %s — clean up with `soundtouch-cli --host %s group remove`", succeeded, succeeded))
|
||||
}
|
||||
|
||||
return fmt.Errorf("/addGroup propagation failed")
|
||||
}
|
||||
|
||||
// The LEFT (master) response carries the assigned group ID; use it for display.
|
||||
PrintSuccess(fmt.Sprintf("Stereo pair created (id=%s)", leftOut.group.ID))
|
||||
printGroup(leftOut.group)
|
||||
PrintSuccess(fmt.Sprintf("Stereo pair created (id=%s)", result.Group.ID))
|
||||
printGroup(result.Group)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// addGroupOutcome is the per-speaker result of a parallel /addGroup call.
|
||||
type addGroupOutcome struct {
|
||||
host string
|
||||
group *models.Group
|
||||
err error
|
||||
}
|
||||
|
||||
// propagateAddGroup POSTs /addGroup to both speakers concurrently and returns
|
||||
// the (LEFT, RIGHT) outcomes. A non-GROUP_OK Status in the response is
|
||||
// reported as an error so callers don't have to re-inspect the body.
|
||||
//
|
||||
// The two POSTs carry different payloads: the master (LEFT) receives the base
|
||||
// request with no senderIPAddress so its state machine forms the group as the
|
||||
// master, while the slave (RIGHT) receives a copy with senderIPAddress set to
|
||||
// the master's IP so its state machine joins as the slave. Sending the same
|
||||
// payload to both makes both speakers think they're the slave — they enter
|
||||
// AddingSlave, wait for a master that never confirms, time out after 5 s, and
|
||||
// revert (issue #252).
|
||||
func propagateAddGroup(left, right *client.Client, leftIP, rightIP string, req *models.Group) (addGroupOutcome, addGroupOutcome) {
|
||||
masterReq := *req
|
||||
masterReq.SenderIPAddress = ""
|
||||
|
||||
slaveReq := *req
|
||||
slaveReq.SenderIPAddress = leftIP
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
leftOut, rightOut addGroupOutcome
|
||||
)
|
||||
|
||||
wg.Add(2)
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
leftOut = postAddGroup(left, leftIP, &masterReq)
|
||||
}()
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
rightOut = postAddGroup(right, rightIP, &slaveReq)
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
|
||||
return leftOut, rightOut
|
||||
}
|
||||
|
||||
func postAddGroup(cli *client.Client, host string, req *models.Group) addGroupOutcome {
|
||||
out := addGroupOutcome{host: host}
|
||||
|
||||
g, err := cli.AddGroup(req)
|
||||
if err != nil {
|
||||
out.err = err
|
||||
return out
|
||||
}
|
||||
|
||||
out.group = g
|
||||
|
||||
if g != nil && g.Status != "" && g.Status != "GROUP_OK" {
|
||||
out.err = fmt.Errorf("device returned status %q (want GROUP_OK)", g.Status)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
// renameGroup updates the name of the existing stereo pair. The device
|
||||
// requires the full structure on every update, so we fetch the current
|
||||
// state first.
|
||||
// renameGroup updates and verifies the name on both stereo-pair members.
|
||||
func renameGroup(c *cli.Context) error {
|
||||
clientConfig := GetClientConfig(c)
|
||||
newName := c.String("name")
|
||||
|
||||
if newName == "" {
|
||||
PrintError("--name is required")
|
||||
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
PrintDeviceHeader(fmt.Sprintf("Renaming stereo pair to %q", newName), clientConfig.Host, clientConfig.Port)
|
||||
|
||||
stClient, err := CreateSoundTouchClient(clientConfig)
|
||||
coordinator := newGroupCoordinator(clientConfig)
|
||||
|
||||
current, err := coordinator.Inspect(clientConfig.Host)
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("Failed to create client: %v", err))
|
||||
PrintError(fmt.Sprintf("Failed to inspect stereo pair before rename: %v", err))
|
||||
printGroupResultDetails(current)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
current, err := stClient.GetGroup()
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("Failed to read current group: %v", err))
|
||||
return err
|
||||
if current.Group == nil || current.Group.IsEmpty() {
|
||||
return fmt.Errorf("device is not in a stereo pair")
|
||||
}
|
||||
|
||||
if current.IsEmpty() {
|
||||
PrintError("Device is not in a stereo pair — nothing to rename")
|
||||
return fmt.Errorf("no group configured")
|
||||
}
|
||||
|
||||
// Status is read-only on the device side; don't echo it back.
|
||||
current.Status = ""
|
||||
current.Name = newName
|
||||
|
||||
result, err := stClient.UpdateGroup(current)
|
||||
result, err := coordinator.Rename(stereopair.RenameRequest{
|
||||
MemberIPAddress: clientConfig.Host,
|
||||
ExpectedGroupID: current.Group.ID,
|
||||
Name: newName,
|
||||
})
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("Failed to rename group: %v", err))
|
||||
printGroupResultDetails(result)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
PrintSuccess(fmt.Sprintf("Stereo pair renamed to %q", result.Name))
|
||||
printGroup(result)
|
||||
PrintSuccess(fmt.Sprintf("Stereo pair renamed to %q", result.Group.Name))
|
||||
printGroup(result.Group)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// removeGroup tears down the device's stereo pair by sending /removeGroup to
|
||||
// every member in parallel. Sending it only to the master (as the old code
|
||||
// did) leaves the slave stuck in GroupSlave state indefinitely — mirrors the
|
||||
// same symmetry as createGroup (see issue #252 comment there).
|
||||
// removeGroup dissolves and verifies the stereo pair on every member.
|
||||
func removeGroup(c *cli.Context) error {
|
||||
clientConfig := GetClientConfig(c)
|
||||
PrintDeviceHeader("Removing stereo pair", clientConfig.Host, clientConfig.Port)
|
||||
|
||||
stClient, err := CreateSoundTouchClient(clientConfig)
|
||||
coordinator := newGroupCoordinator(clientConfig)
|
||||
|
||||
current, err := coordinator.Inspect(clientConfig.Host)
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("Failed to create client: %v", err))
|
||||
return err
|
||||
PrintWarning(fmt.Sprintf("Stereo pair is degraded before removal: %v", err))
|
||||
printGroupResultDetails(current)
|
||||
|
||||
if current.Group == nil || current.Group.IsEmpty() {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch current group to learn every member's IP before tearing down.
|
||||
group, err := stClient.GetGroup()
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("Failed to read current group: %v", err))
|
||||
return err
|
||||
}
|
||||
|
||||
if group.IsEmpty() {
|
||||
if current.Group == nil || current.Group.IsEmpty() {
|
||||
fmt.Println("Device is not in a stereo pair — nothing to remove")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Collect the unique set of member IPs. The master is always reachable
|
||||
// via clientConfig.Host; the roles carry all members including slaves.
|
||||
type memberResult struct {
|
||||
ip string
|
||||
err error
|
||||
}
|
||||
dissolveHost := dissolveRecoveryHost(current, clientConfig.Host)
|
||||
|
||||
members := make([]string, 0, len(group.Roles.Roles))
|
||||
seen := map[string]bool{}
|
||||
result, err := coordinator.Dissolve(stereopair.DissolveRequest{
|
||||
MemberIPAddress: dissolveHost,
|
||||
ExpectedGroupID: current.Group.ID,
|
||||
ExpectedGroup: current.Group,
|
||||
})
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("Failed to remove stereo pair: %v", err))
|
||||
printGroupResultDetails(result)
|
||||
|
||||
for _, role := range group.Roles.Roles {
|
||||
if role.IPAddress != "" && !seen[role.IPAddress] {
|
||||
seen[role.IPAddress] = true
|
||||
members = append(members, role.IPAddress)
|
||||
}
|
||||
}
|
||||
|
||||
// Always include the addressed host even if the group response omitted IPs.
|
||||
if !seen[clientConfig.Host] {
|
||||
members = append(members, clientConfig.Host)
|
||||
}
|
||||
|
||||
results := make([]memberResult, len(members))
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i, ip := range members {
|
||||
wg.Add(1)
|
||||
|
||||
go func(idx int, host string) {
|
||||
defer wg.Done()
|
||||
|
||||
mc, mcErr := clientForHost(c, host)
|
||||
if mcErr != nil {
|
||||
results[idx] = memberResult{ip: host, err: mcErr}
|
||||
return
|
||||
}
|
||||
|
||||
results[idx] = memberResult{ip: host, err: mc.RemoveGroup()}
|
||||
}(i, ip)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
anyErr := false
|
||||
|
||||
for _, r := range results {
|
||||
if r.err != nil {
|
||||
PrintError(fmt.Sprintf("%s /removeGroup failed: %v", r.ip, r.err))
|
||||
|
||||
anyErr = true
|
||||
}
|
||||
}
|
||||
|
||||
if anyErr {
|
||||
return fmt.Errorf("/removeGroup propagation failed")
|
||||
return err
|
||||
}
|
||||
|
||||
PrintSuccess("Stereo pair removed")
|
||||
@@ -333,32 +160,141 @@ func removeGroup(c *cli.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// fetchDeviceInfo builds a one-off client for the given IP and reads /info.
|
||||
// Reused for both halves of a `create` invocation so the caller doesn't have
|
||||
// to babysit two host/port pairs.
|
||||
func fetchDeviceInfo(c *cli.Context, host string) (*models.DeviceInfo, error) {
|
||||
stClient, err := clientForHost(c, host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
func dissolveRecoveryHost(result stereopair.Result, fallback string) string {
|
||||
if result.Group == nil || result.Group.ID == "" {
|
||||
return fallback
|
||||
}
|
||||
|
||||
return stClient.GetDeviceInfo()
|
||||
for i := range result.Members {
|
||||
member := &result.Members[i]
|
||||
if member.Group != nil && member.Group.ID == result.Group.ID && net.ParseIP(member.IPAddress) != nil {
|
||||
return member.IPAddress
|
||||
}
|
||||
}
|
||||
|
||||
return fallback
|
||||
}
|
||||
|
||||
// clientForHost mirrors CreateSoundTouchClient but overrides the host so we
|
||||
// can talk to a speaker other than the one named in --host.
|
||||
func clientForHost(c *cli.Context, host string) (*client.Client, error) {
|
||||
cfg, err := loadConfig(c.Duration("timeout"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to load config: %w", err)
|
||||
func newGroupCoordinator(config *ClientConfig) *stereopair.Coordinator {
|
||||
lifecycleConfig := *config
|
||||
if lifecycleConfig.Timeout < stereopair.RequestTimeout {
|
||||
lifecycleConfig.Timeout = stereopair.RequestTimeout
|
||||
}
|
||||
|
||||
return client.NewClient(&client.Config{
|
||||
Host: host,
|
||||
Port: speaker.HTTPPort,
|
||||
Timeout: cfg.HTTPTimeout,
|
||||
UserAgent: cfg.UserAgent,
|
||||
}), nil
|
||||
cleanupClient := &http.Client{Timeout: lifecycleConfig.Timeout}
|
||||
cleanup, preflight, rename := cliStereoPairGenerationPersistence(cleanupClient)
|
||||
|
||||
return stereopair.NewWithGenerationLifecyclePersistence(
|
||||
groupClientFactory(&lifecycleConfig),
|
||||
cleanup, preflight, rename,
|
||||
)
|
||||
}
|
||||
|
||||
// cliStereoPairGenerationPersistence wires generation-lifecycle hooks for
|
||||
// the CLI: cleanup and rename are no-ops, and preflight's read-only
|
||||
// dangling-generation check is advisory (mirrors -service's and -player's
|
||||
// own equivalents).
|
||||
//
|
||||
// A speaker self-reports its own group create/rename/teardown to whatever
|
||||
// Marge backend it's configured with -- that's the entire reason
|
||||
// HandleMargeAddGroup/HandleMargeModifyGroup/HandleMargeDeleteGroup exist,
|
||||
// they're only ever called by speakers, never by us. Proactively pushing the
|
||||
// same update ourselves would duplicate that against a backend we generally
|
||||
// can't authenticate to anyway (real Bose cloud, another AfterTouch/SoundCork
|
||||
// instance, ...). The one part with a distinct purpose -- checking for a
|
||||
// dangling stale generation before a new Create -- is still attempted, but
|
||||
// its failure must not block Create: it's a best-effort safety net on top of
|
||||
// the coordinator's own physical preflight, not the primary guard.
|
||||
func cliStereoPairGenerationPersistence(
|
||||
cleanupClient *http.Client,
|
||||
) (stereopair.GenerationCleanup, stereopair.GenerationPreflight, stereopair.GenerationRename) {
|
||||
cleanup := func(stereopair.GenerationRef) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
preflight := func(refs []stereopair.GenerationRef) error {
|
||||
if err := stereopair.EnsureMargeNoGroupGenerations(cleanupClient, refs); err != nil {
|
||||
PrintWarning(fmt.Sprintf("stereo-pair external generation preflight inconclusive, proceeding: %v", err))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
rename := func(stereopair.GenerationRef, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
return cleanup, preflight, rename
|
||||
}
|
||||
|
||||
// groupClientFactory addresses every member directly while retaining the
|
||||
// effective CLI port and timeout.
|
||||
func groupClientFactory(config *ClientConfig) stereopair.ClientFactory {
|
||||
baseConfig := *config
|
||||
|
||||
return func(ipAddress string) (stereopair.Client, error) {
|
||||
memberConfig := baseConfig
|
||||
memberConfig.Host = ipAddress
|
||||
|
||||
return CreateSoundTouchClient(&memberConfig)
|
||||
}
|
||||
}
|
||||
|
||||
func printGroupResultDetails(result stereopair.Result) {
|
||||
if result.Status == stereopair.StatusDegraded {
|
||||
PrintWarning(fmt.Sprintf("Stereo-pair %s result is degraded", result.Operation))
|
||||
}
|
||||
|
||||
for i := range result.Members {
|
||||
member := &result.Members[i]
|
||||
label := groupMemberLabel(i, member)
|
||||
|
||||
if member.PreflightError != nil {
|
||||
PrintError(fmt.Sprintf("%s preflight failed: %v", label, member.PreflightError))
|
||||
}
|
||||
|
||||
if member.MutationError != nil {
|
||||
PrintError(fmt.Sprintf("%s mutation failed: %v", label, member.MutationError))
|
||||
}
|
||||
|
||||
if member.VerificationError != nil {
|
||||
PrintError(fmt.Sprintf("%s verification failed: %v", label, member.VerificationError))
|
||||
}
|
||||
|
||||
if member.CompensationError != nil {
|
||||
PrintError(fmt.Sprintf("%s cleanup failed: %v", label, member.CompensationError))
|
||||
} else if member.CompensationAttempted && !member.CompensationVerified {
|
||||
PrintWarning(fmt.Sprintf("%s cleanup could not be verified", label))
|
||||
}
|
||||
}
|
||||
|
||||
if result.CompensationAttempted {
|
||||
if result.CompensationComplete {
|
||||
PrintWarning("Partial stereo-pair state was cleaned up and verified")
|
||||
} else {
|
||||
PrintError("Partial stereo-pair state cleanup is incomplete")
|
||||
}
|
||||
}
|
||||
|
||||
if result.PersistenceError != nil {
|
||||
PrintError(fmt.Sprintf("Persistent group generation update failed: %v", result.PersistenceError))
|
||||
}
|
||||
}
|
||||
|
||||
func groupMemberLabel(index int, member *stereopair.MemberResult) string {
|
||||
if member.IPAddress != "" && member.DeviceID != "" {
|
||||
return fmt.Sprintf("%s (%s)", member.IPAddress, member.DeviceID)
|
||||
}
|
||||
|
||||
if member.IPAddress != "" {
|
||||
return member.IPAddress
|
||||
}
|
||||
|
||||
if member.DeviceID != "" {
|
||||
return member.DeviceID
|
||||
}
|
||||
|
||||
return fmt.Sprintf("member %d", index+1)
|
||||
}
|
||||
|
||||
func printGroup(g *models.Group) {
|
||||
|
||||
@@ -1,184 +1,255 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/client"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/stereopair"
|
||||
)
|
||||
|
||||
// happyAddGroupServer fakes a speaker's /addGroup that echoes the request
|
||||
// with an assigned ID and GROUP_OK status, matching real hardware behaviour.
|
||||
func happyAddGroupServer(t *testing.T, assignedID string) (*httptest.Server, *[]string) {
|
||||
func TestGroupClientFactoryUsesMemberHostAndConfiguredPort(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/getGroup" {
|
||||
t.Errorf("path = %q, want /getGroup", r.URL.Path)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
_, _ = w.Write([]byte(`<group id="pair-id"><name>Pair</name></group>`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
host, port := testServerHostPort(t, srv.URL)
|
||||
factory := groupClientFactory(&ClientConfig{
|
||||
Host: "192.0.2.200",
|
||||
Port: port,
|
||||
Timeout: time.Second,
|
||||
})
|
||||
|
||||
memberClient, err := factory(host)
|
||||
if err != nil {
|
||||
t.Fatalf("factory: %v", err)
|
||||
}
|
||||
|
||||
group, err := memberClient.GetGroup()
|
||||
if err != nil {
|
||||
t.Fatalf("GetGroup: %v", err)
|
||||
}
|
||||
|
||||
if group.ID != "pair-id" || group.Name != "Pair" {
|
||||
t.Fatalf("group = %+v, want test server response", group)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupClientFactoryUsesConfiguredTimeout(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
_, _ = w.Write([]byte(`<group/>`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
host, port := testServerHostPort(t, srv.URL)
|
||||
factory := groupClientFactory(&ClientConfig{Port: port, Timeout: 5 * time.Millisecond})
|
||||
memberClient, err := factory(host)
|
||||
if err != nil {
|
||||
t.Fatalf("factory: %v", err)
|
||||
}
|
||||
|
||||
if _, err := memberClient.GetGroup(); err == nil {
|
||||
t.Fatal("GetGroup succeeded, want configured timeout")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMargeGroupGenerationURL(t *testing.T) {
|
||||
tests := []struct {
|
||||
base string
|
||||
want string
|
||||
}{
|
||||
{base: "http://aftertouch.example:8000", want: "http://aftertouch.example:8000/streaming/account/ACCOUNT1/group/PAIR1"},
|
||||
{base: "http://unifi:8001/marge", want: "http://unifi:8001/marge/streaming/account/ACCOUNT1/group/PAIR1"},
|
||||
{base: "https://proxy.example/prefix/streaming/", want: "https://proxy.example/prefix/streaming/account/ACCOUNT1/group/PAIR1"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
got, err := stereopair.MargeGroupGenerationURL(stereopair.GenerationRef{
|
||||
MargeURL: test.base, AccountID: "ACCOUNT1", GroupID: "PAIR1",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("margeGroupGenerationURL(%q): %v", test.base, err)
|
||||
}
|
||||
if got != test.want {
|
||||
t.Errorf("margeGroupGenerationURL(%q) = %q, want %q", test.base, got, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteMargeGroupGenerationUsesExactEndpoint(t *testing.T) {
|
||||
deleteSeen := false
|
||||
getSeen := false
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodDelete:
|
||||
deleteSeen = true
|
||||
if r.URL.Path != "/streaming/account/ACCOUNT1/group/PAIR1" {
|
||||
t.Errorf("DELETE path = %s", r.URL.Path)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case http.MethodGet:
|
||||
getSeen = true
|
||||
if r.URL.Path != "/streaming/account/ACCOUNT1/device/LEFT-ID/group" {
|
||||
t.Errorf("GET path = %s", r.URL.Path)
|
||||
}
|
||||
if deleteSeen {
|
||||
_, _ = w.Write([]byte(`<group/>`))
|
||||
} else {
|
||||
_, _ = w.Write([]byte(`<group id="PAIR1"><masterDeviceId>LEFT-ID</masterDeviceId><roles><groupRole><deviceId>LEFT-ID</deviceId><role>LEFT</role><ipAddress>192.0.2.10</ipAddress></groupRole><groupRole><deviceId>RIGHT-ID</deviceId><role>RIGHT</role><ipAddress>192.0.2.11</ipAddress></groupRole></roles></group>`))
|
||||
}
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
err := stereopair.DeleteMargeGroupGeneration(server.Client(), stereopair.GenerationRef{
|
||||
MargeURL: server.URL, AccountID: "ACCOUNT1", GroupID: "PAIR1", DeviceID: "LEFT-ID",
|
||||
ExpectedGroup: &models.Group{
|
||||
ID: "PAIR1",
|
||||
MasterDeviceID: "LEFT-ID",
|
||||
Roles: models.GroupRoles{Roles: []models.GroupRole{
|
||||
{DeviceID: "LEFT-ID", Role: "LEFT", IPAddress: "192.0.2.10"},
|
||||
{DeviceID: "RIGHT-ID", Role: "RIGHT", IPAddress: "192.0.2.11"},
|
||||
}},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("deleteMargeGroupGeneration: %v", err)
|
||||
}
|
||||
if !deleteSeen || !getSeen {
|
||||
t.Fatalf("Marge cleanup requests DELETE=%t GET=%t, want both", deleteSeen, getSeen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrintGroupResultDetailsReportsMemberFailuresAndCleanup(t *testing.T) {
|
||||
result := stereopair.Result{
|
||||
Operation: stereopair.OperationCreate,
|
||||
Status: stereopair.StatusDegraded,
|
||||
CompensationAttempted: true,
|
||||
PersistenceError: errors.New("datastore unavailable"),
|
||||
Members: []stereopair.MemberResult{
|
||||
{
|
||||
IPAddress: "192.0.2.10",
|
||||
DeviceID: "LEFT-ID",
|
||||
PreflightError: errors.New("offline"),
|
||||
},
|
||||
{
|
||||
IPAddress: "192.0.2.11",
|
||||
MutationError: errors.New("add failed"),
|
||||
VerificationError: errors.New("unexpected group"),
|
||||
CompensationAttempted: true,
|
||||
CompensationError: errors.New("remove failed"),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
output := captureStdout(t, func() {
|
||||
printGroupResultDetails(result)
|
||||
})
|
||||
|
||||
for _, expected := range []string{
|
||||
"Stereo-pair create result is degraded",
|
||||
"192.0.2.10 (LEFT-ID) preflight failed: offline",
|
||||
"192.0.2.11 mutation failed: add failed",
|
||||
"192.0.2.11 verification failed: unexpected group",
|
||||
"192.0.2.11 cleanup failed: remove failed",
|
||||
"Partial stereo-pair state cleanup is incomplete",
|
||||
"Persistent group generation update failed: datastore unavailable",
|
||||
} {
|
||||
if !strings.Contains(output, expected) {
|
||||
t.Errorf("output missing %q:\n%s", expected, output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDissolveRecoveryHostSelectsStillGroupedMember(t *testing.T) {
|
||||
result := stereopair.Result{
|
||||
Group: &models.Group{ID: "PAIR-ID"},
|
||||
Members: []stereopair.MemberResult{
|
||||
{IPAddress: "192.0.2.10", Group: &models.Group{}},
|
||||
{IPAddress: "192.0.2.11", Group: &models.Group{ID: "PAIR-ID"}},
|
||||
},
|
||||
}
|
||||
|
||||
if got := dissolveRecoveryHost(result, "192.0.2.10"); got != "192.0.2.11" {
|
||||
t.Fatalf("recovery host = %q, want surviving member", got)
|
||||
}
|
||||
}
|
||||
|
||||
func testServerHostPort(t *testing.T, serverURL string) (string, int) {
|
||||
t.Helper()
|
||||
|
||||
bodies := make([]string, 0)
|
||||
parsed, err := url.Parse(serverURL)
|
||||
if err != nil {
|
||||
t.Fatalf("parse server URL: %v", err)
|
||||
}
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/addGroup" || r.Method != http.MethodPost {
|
||||
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
|
||||
http.NotFound(w, r)
|
||||
host, portText, err := net.SplitHostPort(parsed.Host)
|
||||
if err != nil {
|
||||
t.Fatalf("split server host: %v", err)
|
||||
}
|
||||
|
||||
port, err := strconv.Atoi(portText)
|
||||
if err != nil {
|
||||
t.Fatalf("parse server port: %v", err)
|
||||
}
|
||||
|
||||
return host, port
|
||||
}
|
||||
|
||||
// TestCLIStereoPairGenerationPersistenceSkipsWritesButAttemptsRead covers
|
||||
// the CLI's generation-lifecycle wiring: cleanup and rename must never push
|
||||
// to a Marge backend -- the speaker itself self-reports its own group
|
||||
// teardown/rename to whatever backend it's configured with (see
|
||||
// HandleMargeDeleteGroup/HandleMargeModifyGroup, only ever called by
|
||||
// speakers). Preflight still attempts its read-only dangling-generation
|
||||
// check, but a failure there (network error, wrong credentials, real Bose
|
||||
// cloud rejecting us, ...) must not block Create.
|
||||
func TestCLIStereoPairGenerationPersistenceSkipsWritesButAttemptsRead(t *testing.T) {
|
||||
getCalls := 0
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/device/LEFT-ID/group") {
|
||||
getCalls++
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
bodies = append(bodies, string(body))
|
||||
|
||||
var got models.Group
|
||||
if err := xml.Unmarshal(body, &got); err != nil {
|
||||
t.Fatalf("decode request body: %v", err)
|
||||
}
|
||||
|
||||
got.ID = assignedID
|
||||
got.Status = "GROUP_OK"
|
||||
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
|
||||
enc, _ := xml.Marshal(&got)
|
||||
_, _ = w.Write(enc)
|
||||
t.Fatalf("unexpected external %s %s: cleanup/rename must not write to a backend the CLI doesn't own", r.Method, r.URL.Path)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
return srv, &bodies
|
||||
}
|
||||
cleanup, preflight, rename := cliStereoPairGenerationPersistence(server.Client())
|
||||
|
||||
func newTestGroupClient(serverURL string) *client.Client {
|
||||
return client.NewClientFromHost(serverURL)
|
||||
}
|
||||
ref := stereopair.GenerationRef{
|
||||
DeviceID: "LEFT-ID", AccountID: "ACCOUNT1", MargeURL: server.URL + "/marge",
|
||||
GroupID: "7654321",
|
||||
}
|
||||
|
||||
func sampleGroupRequest(leftIP, rightIP string) *models.Group {
|
||||
return &models.Group{
|
||||
Name: "Living Room",
|
||||
MasterDeviceID: "9070658C9D4A",
|
||||
Roles: models.GroupRoles{
|
||||
Roles: []models.GroupRole{
|
||||
{DeviceID: "9070658C9D4A", Role: "LEFT", IPAddress: leftIP},
|
||||
{DeviceID: "F45EAB3115DA", Role: "RIGHT", IPAddress: rightIP},
|
||||
},
|
||||
},
|
||||
// senderIPAddress is intentionally not set here; propagateAddGroup
|
||||
// adds it to the slave's copy only.
|
||||
if err := rename(ref, "Renamed living room"); err != nil {
|
||||
t.Fatalf("rename = %v, want nil (speaker self-reports its own rename)", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPropagateAddGroup_BothSucceed(t *testing.T) {
|
||||
leftSrv, leftBodies := happyAddGroupServer(t, "9999999")
|
||||
defer leftSrv.Close()
|
||||
|
||||
rightSrv, rightBodies := happyAddGroupServer(t, "9999999")
|
||||
defer rightSrv.Close()
|
||||
|
||||
leftClient := newTestGroupClient(leftSrv.URL)
|
||||
rightClient := newTestGroupClient(rightSrv.URL)
|
||||
|
||||
req := sampleGroupRequest("192.0.2.131", "192.0.2.134")
|
||||
|
||||
leftOut, rightOut := propagateAddGroup(leftClient, rightClient, "192.0.2.131", "192.0.2.134", req)
|
||||
|
||||
if leftOut.err != nil {
|
||||
t.Errorf("LEFT err = %v, want nil", leftOut.err)
|
||||
if err := cleanup(ref); err != nil {
|
||||
t.Fatalf("cleanup = %v, want nil (speaker self-reports its own teardown)", err)
|
||||
}
|
||||
|
||||
if rightOut.err != nil {
|
||||
t.Errorf("RIGHT err = %v, want nil", rightOut.err)
|
||||
if err := preflight([]stereopair.GenerationRef{ref}); err != nil {
|
||||
t.Fatalf("preflight = %v, want nil: an unauthenticated external check must not block Create", err)
|
||||
}
|
||||
|
||||
if leftOut.group == nil || leftOut.group.ID != "9999999" || leftOut.group.Status != "GROUP_OK" {
|
||||
t.Errorf("LEFT group = %+v, want id=9999999 status=GROUP_OK", leftOut.group)
|
||||
}
|
||||
|
||||
if rightOut.group == nil || rightOut.group.Status != "GROUP_OK" {
|
||||
t.Errorf("RIGHT group = %+v, want status=GROUP_OK", rightOut.group)
|
||||
}
|
||||
|
||||
// Both speakers must have received the roles, but only the slave's payload
|
||||
// carries senderIPAddress — see propagateAddGroup for the why.
|
||||
for label, bodies := range map[string]*[]string{"LEFT": leftBodies, "RIGHT": rightBodies} {
|
||||
if len(*bodies) != 1 {
|
||||
t.Fatalf("%s: expected exactly one POST, got %d", label, len(*bodies))
|
||||
}
|
||||
|
||||
body := (*bodies)[0]
|
||||
for _, want := range []string{"<role>LEFT</role>", "<role>RIGHT</role>"} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("%s body missing %q\nbody:\n%s", label, want, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
leftBody := (*leftBodies)[0]
|
||||
if strings.Contains(leftBody, "<senderIPAddress>") {
|
||||
t.Errorf("LEFT (master) body must NOT carry <senderIPAddress>, otherwise the master flips into slave mode (issue #252)\nbody:\n%s", leftBody)
|
||||
}
|
||||
|
||||
rightBody := (*rightBodies)[0]
|
||||
if !strings.Contains(rightBody, "<senderIPAddress>192.0.2.131</senderIPAddress>") {
|
||||
t.Errorf("RIGHT (slave) body must carry <senderIPAddress>192.0.2.131</senderIPAddress>\nbody:\n%s", rightBody)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPropagateAddGroup_RightFails(t *testing.T) {
|
||||
leftSrv, _ := happyAddGroupServer(t, "9999999")
|
||||
defer leftSrv.Close()
|
||||
|
||||
rightSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
http.Error(w, "boom", http.StatusInternalServerError)
|
||||
}))
|
||||
defer rightSrv.Close()
|
||||
|
||||
leftClient := newTestGroupClient(leftSrv.URL)
|
||||
rightClient := newTestGroupClient(rightSrv.URL)
|
||||
|
||||
req := sampleGroupRequest("192.0.2.131", "192.0.2.134")
|
||||
|
||||
leftOut, rightOut := propagateAddGroup(leftClient, rightClient, "192.0.2.131", "192.0.2.134", req)
|
||||
|
||||
if leftOut.err != nil {
|
||||
t.Errorf("LEFT err = %v, want nil", leftOut.err)
|
||||
}
|
||||
|
||||
if rightOut.err == nil {
|
||||
t.Error("RIGHT err = nil, want non-nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostAddGroup_StatusOtherThanGroupOKIsError(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
_, _ = w.Write([]byte(`<group><status>GROUP_NOT_READY</status></group>`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
out := postAddGroup(newTestGroupClient(srv.URL), "test", sampleGroupRequest("1.1.1.1", "2.2.2.2"))
|
||||
|
||||
if out.err == nil {
|
||||
t.Fatal("expected error for non-GROUP_OK status")
|
||||
}
|
||||
|
||||
if !strings.Contains(out.err.Error(), "GROUP_NOT_READY") {
|
||||
t.Errorf("error %q does not mention returned status", out.err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostAddGroup_EmptyStatusIsAccepted(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
_, _ = w.Write([]byte(`<group id="42"><name>n</name></group>`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
out := postAddGroup(newTestGroupClient(srv.URL), "test", sampleGroupRequest("1.1.1.1", "2.2.2.2"))
|
||||
|
||||
if out.err != nil {
|
||||
t.Errorf("err = %v, want nil for empty status (some firmware omits it)", out.err)
|
||||
}
|
||||
|
||||
if out.group == nil || out.group.ID != "42" {
|
||||
t.Errorf("group = %+v, want id=42", out.group)
|
||||
if getCalls != 1 {
|
||||
t.Fatalf("external GET calls = %d, want exactly 1 (preflight must still attempt the read)", getCalls)
|
||||
}
|
||||
}
|
||||
|
||||
+313
-14
@@ -15,6 +15,7 @@ import (
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/constants"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/setup"
|
||||
"github.com/urfave/cli/v2"
|
||||
"golang.org/x/term"
|
||||
@@ -52,10 +53,12 @@ func setupCommand() *cli.Command {
|
||||
setupRemoteServicesCmd(),
|
||||
setupInstallCACmd(),
|
||||
setupMigrateCmd(),
|
||||
setupRevertCmd(),
|
||||
setupRebootCmd(),
|
||||
setupVerifyCmd(),
|
||||
setupPlanCmd(),
|
||||
setupPairCmd(),
|
||||
setupSyncCmd(),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -517,8 +520,13 @@ func setupSSHCheckCmd() *cli.Command {
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("port 22 not reachable: %v", err))
|
||||
fmt.Println()
|
||||
fmt.Println("Modern SoundTouch firmware (27.x) does not let us enable SSH from")
|
||||
fmt.Println("telnet — those commands were removed. To enable SSH on the speaker:")
|
||||
fmt.Println("Try enabling it over telnet first — this works on many (not all) FW 27.x")
|
||||
fmt.Println("speakers via the port-17000 envswitch trick (#471):")
|
||||
fmt.Println(" soundtouch-cli setup enable-ssh")
|
||||
fmt.Println("For stubborn devices (ST Portable, CineMate 520) where the default")
|
||||
fmt.Println("injection is accepted but sshd never starts, add --full-config.")
|
||||
fmt.Println()
|
||||
fmt.Println("If enable-ssh doesn't work on this device, fall back to the USB-stick method:")
|
||||
fmt.Println(" 1. Format a FAT32 USB stick.")
|
||||
fmt.Println(" 2. Create an empty file named `remote_services` at its root.")
|
||||
fmt.Println(" 3. Plug the stick into the speaker (rear USB port) while it is on.")
|
||||
@@ -541,17 +549,23 @@ func setupSSHCheckCmd() *cli.Command {
|
||||
// runEnableSSHInjection runs the port-17000 SSH-enable injection over telnet,
|
||||
// printing the device transcript as it goes. With fullConfig it sends the
|
||||
// #515 sequence (all four config URLs with the injection on margeServerUrl, not
|
||||
// just envswitch) and reboots afterwards; otherwise it sends the single-
|
||||
// envswitch default that fires on the speaker's next boseurls check.
|
||||
func runEnableSSHInjection(m *setup.Manager, host, serviceURL string, fullConfig bool) error {
|
||||
// just envswitch), pausing commandDelay between each of the 6 steps (5
|
||||
// commands + reboot) — see setup.DefaultTelnetCommandDelay for why the pause
|
||||
// exists — then reboots; otherwise it sends the single-envswitch default that
|
||||
// fires on the speaker's next boseurls check (no pause needed, it's one
|
||||
// command).
|
||||
func runEnableSSHInjection(m *setup.Manager, host, serviceURL string, fullConfig bool, commandDelay time.Duration) error {
|
||||
var (
|
||||
logs string
|
||||
err error
|
||||
)
|
||||
|
||||
if fullConfig {
|
||||
fmt.Printf("Enabling SSH on %s via telnet :17000 (full #515 sequence: all four config URLs with the injection on margeServerUrl, then reboot)...\n", host)
|
||||
logs, err = m.EnableSSHViaTelnetFullConfig(host, serviceURL)
|
||||
// 6 steps total (5 commands + reboot), so 6 gaps between/around them.
|
||||
fmt.Printf("Enabling SSH on %s via telnet :17000 (full #515 sequence: all four config URLs with "+
|
||||
"the injection on margeServerUrl, %s between each of 6 steps — about %s before the reboot fires "+
|
||||
"— then reboot)...\n", host, commandDelay, 6*commandDelay)
|
||||
logs, err = m.EnableSSHViaTelnetFullConfig(host, serviceURL, commandDelay)
|
||||
} else {
|
||||
fmt.Printf("Enabling SSH on %s via telnet :17000 (runs on the speaker's next boseurls check, up to ~60s)...\n", host)
|
||||
logs, err = m.EnableSSHViaTelnet(host, serviceURL)
|
||||
@@ -570,6 +584,10 @@ func runEnableSSHInjection(m *setup.Manager, host, serviceURL string, fullConfig
|
||||
return nil
|
||||
}
|
||||
|
||||
if commandDelay > 0 {
|
||||
time.Sleep(commandDelay)
|
||||
}
|
||||
|
||||
fmt.Println("Rebooting the speaker to apply the new configuration...")
|
||||
|
||||
rlogs, rerr := m.Reboot(host, setup.RebootMethodTelnet)
|
||||
@@ -585,6 +603,41 @@ func runEnableSSHInjection(m *setup.Manager, host, serviceURL string, fullConfig
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureMargeAccountPaired checks /info and pairs an unpaired device before
|
||||
// the SSH-enable injection runs — see setup.EnsureMargeAccountPaired for why.
|
||||
// Pairing failure is logged as a warning, not fatal: the claim that an
|
||||
// unpaired device never polls margeServerUrl is not yet confirmed on every
|
||||
// device this command targets, so the injection is still worth attempting
|
||||
// even if the pairing step itself couldn't be verified.
|
||||
func ensureMargeAccountPaired(m *setup.Manager, deviceIP, wantAccountID string) {
|
||||
var t setup.TelnetClient
|
||||
|
||||
if m.NewTelnet != nil {
|
||||
t = m.NewTelnet(deviceIP)
|
||||
|
||||
if dialErr := t.Dial(); dialErr != nil {
|
||||
t = nil
|
||||
} else {
|
||||
defer func() { _ = t.Close() }()
|
||||
}
|
||||
}
|
||||
|
||||
accountID, alreadyPaired, logs, err := m.EnsureMargeAccountPaired(deviceIP, wantAccountID, t)
|
||||
if logs != "" {
|
||||
fmt.Print(logs)
|
||||
}
|
||||
|
||||
switch {
|
||||
case err != nil:
|
||||
PrintWarning(fmt.Sprintf("Pairing check failed (%v) — continuing anyway; the SSH-enable injection may not "+
|
||||
"fire on an unpaired device (#515).", err))
|
||||
case alreadyPaired:
|
||||
fmt.Printf("Device already paired (margeAccountUUID=%s).\n", accountID)
|
||||
default:
|
||||
fmt.Printf("Device was unpaired — paired it with generated account %s so margeServerUrl gets polled (#515).\n", accountID)
|
||||
}
|
||||
}
|
||||
|
||||
func setupEnableSSHCmd() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "enable-ssh",
|
||||
@@ -608,6 +661,24 @@ func setupEnableSSHCmd() *cli.Command {
|
||||
Usage: "For stubborn devices (ST Portable, CineMate 520) where the default single-envswitch injection is accepted but sshd never starts: " +
|
||||
"replicate the #515 manual sequence — write all four sys configuration URL keys with the SSH-enable injection on margeServerUrl (not just envswitch), then reboot",
|
||||
},
|
||||
&cli.DurationFlag{
|
||||
Name: "command-delay",
|
||||
Value: setup.DefaultTelnetCommandDelay,
|
||||
Usage: "Only affects --full-config: pause between each of its 6 steps (5 commands + reboot). " +
|
||||
"Raise this if the default doesn't work on your device; 0 sends everything back-to-back",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "no-auto-pair",
|
||||
Usage: "Skip the automatic pairing check: by default, enable-ssh reads /info first and pairs an unpaired " +
|
||||
"(factory-reset) device with an account ID, since an unpaired device reportedly never " +
|
||||
"polls margeServerUrl at all (#515) — the injection would have nothing to fire on otherwise",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "account",
|
||||
Usage: "Only used when the device is unpaired and --no-auto-pair is not set: account ID to pair with " +
|
||||
"(empty = generate a fresh 7-digit one). Use this if you already know which account this device " +
|
||||
"should end up on (e.g. to match one already in the datastore) rather than getting a random one now",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "no-reset-urls",
|
||||
Usage: "Skip restoring clean boseurls after SSH is up (leaves the injected marge URL in place)",
|
||||
@@ -641,7 +712,11 @@ func setupEnableSSHCmd() *cli.Command {
|
||||
serviceURL = "https://aftertouch.invalid"
|
||||
}
|
||||
|
||||
if err := runEnableSSHInjection(m, cfg.Host, serviceURL, c.Bool("full-config")); err != nil {
|
||||
if !c.Bool("no-auto-pair") {
|
||||
ensureMargeAccountPaired(m, cfg.Host, c.String("account"))
|
||||
}
|
||||
|
||||
if err := runEnableSSHInjection(m, cfg.Host, serviceURL, c.Bool("full-config"), c.Duration("command-delay")); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -941,6 +1016,116 @@ func promptBasicAuth() (string, string, error) {
|
||||
return user, string(pass), nil
|
||||
}
|
||||
|
||||
// setupSyncCmd wraps POST /api/setup/sync/{deviceId} — the same operation
|
||||
// as the web UI's Devices → Sync Data button. It only reads from the
|
||||
// speaker (presets, recents, sources) into AfterTouch's datastore; it never
|
||||
// writes anything back to the speaker. Useful for scripting or reproducing
|
||||
// what Sync does in isolation (see issue #614: Sync's own code cannot wipe
|
||||
// the speaker's preset table, since it never sends anything back).
|
||||
func setupSyncCmd() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "sync",
|
||||
Usage: "Pull presets/recents/sources from the speaker into AfterTouch's datastore (same as the web UI's \"Sync Data\" button)",
|
||||
Before: RequireHost,
|
||||
Flags: []cli.Flag{
|
||||
&cli.StringFlag{Name: "service-url", Required: true, Usage: "AfterTouch base URL"},
|
||||
&cli.StringFlag{Name: "auth", Usage: "Basic-auth credentials for AfterTouch as user:pass (omit to be prompted on 401)"},
|
||||
},
|
||||
Action: func(c *cli.Context) error {
|
||||
cfg := GetClientConfig(c)
|
||||
serviceURL := strings.TrimRight(c.String("service-url"), "/")
|
||||
|
||||
if err := validateServiceURL(serviceURL); err != nil {
|
||||
PrintError(err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
client, err := CreateSoundTouchClient(cfg)
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("Failed to create client: %v", err))
|
||||
return err
|
||||
}
|
||||
|
||||
deviceInfo, err := client.GetDeviceInfo()
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("Failed to get device info from speaker: %v", err))
|
||||
return err
|
||||
}
|
||||
|
||||
if deviceInfo.DeviceID == "" {
|
||||
err := fmt.Errorf("speaker at %s did not report a DeviceID", cfg.Host)
|
||||
PrintError(err.Error())
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
PrintDeviceHeader(fmt.Sprintf("Syncing %s into AfterTouch", deviceInfo.DeviceID), cfg.Host, cfg.Port)
|
||||
|
||||
if err := postSetupSync(serviceURL, deviceInfo.DeviceID, c.String("auth")); err != nil {
|
||||
PrintError(err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
PrintSuccess(fmt.Sprintf("Synced presets, recents, and sources for %s.", deviceInfo.DeviceID))
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// postSetupSync POSTs to AfterTouch's /api/setup/sync/{deviceId}, prompting
|
||||
// for basic-auth credentials on 401 (matches fetchCACert's pattern).
|
||||
func postSetupSync(serviceURL, deviceID, authFlag string) error {
|
||||
endpoint := fmt.Sprintf("%s/api/setup/sync/%s", serviceURL, deviceID)
|
||||
|
||||
doRequest := func(user, pass string) (*http.Response, error) {
|
||||
req, err := http.NewRequest(http.MethodPost, endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if user != "" {
|
||||
req.SetBasicAuth(user, pass)
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
|
||||
return client.Do(req)
|
||||
}
|
||||
|
||||
user, pass := splitAuth(authFlag)
|
||||
|
||||
resp, err := doRequest(user, pass)
|
||||
if err != nil {
|
||||
return fmt.Errorf("POST %s: %w", endpoint, err)
|
||||
}
|
||||
|
||||
if resp.StatusCode == http.StatusUnauthorized {
|
||||
_ = resp.Body.Close()
|
||||
|
||||
fmt.Printf("%s requires basic auth.\n", endpoint)
|
||||
|
||||
user, pass, err = promptBasicAuth()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err = doRequest(user, pass)
|
||||
if err != nil {
|
||||
return fmt.Errorf("POST %s (with auth): %w", endpoint, err)
|
||||
}
|
||||
}
|
||||
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("POST %s returned %d: %s", endpoint, resp.StatusCode, strings.TrimSpace(string(body)))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func setupMigrateCmd() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "migrate",
|
||||
@@ -951,6 +1136,10 @@ func setupMigrateCmd() *cli.Command {
|
||||
&cli.StringFlag{Name: "method", Value: string(setup.MigrationMethodTelnet), Usage: "telnet | hosts | resolv | xml"},
|
||||
&cli.StringFlag{Name: "proxy-url", Usage: "Optional upstream proxy URL (for --method=xml)"},
|
||||
&cli.BoolFlag{Name: "skip-preflight", Usage: "Skip the AfterTouch settings preflight (use when AfterTouch's settings endpoint is unreachable)"},
|
||||
&cli.StringFlag{Name: "marge-url", Usage: "Override margeServerUrl instead of deriving it from --service-url (e.g. to restore the original Bose cloud URL). Applies to --method=telnet and --method=xml"},
|
||||
&cli.StringFlag{Name: "stats-url", Usage: "Override statsServerUrl (telnet/xml)"},
|
||||
&cli.StringFlag{Name: "sw-update-url", Usage: "Override swUpdateUrl (telnet/xml)"},
|
||||
&cli.StringFlag{Name: "bmx-url", Usage: "Override bmxRegistryUrl (telnet/xml)"},
|
||||
},
|
||||
Action: func(c *cli.Context) error {
|
||||
cfg := GetClientConfig(c)
|
||||
@@ -962,6 +1151,13 @@ func setupMigrateCmd() *cli.Command {
|
||||
return err
|
||||
}
|
||||
|
||||
options := map[string]string{
|
||||
"marge_url": c.String("marge-url"),
|
||||
"stats_url": c.String("stats-url"),
|
||||
"sw_update_url": c.String("sw-update-url"),
|
||||
"bmx_url": c.String("bmx-url"),
|
||||
}
|
||||
|
||||
m := setup.NewManager(serviceURL, nil, nil)
|
||||
|
||||
// For DNS-redirect methods check that AfterTouch's DNS listener
|
||||
@@ -985,7 +1181,7 @@ func setupMigrateCmd() *cli.Command {
|
||||
|
||||
fmt.Printf("Migrating %s → %s using method=%s\n", cfg.Host, serviceURL, method)
|
||||
|
||||
logs, err := m.MigrateSpeaker(cfg.Host, serviceURL, c.String("proxy-url"), nil, method)
|
||||
logs, err := m.MigrateSpeaker(cfg.Host, serviceURL, c.String("proxy-url"), options, method)
|
||||
if logs != "" {
|
||||
fmt.Print(logs)
|
||||
}
|
||||
@@ -1314,6 +1510,98 @@ func renderMigrationSummary(deviceIP, serviceURL string, s *setup.MigrationSumma
|
||||
}
|
||||
}
|
||||
|
||||
var telnetRevertOverrideFlags = []string{"marge-url", "stats-url", "sw-update-url", "bmx-url"}
|
||||
|
||||
func validateRevertMethodOptions(method string, overrideFlags []string) error {
|
||||
if method != "ssh" && method != string(setup.MigrationMethodTelnet) {
|
||||
return fmt.Errorf("unsupported revert method %q; expected ssh or telnet", method)
|
||||
}
|
||||
|
||||
if method != string(setup.MigrationMethodTelnet) && len(overrideFlags) > 0 {
|
||||
return fmt.Errorf("--%s requires --method telnet", strings.Join(overrideFlags, ", --"))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// setupRevertCmd restores either the SSH/filesystem migration state or only
|
||||
// the four URL fields written by a telnet migration. The default remains the
|
||||
// existing SSH path for backwards compatibility.
|
||||
//
|
||||
// Deliberately out of scope (matches the web UI button): SSH/remote_services
|
||||
// persistence (use `setup remote-services --remove`) and account pairing
|
||||
// (use `account unpair`) — see #614 self-test notes for the full checklist.
|
||||
func setupRevertCmd() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "revert",
|
||||
Usage: "Undo a migration via SSH backups or restore canonical Bose service URLs over telnet",
|
||||
Before: RequireHost,
|
||||
Flags: []cli.Flag{
|
||||
&cli.StringFlag{Name: "method", Value: "ssh", Usage: "ssh | telnet"},
|
||||
&cli.StringFlag{Name: "marge-url", Usage: "Override the canonical Bose margeServerUrl (telnet only)"},
|
||||
&cli.StringFlag{Name: "stats-url", Usage: "Override the canonical Bose statsServerUrl (telnet only)"},
|
||||
&cli.StringFlag{Name: "sw-update-url", Usage: "Override the canonical Bose swUpdateUrl (telnet only)"},
|
||||
&cli.StringFlag{Name: "bmx-url", Usage: "Override the canonical Bose bmxRegistryUrl (telnet only)"},
|
||||
},
|
||||
Action: func(c *cli.Context) error {
|
||||
cfg := GetClientConfig(c)
|
||||
method := c.String("method")
|
||||
|
||||
var overrideFlags []string
|
||||
|
||||
for _, flag := range telnetRevertOverrideFlags {
|
||||
if c.IsSet(flag) {
|
||||
overrideFlags = append(overrideFlags, flag)
|
||||
}
|
||||
}
|
||||
|
||||
if err := validateRevertMethodOptions(method, overrideFlags); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
m := setup.NewManager("", nil, nil)
|
||||
|
||||
fmt.Printf("Reverting migration on %s using method=%s...\n", cfg.Host, method)
|
||||
|
||||
var (
|
||||
logs string
|
||||
err error
|
||||
)
|
||||
|
||||
switch method {
|
||||
case "ssh":
|
||||
logs, err = m.RevertMigration(cfg.Host)
|
||||
case string(setup.MigrationMethodTelnet):
|
||||
options := map[string]string{
|
||||
"marge_url": c.String("marge-url"),
|
||||
"stats_url": c.String("stats-url"),
|
||||
"sw_update_url": c.String("sw-update-url"),
|
||||
"bmx_url": c.String("bmx-url"),
|
||||
}
|
||||
logs, err = m.RevertTelnetURLs(cfg.Host, options)
|
||||
}
|
||||
|
||||
if logs != "" {
|
||||
fmt.Print(logs)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
PrintError(err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
if method == string(setup.MigrationMethodTelnet) {
|
||||
PrintSuccess("Canonical Bose URL configuration restored. Reboot the speaker to verify the persisted layer; filesystem, DNS, CA, SSH, and account state were not changed.")
|
||||
} else {
|
||||
PrintSuccess("Migration reverted. SSH access and account pairing are untouched by this — " +
|
||||
"see `setup remote-services --remove` and `account unpair` if you want those cleared too.")
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func setupRebootCmd() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "reboot",
|
||||
@@ -1740,11 +2028,11 @@ func setupPairCmd() *cli.Command {
|
||||
Usage: "Pair the speaker with an account via WebSocket SETUP state machine",
|
||||
Before: RequireHost,
|
||||
Flags: []cli.Flag{
|
||||
&cli.StringFlag{Name: "account", Usage: "7-digit account ID (empty = generate)"},
|
||||
&cli.StringFlag{Name: "account", Usage: "Account ID to pair with (empty = generate a fresh 7-digit one)"},
|
||||
&cli.StringFlag{Name: "mode", Value: "full", Usage: "full (state machine) or bare (setMargeAccount only — experimental)"},
|
||||
&cli.StringFlag{Name: "service-url", Value: "http://aftertouch.local:8000", Usage: "AfterTouch base URL (also populates <boseServer>/<updateServer> in setMargeAccount)"},
|
||||
&cli.StringFlag{Name: "name", Usage: "Speaker name to set during pairing (empty = keep current)"},
|
||||
&cli.IntFlag{Name: "language", Value: setup.LanguageEnglish, Usage: "sysLanguage code (2 = English)"},
|
||||
&cli.IntFlag{Name: "language", Value: setup.LanguageEnglish, Usage: "sysLanguage code (3 = English)"},
|
||||
&cli.DurationFlag{Name: "step-timeout", Value: 8 * time.Second},
|
||||
&cli.StringFlag{Name: "token", Usage: "userAuthToken value (empty = use built-in placeholder matching the Bose app token shape)"},
|
||||
},
|
||||
@@ -1764,8 +2052,8 @@ func setupPairCmd() *cli.Command {
|
||||
fmt.Printf("Generated account id: %s\n", accountID)
|
||||
}
|
||||
|
||||
if !setup.IsValidAccountID(accountID) {
|
||||
return fmt.Errorf("invalid account id %q: must be 7 digits", accountID)
|
||||
if !datastore.IsSafeIdentifier(accountID) {
|
||||
return fmt.Errorf("invalid account id %q: must be a non-empty, path-safe identifier", accountID)
|
||||
}
|
||||
|
||||
switch mode {
|
||||
@@ -1847,6 +2135,17 @@ func runPairBare(c *cli.Context, deviceIP, accountID string) error {
|
||||
func runPairFull(c *cli.Context, deviceIP, accountID string) error {
|
||||
m := setup.NewManager(c.String("service-url"), nil, nil)
|
||||
|
||||
needed, status, err := m.PreflightInitPlan(deviceIP)
|
||||
if err != nil {
|
||||
PrintError(fmt.Sprintf("preflight: %v", err))
|
||||
return err
|
||||
}
|
||||
|
||||
if !needed {
|
||||
PrintSuccess(fmt.Sprintf("Device already configured (status=%s) — nothing to do.", status))
|
||||
return nil
|
||||
}
|
||||
|
||||
plan := setup.InitPlan{
|
||||
DeviceIP: deviceIP,
|
||||
ServiceURL: c.String("service-url"),
|
||||
@@ -1860,7 +2159,7 @@ func runPairFull(c *cli.Context, deviceIP, accountID string) error {
|
||||
ctx, cancel := context.WithTimeout(c.Context, 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := m.ExecuteInitPlan(ctx, plan, func(e setup.StepEvent) {
|
||||
_, err = m.ExecuteInitPlan(ctx, plan, func(e setup.StepEvent) {
|
||||
switch e.Status {
|
||||
case setup.StatusOK:
|
||||
fmt.Printf("[%d] %s — ok\n", e.Kind, e.Name)
|
||||
|
||||
@@ -3,6 +3,8 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -43,6 +45,46 @@ func captureStdout(t *testing.T, fn func()) string {
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func TestPostSetupSync_PostsToDeviceScopedURL(t *testing.T) {
|
||||
var gotMethod, gotPath string
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotMethod = r.Method
|
||||
gotPath = r.URL.Path
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"ok": true}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
if err := postSetupSync(srv.URL, "DEVICEID01", ""); err != nil {
|
||||
t.Fatalf("postSetupSync: %v", err)
|
||||
}
|
||||
|
||||
if gotMethod != http.MethodPost {
|
||||
t.Errorf("expected POST, got %s", gotMethod)
|
||||
}
|
||||
|
||||
if want := "/api/setup/sync/DEVICEID01"; gotPath != want {
|
||||
t.Errorf("expected path %q, got %q", want, gotPath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostSetupSync_PropagatesServerError(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
http.Error(w, "device not found", http.StatusNotFound)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
err := postSetupSync(srv.URL, "DEVICEID01", "")
|
||||
if err == nil {
|
||||
t.Fatal("expected an error for a 404 response")
|
||||
}
|
||||
|
||||
if !strings.Contains(err.Error(), "device not found") {
|
||||
t.Errorf("expected error to include server body, got %q", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderSourceTable_AlignsColumnsAndDedupsDisplayName(t *testing.T) {
|
||||
items := []models.SourceItem{
|
||||
// displayName != account → kept as "AUX (AUX IN)"
|
||||
@@ -165,6 +207,38 @@ func TestRecommendMigrationMethod_EmptyWhenNoTransport(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRevertMethodOptions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
overrides []string
|
||||
wantError string
|
||||
}{
|
||||
{name: "ssh defaults", method: "ssh"},
|
||||
{name: "telnet defaults", method: "telnet"},
|
||||
{name: "telnet overrides", method: "telnet", overrides: []string{"marge-url"}},
|
||||
{name: "ssh rejects overrides", method: "ssh", overrides: []string{"marge-url"}, wantError: "requires --method telnet"},
|
||||
{name: "unknown method", method: "serial", wantError: "unsupported revert method"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validateRevertMethodOptions(tt.method, tt.overrides)
|
||||
if tt.wantError == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("validateRevertMethodOptions: %v", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantError) {
|
||||
t.Fatalf("error = %v, want text %q", err, tt.wantError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildPlanSteps_NoOpWhenAlreadyMigratedAndPaired(t *testing.T) {
|
||||
summary := &setup.MigrationSummary{IsMigrated: true, IsPaired: true, TelnetMigrated: true}
|
||||
inspect := &setup.InspectReport{Info: &setup.DeviceInfoXML{DeviceID: "AABBCCDDEEFF"}}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/updatecheck"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
// updateCheckRepo is the GitHub repo checked for newer releases, matching
|
||||
// soundtouch-service's periodic background check (#591,
|
||||
// _/i591/design-update-check.md).
|
||||
const updateCheckRepo = "gesellix/Bose-SoundTouch"
|
||||
|
||||
// updateCheckCommand assembles the on-demand `soundtouch-cli update-check`
|
||||
// command, the CLI-side answer to that design doc's open question 2
|
||||
// (CLI-only users get no update notice from the service's background
|
||||
// checker). Unlike the service's opt-in periodic check, running this
|
||||
// command *is* the opt-in: no config flag, no persisted state, just one
|
||||
// GitHub API request each time it's invoked.
|
||||
func updateCheckCommand() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "update-check",
|
||||
Usage: "Check GitHub for a newer soundtouch-cli release",
|
||||
Action: runUpdateCheck,
|
||||
}
|
||||
}
|
||||
|
||||
func runUpdateCheck(c *cli.Context) error {
|
||||
checker := updatecheck.NewChecker(nil, updateCheckRepo, version)
|
||||
|
||||
result, err := checker.CheckNow(c.Context)
|
||||
if err != nil {
|
||||
return fmt.Errorf("update check failed: %w", err)
|
||||
}
|
||||
|
||||
printUpdateCheckResult(result)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func printUpdateCheckResult(result updatecheck.Result) {
|
||||
if result.LatestVersion == "" {
|
||||
fmt.Printf("Running %s, not a released version, skipping comparison.\n", result.CurrentVersion)
|
||||
return
|
||||
}
|
||||
|
||||
if result.Available {
|
||||
fmt.Printf("A newer version is available: %s (you're on %s)\n", result.LatestVersion, result.CurrentVersion)
|
||||
fmt.Println(result.ReleaseURL)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("You're on the latest version (%s).\n", result.CurrentVersion)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/updatecheck"
|
||||
)
|
||||
|
||||
// TestUpdateCheckCommand_Registered checks the command is wired up with the
|
||||
// expected name and an Action, without making any real GitHub API calls.
|
||||
func TestUpdateCheckCommand_Registered(t *testing.T) {
|
||||
cmd := updateCheckCommand()
|
||||
|
||||
if cmd.Name != "update-check" {
|
||||
t.Errorf("command name = %q; want %q", cmd.Name, "update-check")
|
||||
}
|
||||
|
||||
if cmd.Action == nil {
|
||||
t.Error("expected an Action to be set")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrintUpdateCheckResult_DoesNotPanic exercises all three result shapes
|
||||
// (unparseable current version, update available, up to date) purely for
|
||||
// the "does not panic" guarantee; updatecheck.Checker's own tests already
|
||||
// cover the comparison logic itself.
|
||||
func TestPrintUpdateCheckResult_DoesNotPanic(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
result updatecheck.Result
|
||||
}{
|
||||
{"unparseable current version", updatecheck.Result{CurrentVersion: "dev"}},
|
||||
{"update available", updatecheck.Result{CurrentVersion: "v1.0.0", LatestVersion: "v1.1.0", Available: true, ReleaseURL: "https://example.invalid"}},
|
||||
{"up to date", updatecheck.Result{CurrentVersion: "v1.1.0", LatestVersion: "v1.1.0", Available: false}},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
printUpdateCheckResult(tc.result)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2339,6 +2339,9 @@ func main() {
|
||||
// Defined in cmd_library.go.
|
||||
app.Commands = append(app.Commands, libraryCommand())
|
||||
|
||||
// On-demand GitHub release check (#591). Defined in cmd_updatecheck.go.
|
||||
app.Commands = append(app.Commands, updateCheckCommand())
|
||||
|
||||
// Sort commands alphabetically (including subcommands and flags recursively)
|
||||
sortCommands(app.Commands)
|
||||
|
||||
|
||||
@@ -25,6 +25,9 @@ Based on captured WebSocket interactions and device API capabilities, this web U
|
||||
- **Real-time status monitoring** via WebSocket connections
|
||||
- **Multi-device support** with centralized control
|
||||
- **Connection status** indicators and health monitoring
|
||||
- **SoundTouch 10 stereo pairs** shown as one target, with verified create,
|
||||
rename, and dissolve operations across both physical speakers and their
|
||||
exact persisted group generation
|
||||
|
||||
### Playback Control
|
||||
- **Play/Pause/Stop/Next/Previous** controls
|
||||
@@ -88,7 +91,7 @@ go build -o soundtouch-player
|
||||
./soundtouch-player -port 8888
|
||||
|
||||
# Connect to specific device
|
||||
./soundtouch-player -host 192.0.2.100
|
||||
./soundtouch-player --devices 192.0.2.100
|
||||
```
|
||||
|
||||
### Command Line Options
|
||||
@@ -137,7 +140,7 @@ device datastore).
|
||||
The application automatically discovers SoundTouch devices using:
|
||||
- **mDNS discovery** for local network devices
|
||||
- **UPnP/SSDP discovery** as fallback
|
||||
- **Manual device addition** via IP address
|
||||
- **Configured devices** via `--devices`, retried whenever discovery runs
|
||||
|
||||
### Real-time Updates
|
||||
The interface maintains WebSocket connections to each device for instant updates of:
|
||||
@@ -345,6 +348,14 @@ Based on WebSocket interaction analysis, potential future features:
|
||||
- Advanced preset programming
|
||||
- Progressive Web App (PWA) features
|
||||
|
||||
## Behaviour reference
|
||||
|
||||
[Player: Sources and Selection State](../../docs/content/docs/reference/PLAYER-SOURCE-BEHAVIOUR.md)
|
||||
covers the parts that are not obvious from the code: which advertised sources
|
||||
can actually be selected and which need a station ContentItem, how a selection
|
||||
is confirmed against a speaker that answers 200 either way, and the revision
|
||||
and epoch fields the browser uses to order status updates.
|
||||
|
||||
## License
|
||||
|
||||
Same as the parent project - see main repository LICENSE file.
|
||||
|
||||
@@ -161,7 +161,7 @@ func main() {
|
||||
log.Printf("Trusting AfterTouch service CA from %s", sanitizeLog(caPath))
|
||||
}
|
||||
|
||||
discoveryService := soundtouchweb.NewDiscoveryService(ifaceName)
|
||||
discoveryService := soundtouchweb.NewDiscoveryService(ifaceName, manualHosts...)
|
||||
|
||||
// Discover devices on startup
|
||||
go func() {
|
||||
@@ -170,6 +170,11 @@ func main() {
|
||||
|
||||
webApp.BroadcastDiscoveryStatus("starting", webApp.DeviceCount())
|
||||
|
||||
// Register configured devices immediately rather than waiting for
|
||||
// the full mDNS/UPnP sweep below (bounded by cfg.DiscoveryTimeout,
|
||||
// currently 10s) to complete. manualHosts are also folded into
|
||||
// discoveryService's PreferredDevices so a host that's offline
|
||||
// right now still gets retried on every subsequent discovery pass.
|
||||
for _, host := range manualHosts {
|
||||
webApp.AddDeviceByHost(host, 8090, "manual")
|
||||
}
|
||||
|
||||
+743
-356
File diff suppressed because it is too large
Load Diff
@@ -1,13 +1,199 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
// newTestServiceContext builds a real *cli.Context against serviceFlags (the
|
||||
// exact flags soundtouch-service registers), so loadConfig tests exercise the
|
||||
// same parsing/env-var wiring production code does, instead of a hand-rolled
|
||||
// stand-in that could silently drift from it.
|
||||
func newTestServiceContext(t *testing.T, args ...string) *cli.Context {
|
||||
t.Helper()
|
||||
|
||||
app := &cli.App{Flags: serviceFlags}
|
||||
set := flag.NewFlagSet("test", flag.ContinueOnError)
|
||||
|
||||
for _, f := range serviceFlags {
|
||||
if err := f.Apply(set); err != nil {
|
||||
t.Fatalf("apply flag %v: %v", f.Names(), err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := set.Parse(args); err != nil {
|
||||
t.Fatalf("parse args %v: %v", args, err)
|
||||
}
|
||||
|
||||
return cli.NewContext(app, set, nil)
|
||||
}
|
||||
|
||||
func TestResolveFallbackHost(t *testing.T) {
|
||||
hostname, _ := os.Hostname()
|
||||
if hostname == "" {
|
||||
hostname = "localhost"
|
||||
}
|
||||
|
||||
hostname = strings.ToLower(hostname)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
deploymentMode string
|
||||
wantHost string
|
||||
wantWarn bool
|
||||
}{
|
||||
{"on-device uses localhost, no warning", "on-device", "localhost", false},
|
||||
{"public-network returns no fallback, no warning (caller must fail fast)", "public-network", "", false},
|
||||
{"private-network uses this host's own hostname, with warning", "private-network", hostname, true},
|
||||
{"unset/legacy behaves like private-network", "", hostname, true},
|
||||
{"unrecognized mode behaves like private-network", "some-typo", hostname, true},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
gotHost, gotWarn := resolveFallbackHost(tc.deploymentMode)
|
||||
if gotHost != tc.wantHost {
|
||||
t.Errorf("host: got %q, want %q", gotHost, tc.wantHost)
|
||||
}
|
||||
|
||||
if gotWarn != tc.wantWarn {
|
||||
t.Errorf("warnOnUse: got %v, want %v", gotWarn, tc.wantWarn)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadConfig_DeviceSeedRetryTuning(t *testing.T) {
|
||||
t.Run("defaults", func(t *testing.T) {
|
||||
config, err := loadConfig(newTestServiceContext(t))
|
||||
if err != nil {
|
||||
t.Fatalf("loadConfig() error = %v", err)
|
||||
}
|
||||
|
||||
if config.deviceSeedRetryInterval != 30*time.Second {
|
||||
t.Errorf("deviceSeedRetryInterval = %s, want 30s", config.deviceSeedRetryInterval)
|
||||
}
|
||||
|
||||
if config.deviceSeedRetryWindow != 10*time.Minute {
|
||||
t.Errorf("deviceSeedRetryWindow = %s, want 10m", config.deviceSeedRetryWindow)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("flags override the defaults", func(t *testing.T) {
|
||||
config, err := loadConfig(newTestServiceContext(t,
|
||||
"--device-seed-retry-interval=5s",
|
||||
"--device-seed-retry-window=1m"))
|
||||
if err != nil {
|
||||
t.Fatalf("loadConfig() error = %v", err)
|
||||
}
|
||||
|
||||
if config.deviceSeedRetryInterval != 5*time.Second {
|
||||
t.Errorf("deviceSeedRetryInterval = %s, want 5s", config.deviceSeedRetryInterval)
|
||||
}
|
||||
|
||||
if config.deviceSeedRetryWindow != time.Minute {
|
||||
t.Errorf("deviceSeedRetryWindow = %s, want 1m", config.deviceSeedRetryWindow)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unparseable values fall back to the defaults", func(t *testing.T) {
|
||||
config, err := loadConfig(newTestServiceContext(t,
|
||||
"--device-seed-retry-interval=not-a-duration",
|
||||
"--device-seed-retry-window=also-not-a-duration"))
|
||||
if err != nil {
|
||||
t.Fatalf("loadConfig() error = %v", err)
|
||||
}
|
||||
|
||||
if config.deviceSeedRetryInterval != 30*time.Second {
|
||||
t.Errorf("deviceSeedRetryInterval = %s, want fallback 30s", config.deviceSeedRetryInterval)
|
||||
}
|
||||
|
||||
if config.deviceSeedRetryWindow != 10*time.Minute {
|
||||
t.Errorf("deviceSeedRetryWindow = %s, want fallback 10m", config.deviceSeedRetryWindow)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestLoadConfig_DeploymentMode(t *testing.T) {
|
||||
t.Run("on-device with no --server-url defaults to localhost", func(t *testing.T) {
|
||||
config, err := loadConfig(newTestServiceContext(t, "--deployment-mode=on-device", "--port=8000"))
|
||||
if err != nil {
|
||||
t.Fatalf("loadConfig: unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if config.serverURL != "http://localhost:8000" {
|
||||
t.Errorf("serverURL: got %q, want %q", config.serverURL, "http://localhost:8000")
|
||||
}
|
||||
|
||||
if config.httpsDefaultURL != "https://localhost:8443" {
|
||||
t.Errorf("httpsDefaultURL: got %q, want %q", config.httpsDefaultURL, "https://localhost:8443")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("public-network with no --server-url fails fast instead of guessing", func(t *testing.T) {
|
||||
_, err := loadConfig(newTestServiceContext(t, "--deployment-mode=public-network"))
|
||||
if err == nil {
|
||||
t.Fatal("expected an error, got nil")
|
||||
}
|
||||
|
||||
if !strings.Contains(err.Error(), "public-network") {
|
||||
t.Errorf("expected error to mention public-network, got: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("public-network with an explicit --server-url succeeds", func(t *testing.T) {
|
||||
config, err := loadConfig(newTestServiceContext(t,
|
||||
"--deployment-mode=public-network", "--server-url=https://soundtouch.example.com"))
|
||||
if err != nil {
|
||||
t.Fatalf("loadConfig: unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if config.serverURL != "https://soundtouch.example.com" {
|
||||
t.Errorf("serverURL: got %q, want %q", config.serverURL, "https://soundtouch.example.com")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unset deployment-mode with no --server-url keeps today's hostname fallback", func(t *testing.T) {
|
||||
hostname, _ := os.Hostname()
|
||||
if hostname == "" {
|
||||
hostname = "localhost"
|
||||
}
|
||||
|
||||
hostname = strings.ToLower(hostname)
|
||||
|
||||
config, err := loadConfig(newTestServiceContext(t, "--port=8000"))
|
||||
if err != nil {
|
||||
t.Fatalf("loadConfig: unexpected error: %v", err)
|
||||
}
|
||||
|
||||
want := "http://" + hostname + ":8000"
|
||||
if config.serverURL != want {
|
||||
t.Errorf("serverURL: got %q, want %q (legacy installs must keep working without --deployment-mode)", config.serverURL, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("explicit --server-url always wins regardless of deployment-mode", func(t *testing.T) {
|
||||
for _, mode := range []string{"", "on-device", "private-network", "public-network"} {
|
||||
config, err := loadConfig(newTestServiceContext(t,
|
||||
"--deployment-mode="+mode, "--server-url=http://198.51.100.7:8000"))
|
||||
if err != nil {
|
||||
t.Fatalf("mode %q: loadConfig: unexpected error: %v", mode, err)
|
||||
}
|
||||
|
||||
if config.serverURL != "http://198.51.100.7:8000" {
|
||||
t.Errorf("mode %q: serverURL: got %q, want explicit override unchanged", mode, config.serverURL)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestApplyPersistedSettings(t *testing.T) {
|
||||
tmpDir, err := os.MkdirTemp("", "main-test")
|
||||
if err != nil {
|
||||
|
||||
@@ -39,11 +39,8 @@ func TestPrintRoutes(t *testing.T) {
|
||||
// Now we might have "soundtouch-service.setupRouter.func1"
|
||||
// or "command-line-arguments.setupRouter.func1"
|
||||
// or "main.setupRouter.func1"
|
||||
// Let's remove the first part if it's a known varying package name
|
||||
if idx := strings.Index(handlerName, "setupRouter"); idx != -1 {
|
||||
handlerName = handlerName[idx:]
|
||||
}
|
||||
// In case it's not setupRouter but still has a package prefix
|
||||
// Remove the leading package/binary-name segment(s), whatever form
|
||||
// they take.
|
||||
for {
|
||||
dotIdx := strings.Index(handlerName, ".")
|
||||
if dotIdx == -1 {
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/stereopair"
|
||||
)
|
||||
|
||||
// neverDNSHijacked is the default DNS-hijack predicate for tests that don't
|
||||
// exercise the DNS-migrated-speaker path (see
|
||||
// TestEmbeddedStereoPairPersistenceTreatsDNSHijackedBoseHostAsLocal).
|
||||
func neverDNSHijacked(string) bool { return false }
|
||||
|
||||
// rejectingRoundTripper errors on every request and counts how many it saw.
|
||||
// A preflight failure is now logged and swallowed rather than propagated
|
||||
// (see TestEmbeddedStereoPairPersistenceSkipsExternalWritesButAttemptsRead),
|
||||
// so tests that need to prove an external dispatch actually happened check
|
||||
// calls rather than the returned error.
|
||||
type rejectingRoundTripper struct {
|
||||
calls int
|
||||
}
|
||||
|
||||
func (r *rejectingRoundTripper) RoundTrip(*http.Request) (*http.Response, error) {
|
||||
r.calls++
|
||||
|
||||
return nil, errors.New("unexpected HTTP persistence request")
|
||||
}
|
||||
|
||||
func persistenceTestGroup(id string) *models.Group {
|
||||
return &models.Group{
|
||||
ID: id,
|
||||
Name: "Living room",
|
||||
MasterDeviceID: "LEFT-ID",
|
||||
Roles: models.GroupRoles{Roles: []models.GroupRole{
|
||||
{DeviceID: "LEFT-ID", Role: "LEFT", IPAddress: "192.0.2.10"},
|
||||
{DeviceID: "RIGHT-ID", Role: "RIGHT", IPAddress: "192.0.2.11"},
|
||||
}},
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbeddedStereoPairPersistenceUsesLocalDatastoreAcrossAccounts(t *testing.T) {
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
group := persistenceTestGroup("")
|
||||
groupID, err := ds.AddGroup("OLD-ACCOUNT", group)
|
||||
if err != nil {
|
||||
t.Fatalf("AddGroup: %v", err)
|
||||
}
|
||||
|
||||
localURL := "https://aftertouch.invalid:18443"
|
||||
cleanup, preflight, rename := embeddedStereoPairGenerationPersistence(
|
||||
ds,
|
||||
func() []string { return []string{localURL} },
|
||||
neverDNSHijacked,
|
||||
&http.Client{Transport: &rejectingRoundTripper{}},
|
||||
)
|
||||
|
||||
err = preflight([]stereopair.GenerationRef{{
|
||||
DeviceID: "LEFT-ID", AccountID: "NEW-ACCOUNT", MargeURL: localURL,
|
||||
}})
|
||||
if err == nil || !strings.Contains(err.Error(), groupID) {
|
||||
t.Fatalf("preflight error = %v, want cross-account generation %s", err, groupID)
|
||||
}
|
||||
if err := rename(stereopair.GenerationRef{
|
||||
DeviceID: "LEFT-ID", AccountID: "NEW-ACCOUNT", MargeURL: localURL,
|
||||
GroupID: groupID, ExpectedGroup: group,
|
||||
}, "Renamed living room"); err != nil {
|
||||
t.Fatalf("rename: %v", err)
|
||||
}
|
||||
group.Name = "Renamed living room"
|
||||
|
||||
if err := cleanup(stereopair.GenerationRef{
|
||||
DeviceID: "LEFT-ID", AccountID: "NEW-ACCOUNT", MargeURL: localURL,
|
||||
GroupID: groupID, ExpectedGroup: group,
|
||||
}); err != nil {
|
||||
t.Fatalf("cleanup: %v", err)
|
||||
}
|
||||
|
||||
if err := preflight([]stereopair.GenerationRef{{
|
||||
DeviceID: "LEFT-ID", AccountID: "NEW-ACCOUNT", MargeURL: localURL,
|
||||
}}); err != nil {
|
||||
t.Fatalf("preflight after exact cleanup: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbeddedStereoPairCleanupMapsAmbiguousGenerationToConflict(t *testing.T) {
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
group := persistenceTestGroup("")
|
||||
groupID, err := ds.AddGroup("ACCOUNT1", group)
|
||||
if err != nil {
|
||||
t.Fatalf("AddGroup: %v", err)
|
||||
}
|
||||
localURL := "https://aftertouch.invalid:18443"
|
||||
cleanup, _, _ := embeddedStereoPairGenerationPersistence(
|
||||
ds,
|
||||
func() []string { return []string{localURL} },
|
||||
neverDNSHijacked,
|
||||
&http.Client{Transport: &rejectingRoundTripper{}},
|
||||
)
|
||||
wrongTopology := persistenceTestGroup(groupID)
|
||||
wrongTopology.Roles.Roles[1].DeviceID = "SUBSTITUTE-RIGHT-ID"
|
||||
|
||||
err = cleanup(stereopair.GenerationRef{
|
||||
DeviceID: "LEFT-ID", AccountID: "ACCOUNT1", MargeURL: localURL,
|
||||
GroupID: groupID, ExpectedGroup: wrongTopology,
|
||||
})
|
||||
if !errors.Is(err, stereopair.ErrConflict) || errors.Is(err, stereopair.ErrUnavailable) {
|
||||
t.Fatalf("cleanup error = %v, want ErrConflict only", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEmbeddedStereoPairPersistenceSkipsExternalWritesButAttemptsRead covers
|
||||
// an external (non-local) MargeURL: cleanup and rename must never push to a
|
||||
// backend we don't own -- the speaker itself self-reports its own group
|
||||
// teardown/rename to whatever Marge backend it's configured with, which is
|
||||
// the entire reason HandleMargeDeleteGroup/HandleMargeModifyGroup exist
|
||||
// (they're only ever called by speakers). Preflight still attempts its
|
||||
// read-only dangling-generation check, but a failure there (network error,
|
||||
// wrong credentials, real Bose cloud rejecting us, ...) must not block
|
||||
// Create, since it's a best-effort check on top of the coordinator's own
|
||||
// physical preflight, not the primary guard.
|
||||
func TestEmbeddedStereoPairPersistenceSkipsExternalWritesButAttemptsRead(t *testing.T) {
|
||||
getCalls := 0
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/device/LEFT-ID/group") {
|
||||
getCalls++
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
t.Fatalf("unexpected external %s %s: cleanup/rename must not write to a backend we don't own", r.Method, r.URL.Path)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
cleanup, preflight, rename := embeddedStereoPairGenerationPersistence(
|
||||
datastore.NewDataStore(t.TempDir()),
|
||||
func() []string { return []string{"http://aftertouch.invalid:18000"} },
|
||||
neverDNSHijacked,
|
||||
server.Client(),
|
||||
)
|
||||
|
||||
ref := stereopair.GenerationRef{
|
||||
DeviceID: "LEFT-ID", AccountID: "ACCOUNT1", MargeURL: server.URL + "/marge",
|
||||
GroupID: "7654321", ExpectedGroup: persistenceTestGroup("7654321"),
|
||||
}
|
||||
|
||||
if err := rename(ref, "Renamed living room"); err != nil {
|
||||
t.Fatalf("rename = %v, want nil (speaker self-reports its own rename)", err)
|
||||
}
|
||||
if err := cleanup(ref); err != nil {
|
||||
t.Fatalf("cleanup = %v, want nil (speaker self-reports its own teardown)", err)
|
||||
}
|
||||
if err := preflight([]stereopair.GenerationRef{ref}); err != nil {
|
||||
t.Fatalf("preflight = %v, want nil: an unauthenticated external check must not block Create", err)
|
||||
}
|
||||
if getCalls != 1 {
|
||||
t.Fatalf("external GET calls = %d, want exactly 1 (preflight must still attempt the read)", getCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbeddedStereoPairPersistenceReadsOneCurrentURLSnapshot(t *testing.T) {
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
group := persistenceTestGroup("")
|
||||
groupID, err := ds.AddGroup("OLD-ACCOUNT", group)
|
||||
if err != nil {
|
||||
t.Fatalf("AddGroup: %v", err)
|
||||
}
|
||||
|
||||
currentURL := "http://old.invalid:18000"
|
||||
providerCalls := 0
|
||||
transport := &rejectingRoundTripper{}
|
||||
_, preflight, _ := embeddedStereoPairGenerationPersistence(
|
||||
ds,
|
||||
func() []string {
|
||||
providerCalls++
|
||||
return []string{currentURL}
|
||||
},
|
||||
neverDNSHijacked,
|
||||
&http.Client{Transport: transport},
|
||||
)
|
||||
|
||||
currentURL = "http://new.invalid:18000"
|
||||
err = preflight([]stereopair.GenerationRef{
|
||||
{DeviceID: "LEFT-ID", AccountID: "NEW-ACCOUNT", MargeURL: currentURL},
|
||||
{DeviceID: "RIGHT-ID", AccountID: "NEW-ACCOUNT", MargeURL: currentURL},
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), groupID) {
|
||||
t.Fatalf("preflight error = %v, want current local generation %s", err, groupID)
|
||||
}
|
||||
if providerCalls != 1 {
|
||||
t.Fatalf("URL provider calls = %d, want one coherent snapshot", providerCalls)
|
||||
}
|
||||
|
||||
// The old URL no longer matches localMargeURLs()'s current snapshot, so
|
||||
// this ref is external. Preflight still attempts the read (proven by the
|
||||
// transport call count) but no longer propagates its failure -- an
|
||||
// external check failing must not block Create.
|
||||
err = preflight([]stereopair.GenerationRef{{
|
||||
DeviceID: "LEFT-ID", AccountID: "OLD-ACCOUNT", MargeURL: "http://old.invalid:18000",
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("old URL preflight error = %v, want nil (external check failure must not block)", err)
|
||||
}
|
||||
if transport.calls != 1 {
|
||||
t.Fatalf("external HTTP dispatch calls = %d, want exactly 1", transport.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEmbeddedStereoPairPersistenceTreatsDNSHijackedBoseHostAsLocal covers a
|
||||
// speaker migrated at the DNS level: its own reported MargeURL is still the
|
||||
// literal Bose cloud hostname (DNS migration never changes it), but this
|
||||
// service's DNS hijack redirects that hostname to itself on the network.
|
||||
// Routing it through the external HTTP path instead would reach the real,
|
||||
// still-live Bose cloud and 401 there, hard-blocking Create for a normal
|
||||
// DNS-migrated setup. Uses rejectingRoundTripper to prove no HTTP call is
|
||||
// attempted at all.
|
||||
func TestEmbeddedStereoPairPersistenceTreatsDNSHijackedBoseHostAsLocal(t *testing.T) {
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
group := persistenceTestGroup("")
|
||||
groupID, err := ds.AddGroup("OLD-ACCOUNT", group)
|
||||
if err != nil {
|
||||
t.Fatalf("AddGroup: %v", err)
|
||||
}
|
||||
|
||||
_, preflight, _ := embeddedStereoPairGenerationPersistence(
|
||||
ds,
|
||||
func() []string { return []string{"https://aftertouch.invalid:18443"} },
|
||||
func(margeURL string) bool { return strings.Contains(margeURL, "streaming.bose.com") },
|
||||
&http.Client{Transport: &rejectingRoundTripper{}},
|
||||
)
|
||||
|
||||
err = preflight([]stereopair.GenerationRef{{
|
||||
DeviceID: "LEFT-ID", AccountID: "NEW-ACCOUNT", MargeURL: "https://streaming.bose.com",
|
||||
}})
|
||||
if err == nil || !strings.Contains(err.Error(), groupID) {
|
||||
t.Fatalf("preflight error = %v, want local generation %s found via datastore, not an external HTTP call", err, groupID)
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -6,6 +6,7 @@ DELETE /accounts/{account}/group/ handlers.(
|
||||
DELETE /accounts/{account}/group/{groupId} handlers.(*Server).HandleUnsupported-fm
|
||||
DELETE /api/control/devices/{id}/ soundtouchweb.(*WebApp).HandleDeleteDevice-fm
|
||||
DELETE /api/control/devices/{id}/library/servers/{account} soundtouchweb.(*WebApp).HandleRemoveLibraryServer-fm
|
||||
DELETE /api/control/devices/{id}/stereo-pair/ soundtouchweb.(*WebApp).HandleDissolveStereoPair-fm
|
||||
DELETE /api/setup/devices/{deviceId} handlers.(*Server).HandleRemoveDevice-fm
|
||||
DELETE /api/setup/dns-discoveries handlers.(*Server).HandleClearDNSDiscoveries-fm
|
||||
DELETE /api/setup/interactions/sessions handlers.(*Server).HandleCleanupSessions-fm
|
||||
@@ -42,10 +43,13 @@ GET /api/control/devices/{id}/ soundtouch
|
||||
GET /api/control/devices/{id}/action/{action} soundtouchweb.(*WebApp).HandleAPIControl-fm
|
||||
GET /api/control/devices/{id}/library/browse soundtouchweb.(*WebApp).HandleLibraryBrowse-fm
|
||||
GET /api/control/devices/{id}/library/servers soundtouchweb.(*WebApp).HandleDeviceLibraryServers-fm
|
||||
GET /api/control/devices/{id}/now-playing soundtouchweb.(*WebApp).HandleDeviceNowPlaying-fm
|
||||
GET /api/control/devices/{id}/power-status soundtouchweb.(*WebApp).HandleDevicePowerStatus-fm
|
||||
GET /api/control/devices/{id}/recents soundtouchweb.(*WebApp).HandleDeviceRecents-fm
|
||||
GET /api/control/devices/{id}/stereo-pair/ soundtouchweb.(*WebApp).HandleGetStereoPair-fm
|
||||
GET /api/control/devices/{id}/ws soundtouchweb.(*WebApp).HandleDeviceWebSocket-fm
|
||||
GET /api/control/devices/{id}/zone/ soundtouchweb.(*WebApp).HandleGetZone-fm
|
||||
GET /api/control/devices/{id}/zone/candidates soundtouchweb.(*WebApp).HandleGetZoneCandidates-fm
|
||||
GET /api/control/providers/library/servers soundtouchweb.(*WebApp).HandleDiscoverLibraryServers-fm
|
||||
GET /api/control/providers/radiobrowser/search soundtouchweb.(*WebApp).HandleRadioBrowserSearch-fm
|
||||
GET /api/control/providers/tunein/navigate soundtouchweb.(*WebApp).HandleTuneInNavigate-fm
|
||||
@@ -169,11 +173,12 @@ GET /streaming/sourceproviders handlers.(
|
||||
GET /updates/soundtouch handlers.(*Server).HandleMargeSoftwareUpdate-fm
|
||||
GET /v1/auth handlers.(*Server).HandleSpeakerAuth-fm
|
||||
GET /v1/blacklist/{deviceId} setupRouter
|
||||
GET /web/* setupRouter.(*Server).HandleWeb
|
||||
GET /web/* handlers.(*Server).HandleWeb
|
||||
HEAD /core02/svc-bmx-adapter-siriusxm-everest-eco1/prod/live-adapter handlers.(*Server).HandleSiriusXMLiveAdapter-fm
|
||||
HEAD /core02/svc-bmx-adapter-siriusxm-everest-eco1/prod/live-adapter/* handlers.(*Server).HandleSiriusXMLiveAdapterSubpath-fm
|
||||
OPTIONS /core02/svc-bmx-adapter-siriusxm-everest-eco1/prod/live-adapter handlers.(*Server).HandleSiriusXMLiveAdapter-fm
|
||||
OPTIONS /core02/svc-bmx-adapter-siriusxm-everest-eco1/prod/live-adapter/* handlers.(*Server).HandleSiriusXMLiveAdapterSubpath-fm
|
||||
PATCH /api/control/devices/{id}/stereo-pair/ soundtouchweb.(*WebApp).HandleRenameStereoPair-fm
|
||||
PATCH /core02/svc-bmx-adapter-siriusxm-everest-eco1/prod/live-adapter handlers.(*Server).HandleSiriusXMLiveAdapter-fm
|
||||
PATCH /core02/svc-bmx-adapter-siriusxm-everest-eco1/prod/live-adapter/* handlers.(*Server).HandleSiriusXMLiveAdapterSubpath-fm
|
||||
POST /accounts/{account}/devices handlers.(*Server).HandleUnsupported-fm
|
||||
@@ -194,6 +199,7 @@ POST /api/control/devices/{id}/providers/radiobrowser/play soundtouch
|
||||
POST /api/control/devices/{id}/providers/tts/play soundtouchweb.(*WebApp).HandleAPISpeakText-fm
|
||||
POST /api/control/devices/{id}/providers/tunein/play soundtouchweb.(*WebApp).HandlePlayTuneIn-fm
|
||||
POST /api/control/devices/{id}/providers/url/play soundtouchweb.(*WebApp).HandlePlayURL-fm
|
||||
POST /api/control/devices/{id}/stereo-pair/ soundtouchweb.(*WebApp).HandleCreateStereoPair-fm
|
||||
POST /api/control/devices/{id}/volume/{volume} soundtouchweb.(*WebApp).HandleDirectVolumeControl-fm
|
||||
POST /api/control/devices/{id}/zone/add/{slaveId} soundtouchweb.(*WebApp).HandleZoneAdd-fm
|
||||
POST /api/control/devices/{id}/zone/dissolve soundtouchweb.(*WebApp).HandleZoneDissolve-fm
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/updatecheck"
|
||||
)
|
||||
|
||||
func TestShouldCheckImmediately(t *testing.T) {
|
||||
now := time.Date(2026, 8, 9, 12, 0, 0, 0, time.UTC)
|
||||
interval := 24 * time.Hour
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
lastCheckedAt time.Time
|
||||
want bool
|
||||
}{
|
||||
{"never checked", time.Time{}, true},
|
||||
{"stale (older than interval)", now.Add(-25 * time.Hour), true},
|
||||
{"exactly one interval ago", now.Add(-interval), true},
|
||||
{"recent (within interval)", now.Add(-1 * time.Hour), false},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
if got := shouldCheckImmediately(tc.lastCheckedAt, interval, now); got != tc.want {
|
||||
t.Errorf("%s: shouldCheckImmediately() = %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldSkipDueToBackoff(t *testing.T) {
|
||||
now := time.Date(2026, 8, 9, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
lastErrorAt time.Time
|
||||
want bool
|
||||
}{
|
||||
{"no recent failure", time.Time{}, false},
|
||||
{"failed 30 minutes ago", now.Add(-30 * time.Minute), true},
|
||||
{"failed exactly 1 hour ago", now.Add(-time.Hour), false},
|
||||
{"failed 2 hours ago", now.Add(-2 * time.Hour), false},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
if got := shouldSkipDueToBackoff(tc.lastErrorAt, now); got != tc.want {
|
||||
t.Errorf("%s: shouldSkipDueToBackoff() = %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogUpdateIfNewlyAvailable(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
result updatecheck.Result
|
||||
lastLoggedVersion string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "nothing available",
|
||||
result: updatecheck.Result{Available: false},
|
||||
lastLoggedVersion: "",
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "newly available",
|
||||
result: updatecheck.Result{Available: true, LatestVersion: "v1.1.0"},
|
||||
lastLoggedVersion: "",
|
||||
want: "v1.1.0",
|
||||
},
|
||||
{
|
||||
name: "already logged this version",
|
||||
result: updatecheck.Result{Available: true, LatestVersion: "v1.1.0"},
|
||||
lastLoggedVersion: "v1.1.0",
|
||||
want: "v1.1.0",
|
||||
},
|
||||
{
|
||||
name: "a newer version than what was logged",
|
||||
result: updatecheck.Result{Available: true, LatestVersion: "v1.2.0"},
|
||||
lastLoggedVersion: "v1.1.0",
|
||||
want: "v1.2.0",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
if got := logUpdateIfNewlyAvailable(tc.result, tc.lastLoggedVersion); got != tc.want {
|
||||
t.Errorf("%s: logUpdateIfNewlyAvailable() = %q, want %q", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRandomJitter(t *testing.T) {
|
||||
if got := randomJitter(0); got != 0 {
|
||||
t.Errorf("randomJitter(0) = %v, want 0", got)
|
||||
}
|
||||
|
||||
upperBound := 5 * time.Minute
|
||||
for i := 0; i < 20; i++ {
|
||||
got := randomJitter(upperBound)
|
||||
if got < 0 || got >= upperBound {
|
||||
t.Fatalf("randomJitter(%v) = %v, want in [0, %v)", upperBound, got, upperBound)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// There is deliberately no test for startUpdateCheck itself, matching
|
||||
// startDeviceDiscovery (its equally untested sibling): both are thin,
|
||||
// forever-looping goroutine wrappers whose only decisions live in pure
|
||||
// helpers, which is what the tests above and below cover. The former
|
||||
// TestStartUpdateCheck_DisabledIsANoOp asserted a contract that no longer
|
||||
// exists — the goroutine now always starts, precisely so that enabling the
|
||||
// check from the Settings page takes effect without a restart, and an
|
||||
// early return for "disabled" would defeat that.
|
||||
func TestShouldRunUpdateCheckNow(t *testing.T) {
|
||||
now := time.Date(2026, 8, 10, 12, 0, 0, 0, time.UTC)
|
||||
interval := 24 * time.Hour
|
||||
stale := now.Add(-25 * time.Hour)
|
||||
fresh := now.Add(-1 * time.Hour)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
enabled bool
|
||||
lastCheckedAt time.Time
|
||||
interval time.Duration
|
||||
lastErrorAt time.Time
|
||||
want bool
|
||||
}{
|
||||
{"disabled, never checked", false, time.Time{}, interval, time.Time{}, false},
|
||||
{"disabled, due", false, stale, interval, time.Time{}, false},
|
||||
{"enabled, never checked", true, time.Time{}, interval, time.Time{}, true},
|
||||
{"enabled, due", true, stale, interval, time.Time{}, true},
|
||||
{"enabled, not due yet", true, fresh, interval, time.Time{}, false},
|
||||
{"enabled and due, but in error backoff", true, stale, interval, now.Add(-30 * time.Minute), false},
|
||||
{"enabled and due, backoff expired", true, stale, interval, now.Add(-2 * time.Hour), true},
|
||||
// A zero interval must not turn every poll tick into a GitHub request.
|
||||
{"enabled with a zero interval", true, stale, 0, time.Time{}, false},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
got := shouldRunUpdateCheckNow(tc.enabled, tc.lastCheckedAt, tc.interval, tc.lastErrorAt, now)
|
||||
if got != tc.want {
|
||||
t.Errorf("%s: shouldRunUpdateCheckNow() = %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCheckPollTickIsShorterThanTheDefaultInterval guards the property
|
||||
// that makes the Settings-page toggle feel live: the goroutine must re-read
|
||||
// the settings far more often than the check interval itself, otherwise
|
||||
// switching the check on would appear to do nothing for up to a day.
|
||||
func TestUpdateCheckPollTickIsShorterThanTheDefaultInterval(t *testing.T) {
|
||||
if updateCheckPollTick >= 24*time.Hour {
|
||||
t.Errorf("updateCheckPollTick = %v, want well below the 24h default interval", updateCheckPollTick)
|
||||
}
|
||||
}
|
||||
@@ -8,3 +8,4 @@ parity_mismatches/
|
||||
stats/
|
||||
patterns.json
|
||||
settings.json
|
||||
update-check.json
|
||||
|
||||
@@ -35,7 +35,7 @@ services:
|
||||
start_period: 3s
|
||||
|
||||
spotify-mock:
|
||||
image: golang:1.26.5-alpine
|
||||
image: golang:1.27.1-alpine
|
||||
container_name: spotify-mock
|
||||
working_dir: /app
|
||||
volumes:
|
||||
@@ -53,7 +53,7 @@ services:
|
||||
start_period: 3s
|
||||
|
||||
amazon-mock:
|
||||
image: golang:1.26.5-alpine
|
||||
image: golang:1.27.1-alpine
|
||||
container_name: amazon-mock
|
||||
working_dir: /app
|
||||
volumes:
|
||||
@@ -71,7 +71,7 @@ services:
|
||||
start_period: 3s
|
||||
|
||||
tunein-mock:
|
||||
image: golang:1.26.5-alpine
|
||||
image: golang:1.27.1-alpine
|
||||
container_name: tunein-mock
|
||||
working_dir: /app
|
||||
volumes:
|
||||
|
||||
@@ -112,6 +112,18 @@ Factory-reset the same speaker again and run the full state machine — the same
|
||||
|
||||
This drives `setup.Manager.ExecuteInitPlan` with `SkipURLRewrite=true`, which runs:
|
||||
|
||||
> **Update (#615):** `--mode=full` now preflights via `Manager.PreflightInitPlan`
|
||||
> before opening the WebSocket — it checks `/supportedURLs` for
|
||||
> `/setMargeAccount` and requires `/soundTouchConfigurationStatus` to read
|
||||
> `SOUNDTOUCH_NOT_CONFIGURED`, and no-ops on an already-configured device.
|
||||
> A freshly factory-reset speaker (as in this experiment) reports
|
||||
> `SOUNDTOUCH_NOT_CONFIGURED`, so the preflight passes through unchanged;
|
||||
> see `docs/content/docs/reference/DEVICE-PAIRING-FLOW.md`.
|
||||
|
||||
The historical capture below sent language code `2`. Stockholm's language
|
||||
table identifies that code as German; current English-language setup uses code
|
||||
`3`. The original wire value is retained here as experiment evidence.
|
||||
|
||||
```
|
||||
SETUP_START
|
||||
SETUP_IDENTIFY_DEVICE_ENTER
|
||||
|
||||
@@ -100,16 +100,16 @@ also visible on the ST 20/300/Wave captures in #221. Different from the
|
||||
`sys presetkey N p` form (S4) — the `key prefix_N` shape on FW 27 is what
|
||||
the device's own remote sends.
|
||||
|
||||
| Command | Effect | Source |
|
||||
|---------------------------------|---------------------------------------------------------------------------------------|--------|
|
||||
| `key prefix_1` … `key prefix_6` | Triggers preset 1–6 (same as a remote preset press). | S5 |
|
||||
| `key play` | Begin / resume playback. | S5 |
|
||||
| `key pause` | Pause playback. | S5 |
|
||||
| `key stop` | Stop playback (does **not** terminate the underlying stream). | S5 |
|
||||
| `key prev` | Restart current song / previous track. | S5 |
|
||||
| `key next` | Next track. | S5 |
|
||||
| `key aux` | Toggle Bluetooth / AUX input. | S5 |
|
||||
| `key power` | Echoes "OK" but no observable effect on FW 27.x — possibly handled at a higher layer. | S5 |
|
||||
| Command | Effect | Source |
|
||||
|---------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------|
|
||||
| `key prefix_1` … `key prefix_6` | Triggers preset 1–6 (same as a remote preset press). | S5 |
|
||||
| `key play` | Begin / resume playback. | S5 |
|
||||
| `key pause` | Pause playback. | S5 |
|
||||
| `key stop` | Stop playback (does **not** terminate the underlying stream). | S5 |
|
||||
| `key prev` | Restart current song / previous track. | S5 |
|
||||
| `key next` | Next track. | S5 |
|
||||
| `key aux` | Toggle Bluetooth / AUX input. | S5 |
|
||||
| `key power` | Echoes "OK" but no observable effect on FW 27.x — possibly handled at a higher layer. On Lifestyle/CineMate console devices this is **not** a no-op: it puts the console into standby and, on waking, returns it to the console's own input rather than SoundTouch — see [Lifestyle / Console Device Behavior](../guides/TROUBLESHOOTING.md#lifestyle-console-devices) and #597. | S5 |
|
||||
|
||||
The S4 `bose` script's `sys presetkey N p` form still works, but `key prefix_N` is shorter and matches what the remote already does on FW 27.x.
|
||||
|
||||
@@ -150,11 +150,15 @@ Each `sys configuration` setter is reported by users to return `OK` on success.
|
||||
|
||||
`envswitch` writes to a separate, lower-level persistence store that **wins on next reboot** if the corresponding `sys configuration` value differs. So our migration writes both — see TELNET-MIGRATION-METHOD.md §2.1.
|
||||
|
||||
| Command | Purpose | Source |
|
||||
|---------------------------------------------------|-----------------------------------------------------------------------------------------------|---------|
|
||||
| `envswitch boseurls set <margeUrl> <swUpdateUrl>` | Persist the marge and update URLs. **Two arguments**, in that order. | S6 |
|
||||
| `envswitch accountid set <numeric-id>` | Equivalent to the HTTP `/setMargeAccount` POST. Used as fallback in our `PairAccount` helper. | S6 |
|
||||
| `envswitch accountid get` | Plausible by symmetry but **not yet confirmed** across firmwares; we probe it best-effort. | (probe) |
|
||||
**It's a commit point, not just a two-field setter.** `envswitch boseurls set` persists whatever is currently in the runtime layer at the moment it runs — not only its own two arguments. Confirmed on five variants (`lisa`, `mojo`, `spotty`, `ginger`, `taigan`; [#515 comment 5231931569](https://github.com/gesellix/Bose-SoundTouch/issues/515#issuecomment-5231931569)): a `sys configuration` write survives a reboot **if and only if** an `envswitch boseurls set` runs after it. The same command sequence in reverse order silently loses the later `sys configuration` values on reboot — every command still answers, nothing looks wrong until the reboot. This is why our migration and SSH-enable sequences always issue all four `sys configuration` writes first and `envswitch boseurls set` last (see `telnetURLs.Commands()` / `EnableSSHViaTelnetFullConfig`).
|
||||
|
||||
**It does not acknowledge with `OK`.** Unlike `sys configuration` (which does), `envswitch boseurls set` responds with a different string (observed: `Setting Bose Server URLs to <a> and <b> ->`, no `OK` substring). An implementation that waits for the literal token `OK` will hit its own timeout on this exact command. Our `pkg/telnet.Client.SendCommand` doesn't string-match at all — it reads until the connection goes idle — so this only matters if you're hand-typing the sequence or reimplementing the client elsewhere.
|
||||
|
||||
| Command | Purpose | Source |
|
||||
|-------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|
|
||||
| `envswitch boseurls set <margeUrl> <swUpdateUrl>` | Persist the marge and update URLs, committing the runtime layer as it stands (see above). **Two arguments**, in that order. | S6 |
|
||||
| `envswitch accountid set <numeric-id>` | Equivalent to the HTTP `/setMargeAccount` POST. Used as fallback in our `PairAccount` helper. | S6 |
|
||||
| `envswitch accountid get`, bare `envswitch`, `envswitch boseurls` | **Confirmed unsupported** — all answer `Invalid Command Option` on `lisa`/`mojo`/`spotty` ([#515 comment 5231931569](https://github.com/gesellix/Bose-SoundTouch/issues/515#issuecomment-5231931569)). `envswitch` has no read form on any variant tested; the persisted layer can only be written, then observed indirectly after a reboot (e.g. via `getpdo`, which then reflects the *new* value). | (probe) |
|
||||
|
||||
---
|
||||
|
||||
@@ -166,6 +170,8 @@ Each `sys configuration` setter is reported by users to return `OK` on success.
|
||||
|-------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------|
|
||||
| `getpdo CurrentSystemConfiguration` | Echoes the resolved URL set, including margeServerUrl/bmxRegistryUrl/statsServerUrl/swUpdateUrl. We grep our targetURL out of this to confirm a successful migration. | S6 |
|
||||
|
||||
**The two layers are inverted in `getpdo` visibility around a reboot** ([#515 comment 5231931569](https://github.com/gesellix/Bose-SoundTouch/issues/515#issuecomment-5231931569)): *before* a reboot, `getpdo` shows the runtime (`sys configuration`) values immediately, while an `envswitch`-written value isn't visible yet; *after* a reboot, the `sys configuration` values are gone and the `envswitch`-persisted values are what's now applied. So a `getpdo` check run before rebooting confirms the writes were accepted, but it is **not** evidence the configuration will survive the reboot — only the `envswitch` write (in the right order, see above) determines that. This is why our own migration verification (`migrateViaTelnet`) checks `getpdo` before reboot only to confirm the runtime layer accepted the values, and never claims persistence from it.
|
||||
|
||||
---
|
||||
|
||||
## The `scm` family — service control
|
||||
@@ -295,6 +301,14 @@ sys reboot
|
||||
|
||||
**Which devices need `--full-config`:** observed on the **SoundTouch Portable (Series I, model 412540, FW `27.0.6.46330.5043500`)** (#515) and on some **CineMate 520** units where the default path leaves `sshd` down. The structural differences from the default path that appear to matter are (1) the injection riding `sys configuration margeServerUrl`, not just `envswitch`, and (2) the explicit `sys reboot`. The `--full-config` automation is **candidate behaviour awaiting reporter confirmation** — the manual sequence is confirmed working on the ST Portable, but the flag that automates it has not yet been re-confirmed on hardware. Not every device responds even to the manual sequence (some ST10 and CineMate 520 units never start `sshd` over telnet at all and need the serial / U-Boot route).
|
||||
|
||||
**On the `--command-delay` between steps:** originally added because a reporter's back-to-back run left `sshd` down while a ~7s-gapped run succeeded ([#515 comment 5228449448](https://github.com/gesellix/Bose-SoundTouch/issues/515#issuecomment-5228449448)). That theory was **retracted** by the same reporter after a controlled A/B across three variants showed identical outcomes at 0s and 5s gaps ([comment 5231931569](https://github.com/gesellix/Bose-SoundTouch/issues/515#issuecomment-5231931569)) — the delay itself doesn't appear to matter. The default is kept small and non-zero (`setup.DefaultTelnetCommandDelay`) as a low-cost hedge for untested variants, not because the delay is known to help.
|
||||
|
||||
**The account-pairing precondition** (raised by `Henri-be`, [#515 comment 5230785528](https://github.com/gesellix/Bose-SoundTouch/issues/515#issuecomment-5230785528), tracing back to [#471 comment 4903016740](https://github.com/gesellix/Bose-SoundTouch/issues/471#issuecomment-4903016740); confirmed empirically by `bitranox`, [#515 comment 5232241580](https://github.com/gesellix/Bose-SoundTouch/issues/515#issuecomment-5232241580)): a genuinely unpaired (factory-reset, empty `margeAccountUUID`) device does not poll `margeServerUrl` **at all** — confirmed by pointing a reset device's marge URL at a listener and observing zero requests over 10+ minutes. The SSH-enable injection has no read cycle to fire on until the device is paired. `enable-ssh` handles this automatically by default (`EnsureMargeAccountPaired`, `--no-auto-pair` to skip).
|
||||
|
||||
**Factory reset does not remove root access, if it was ever persisted.** Confirmed on a genuinely factory-reset `spotty` ([#471 comment 5232232575](https://github.com/gesellix/Bose-SoundTouch/issues/471#issuecomment-5232232575)): after the reset, `margeAccountUUID` was empty, all four service URLs were back to `streaming.bose.com`, and presets were gone — but `/etc/remote_services` and `/mnt/nv/remote_services` **survived**, and SSH (:22) and telnet (:17000) stayed open. So once a device has been through `setup enable-ssh` with persistence (`EnsureRemoteServices`, the default), a later factory reset only wipes configuration, not root access — recovery is re-migrate + re-pair + rename + restore presets, with **no USB stick and no re-running the injection**.
|
||||
|
||||
**Readiness after a reboot is per-port, not a single moment.** `JRpersonal` first measured that the firmware needs roughly 60s after a cold boot before `:8090`'s `/info` answers and marge state is ready — a booting device answers a bare `HTTP 400` with an empty body before its services are up, which is easy to misread as a rejection rather than "too early" ([#471 comment 5231997551](https://github.com/gesellix/Bose-SoundTouch/issues/471#issuecomment-5231997551)). `bitranox` refined this across three variants: `:8090` and the diagnostic `:17000` shell (and the config subsystem behind it that `getpdo` reads) do **not** become ready at the same time — waiting for `:8090` and then immediately reading over `:17000` returned an empty response even though the box was otherwise up. Ten observed reboots: down in 2.3–5.3s, ready (able to answer `getpdo` correctly) in 55.1–91.8s, median ~69.8s ([#471 comment 5232046477](https://github.com/gesellix/Bose-SoundTouch/issues/471#issuecomment-5232046477)). Anything automated should wait for the specific interface it's about to use, not for a different port to answer first — see the troubleshooting guide's [power-cycle retry note](../guides/TROUBLESHOOTING.md) for the user-facing version of this.
|
||||
|
||||
---
|
||||
|
||||
## Out of scope here, but worth recording
|
||||
|
||||
@@ -82,6 +82,16 @@ Three important details from the discussion:
|
||||
silently restored on reboot — i.e. there is a parallel "envswitch" persistence
|
||||
layer that wins on next boot if you don't also write to it. **We must always
|
||||
issue both.**
|
||||
|
||||
A later, more precise measurement ([#515 comment 5231931569](https://github.com/gesellix/Bose-SoundTouch/issues/515#issuecomment-5231931569), confirmed on
|
||||
five variants: `lisa`/`mojo`/`spotty`/`ginger`/`taigan`) explains *why*
|
||||
order matters: `envswitch boseurls set` is not just a two-field setter, it
|
||||
**commits whatever is currently in the runtime layer at the moment it
|
||||
runs**. A `sys configuration` write only survives a reboot if `envswitch
|
||||
boseurls set` runs **after** it; the same commands in reverse order lose
|
||||
the `sys configuration` values silently on reboot, with every individual
|
||||
command still answering normally. This is why the sequence above is
|
||||
ordered all-four-`sys-configuration`-then-`envswitch`, never the reverse.
|
||||
2. **margeServerUrl path is bare for `soundtouch-service`.** We mount the marge
|
||||
endpoints at the **root** of port 8000, matching what the existing XML
|
||||
migration writes (`Manager.migrateViaXML` in `pkg/service/setup/setup.go`
|
||||
@@ -91,8 +101,15 @@ Three important details from the discussion:
|
||||
routes marge under that sub-path. **For our service: bare URL. For users
|
||||
redirecting to soundcork: append `/marge`** to both `margeServerUrl` and
|
||||
the first argument of `envswitch boseurls set`.
|
||||
3. **Each command must be sent one at a time, waiting for the device's `OK`
|
||||
response** before sending the next one (`foob61451`'s explicit warning).
|
||||
3. **Each command must be sent one at a time, waiting for the device's
|
||||
response** before sending the next one (`foob61451`'s original warning).
|
||||
Note the exception: `sys configuration` commands ack with `OK`, but
|
||||
`envswitch boseurls set` does **not** — it acks with a different string
|
||||
entirely (observed: `Setting Bose Server URLs to <a> and <b> ->`, no `OK`
|
||||
substring; [#515 comment 5231931569](https://github.com/gesellix/Bose-SoundTouch/issues/515#issuecomment-5231931569)). An implementation that waits for the
|
||||
literal token `OK` will time out on exactly that command. Wait for the
|
||||
shell's prompt (or, as our own `pkg/telnet.Client` does, for the
|
||||
connection to go idle) rather than string-matching `OK`.
|
||||
|
||||
### 2.2 Account pairing fallback
|
||||
|
||||
@@ -106,7 +123,11 @@ in-band equivalent to the HTTP `/setMargeAccount` call, useful when the
|
||||
about.
|
||||
- Useful read-only verification command: `getpdo CurrentSystemConfiguration` —
|
||||
prints the URLs after the changes have been applied so we can verify before
|
||||
rebooting.
|
||||
rebooting. **It only reflects the runtime (`sys configuration`) layer, not
|
||||
the `envswitch`-persisted layer, so a matching `getpdo` here confirms the
|
||||
writes were accepted, not that they will survive the reboot** — see the
|
||||
layer-visibility caveat in
|
||||
[TELNET-COMMAND-REFERENCE.md](TELNET-COMMAND-REFERENCE.md).
|
||||
- `sys reboot` is the trigger that re-reads both layers.
|
||||
|
||||
### 2.4 What Telnet:17000 cannot do
|
||||
@@ -145,6 +166,22 @@ The values are not validated by the local service, so any numeric `accountId`
|
||||
will work — soundcork's runbook (#228) literally calls the token
|
||||
`soundcorkdoesntcare` to make the point.
|
||||
|
||||
> **Booby trap, confirmed on hardware: never send an empty or truncated body
|
||||
> to this endpoint.** On one firmware, a `POST /setMargeAccount` with an
|
||||
> empty body returned `HTTP 200` and cleared `margeAccountUUID`, un-pairing
|
||||
> an already-working speaker
|
||||
> ([#471 comment 5231977172](https://github.com/gesellix/Bose-SoundTouch/issues/471#issuecomment-5231977172)).
|
||||
> A later retry on the same device instead returned `400` and changed
|
||||
> nothing, so the same reporter corrected the finding to
|
||||
> **state-dependent, not a reliable rule you can rely on either way**
|
||||
> ([#471 comment 5232232575](https://github.com/gesellix/Bose-SoundTouch/issues/471#issuecomment-5232232575)). A `400` is not proof the
|
||||
> endpoint rejected a bad request (a booting device also answers a bare
|
||||
> `400` with an empty body before its services are ready, per
|
||||
> `JRpersonal`), and a `200` is not proof it did what you wanted. Practical
|
||||
> takeaway: our own `postSetMargeAccount` always sends a well-formed XML
|
||||
> body, so this doesn't affect the CLI/service — but don't probe this
|
||||
> endpoint by hand against a speaker that currently works.
|
||||
|
||||
### 3.2 Why it's broken in practice
|
||||
|
||||
There are **three independent failure modes** observed:
|
||||
@@ -189,10 +226,16 @@ control:
|
||||
recipes).
|
||||
3. **Randomize.** A "Generate" button that picks a 7-digit number and
|
||||
re-rolls if it collides with an existing account in the local datastore.
|
||||
- **Telnet read-back (best-effort).** `envswitch accountid get` is plausible by
|
||||
symmetry with `envswitch accountid set` (#221) but is not yet confirmed
|
||||
across firmwares. We will probe it during preflight; if it returns a value
|
||||
we cross-check it against `:8090/info` and warn on mismatch.
|
||||
- **Telnet read-back: confirmed unsupported.** `envswitch accountid get` was
|
||||
originally listed as "plausible by symmetry with `envswitch accountid set`
|
||||
(#221), not yet confirmed." It's now confirmed the other way: on
|
||||
`lisa`/`mojo`/`spotty`, `envswitch` has **no read form at all** — both bare
|
||||
`envswitch` and `envswitch boseurls` answer `Invalid Command Option`
|
||||
([#515 comment 5231931569](https://github.com/gesellix/Bose-SoundTouch/issues/515#issuecomment-5231931569)).
|
||||
The persisted layer can only be written, then
|
||||
observed indirectly after a reboot (e.g. via `getpdo`, mindful of the
|
||||
layer-visibility caveat in
|
||||
[TELNET-COMMAND-REFERENCE.md](TELNET-COMMAND-REFERENCE.md)).
|
||||
|
||||
This means the user is never *forced* to invent a number — the common path is
|
||||
"the device already has an ID, reuse it" — and the manual/randomize controls
|
||||
@@ -407,11 +450,14 @@ that `setup.PairAccount` already implements.
|
||||
| ST Portable / FW 27.0.6 | jmosen | #236 | After migration: `POST /marge/streaming/support/power_on` → 502; `<margeAccountUUID/>` empty. Time-bounded HTTP path fails; envswitch fallback succeeds. |
|
||||
| BST20 Portable (factory reset) | ubittner | scheilch/opencloudtouch#167 | `<margeAccountUUID/>` empty; `/setMargeAccount` not in `/supportedURLs`. HTTP path skipped entirely; only the telnet fallback works. |
|
||||
|
||||
### 8.3 Likely to fail (but the failure is clean)
|
||||
### 8.3 Likely to reject the telnet sequence
|
||||
|
||||
Our preflight + abort-on-first-rejection design (`TestMigrateViaTelnet_CommandNotFoundAborts`)
|
||||
means none of these scenarios leave a device half-configured. The user is
|
||||
told what failed and pointed to the XML or DNS method.
|
||||
stops at the first rejected command and reports whether earlier runtime writes
|
||||
or the persistence command may already have applied. A rejection of command #1
|
||||
leaves the URL state untouched; after any later failure, read back all four URL
|
||||
fields before retrying or rebooting. The user is also pointed to the XML or DNS
|
||||
method.
|
||||
|
||||
| Device | Source | Likely cause |
|
||||
|--------------------------------------------|-----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
@@ -439,8 +485,10 @@ negative claim: the author writes "I've made some educated guesses and come
|
||||
up with the following valid commands" and never says they tested
|
||||
`envswitch`. We do not down-weight `envswitch` availability on the strength
|
||||
of S5 alone — but if a real-device run ever shows `envswitch` rejected on
|
||||
an ST 10, our preflight catches it, the migration aborts on the first
|
||||
non-OK response, and the user gets a clear error rather than partial state.
|
||||
an ST 10, the migration aborts on the first unconfirmed response and reports
|
||||
whether runtime writes were confirmed or persistence is uncertain. Because the
|
||||
commands are sequential, the user must read back all four fields before retrying
|
||||
or rebooting.
|
||||
|
||||
### 8.6 Failure-mode matrix
|
||||
|
||||
@@ -449,10 +497,12 @@ What `migrateViaTelnet` does in each failure mode (verified by
|
||||
|
||||
| Failure | Outcome | Test |
|
||||
|------------------------------------------------|---------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------|
|
||||
| Port 17000 closed / TCP unreachable | `Dial` errors before any command is sent; UI shows the error; nothing persisted | `TestMigrateViaTelnet_DialFailureReturnsError` |
|
||||
| `sys configuration` rejected (cmd #1) | Sequence aborts; verification not sent; rest of commands not attempted | `TestMigrateViaTelnet_CommandNotFoundAborts` (envswitch variant — generalises) |
|
||||
| `envswitch boseurls set` rejected | Sequence aborts; runtime-only `sys configuration` state reverts on reboot — no permanent damage | `TestMigrateViaTelnet_CommandNotFoundAborts` |
|
||||
| Verification mismatch (URLs not echoed back) | Loud "verification failed" error; live state may persist until reboot but UI never claims success | `TestMigrateViaTelnet_VerifyMismatchFails` |
|
||||
| Port 17000 closed / TCP unreachable | `Dial` errors before any command is sent; UI shows the error; nothing persisted | `TestMigrateViaTelnet_DialFailureReturnsError` |
|
||||
| `sys configuration` rejected | Sequence aborts; earlier or attempted runtime writes may have applied; read back all four fields | `TestMigrateViaTelnet_GenericRuntimeRejectionReportsPartialState` |
|
||||
| `envswitch boseurls set` rejected | Sequence aborts after four confirmed runtime writes; persistence outcome is uncertain; inspect before rebooting | `TestMigrateViaTelnet_EnvswitchRejectionReportsUncertainPersistence` |
|
||||
| Verification mismatch (URLs not echoed back) | Loud error after accepted `envswitch`; runtime differs and persistence may already have changed; UI never claims success | `TestMigrateViaTelnet_VerifyMismatchFails` |
|
||||
| Invalid or command-unsafe URL input | Rejected before a telnet client is created or any device connection is attempted | `TestMigrateViaTelnet_RejectsUnsafeURLsBeforeCreatingClient` |
|
||||
| Concurrent URL mutations for one speaker | Process-local per-speaker lock keeps command sequences contiguous; different processes remain out of scope | `TestTelnetURLMutationsSameSpeakerAreSerialized` |
|
||||
| `/setMargeAccount` 502 / hang | 5s connect + 12s total budget enforced; falls through to telnet `envswitch accountid set` | `TestPairAccount_FallsBackWhenHTTPReturnsServerError` |
|
||||
| `/setMargeAccount` missing in `/supportedURLs` | HTTP path skipped; goes straight to telnet `envswitch accountid set` | `TestPairAccount_FallsBackWhenSetMargeAccountMissing` |
|
||||
| Both pairing paths unavailable | Structured error: "use the official Bose app before EOS, or open SSH and use the XML method" | `TestPairAccount_NoTelnetAndHTTPMissingReturnsClearError`, `TestPairAccount_TelnetCommandNotFoundReportsBothPaths` |
|
||||
@@ -461,7 +511,7 @@ What `migrateViaTelnet` does in each failure mode (verified by
|
||||
|
||||
- **Green light** — ST 10, ST 20, ST 300, Wave III, Wave IV on FW 27.0.6 (multi-reporter agreement).
|
||||
- **Yellow** — ST Portable and BST20 Portable: migration works, pairing needs our fallback (already implemented).
|
||||
- **Red, but fails cleanly** — SA-5 on FW 9.x, possibly newer ST Portable builds.
|
||||
- **Red, aborts with explicit state diagnostics** — SA-5 on FW 9.x, possibly newer ST Portable builds.
|
||||
- **Unverified but expected to work** — ST 30, ST 520, Wave Music System I/II.
|
||||
|
||||
The most useful next verification step is touching a real ST 30 and ST 520
|
||||
|
||||
@@ -566,7 +566,7 @@ func (m *MockClient) GetNowPlaying() (*models.NowPlaying, error) {
|
||||
|
||||
```dockerfile
|
||||
# test/docker/Dockerfile
|
||||
FROM golang:1.25-alpine
|
||||
FROM golang:1.27.0-alpine
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
|
||||
@@ -101,13 +101,13 @@ rename and network/firmware info.
|
||||
|
||||
---
|
||||
|
||||
## 4. Render stereo pairs as a single device
|
||||
## 4. Stereo-pair presentation and lifecycle (shipped)
|
||||
|
||||
Today soundtouch-player shows the two halves of a stereo pair (formed via
|
||||
`/addGroup` — see issue #252) as independent entries in the device list. The
|
||||
Bose app collapsed a paired ST10 set into one "L+R" entry; restoring that
|
||||
presentation closes the perception gap BirdyBA flagged at
|
||||
<https://github.com/gesellix/Bose-SoundTouch/issues/252#issuecomment-4458140305>.
|
||||
soundtouch-player projects a valid two-speaker stereo pair (formed via
|
||||
`/addGroup` - see [issue #252](https://github.com/gesellix/Bose-SoundTouch/issues/252))
|
||||
as one logical control target. This restores the single-entry presentation
|
||||
expected by users while preserving both physical speakers in the service
|
||||
registry.
|
||||
|
||||
**Device API:**
|
||||
- `GET /getGroup` on each speaker — returns the current `<group>` with
|
||||
@@ -118,28 +118,77 @@ presentation closes the perception gap BirdyBA flagged at
|
||||
side is sufficient to detect the pair
|
||||
|
||||
**Backend:**
|
||||
- During device-list assembly, call `GET /getGroup` for each discovered device
|
||||
in parallel (matches the propagation pattern already used by
|
||||
`soundtouch-cli group create` in `cmd/soundtouch-cli/cmd_group.go`)
|
||||
- Bucket devices by `<masterDeviceId>` — each bucket emits one entry in the
|
||||
list response. Standalone devices stay as their own bucket-of-one
|
||||
- Expose pair metadata on the list entry so the UI can render role chips
|
||||
(`L`/`R`) and resolve role → physical device for actions
|
||||
- Poll `GET /getGroup` together with the other device status and consume
|
||||
`groupUpdated` events. A generation check prevents an older poll from
|
||||
overwriting a newer event.
|
||||
- Collapse only an exact two-member `LEFT`/`RIGHT` group whose registered
|
||||
members agree on the group claim. Malformed, conflicting, or ambiguous data
|
||||
fails open and leaves the physical entries visible.
|
||||
- Use the master speaker's existing registry key for the logical target, so
|
||||
controls continue to route through the master without changing the raw
|
||||
physical-device registry.
|
||||
- Use the same projection for the REST device list and the global player
|
||||
WebSocket snapshot.
|
||||
|
||||
**Frontend:**
|
||||
- Device list collapses paired devices into one card titled with both names
|
||||
(e.g. `"Wohnzimmer L+R"`) and role chips
|
||||
- Clicking the card opens a device-detail page that exposes both per-role
|
||||
status and a "Dissolve pair" action (DELETE flow, already wired in
|
||||
`soundtouch-cli group remove` and in fakespeaker's `/removeGroup` GET)
|
||||
- Standalone speakers continue to render as today
|
||||
- Render one card using the shared member name or the group's name.
|
||||
- Show pair availability as `Stereo pair n/2` and mark the card degraded when
|
||||
a member is unavailable or the group reports a non-OK state.
|
||||
- Hide the single-device remove action on a projected pair. Standalone
|
||||
speakers continue to render as before.
|
||||
- For standalone stereo-capable SoundTouch 10 speakers, offer pair creation
|
||||
with an explicit LEFT/master and RIGHT member.
|
||||
- For an existing pair, offer rename and a separately confirmed dissolve
|
||||
action. A dissolve changes speaker group state; it does not delete either
|
||||
physical speaker from the player registry.
|
||||
|
||||
**Note:** Pair lifecycle (create / rename / remove) already works
|
||||
end-to-end — `pkg/client` group endpoints + `cmd/soundtouch-cli/cmd_group.go`,
|
||||
covered by tests in `cmd/soundtouch-cli/cmd_group_test.go` and exercisable
|
||||
against the fake speaker's group routes
|
||||
(`pkg/service/testing/fakespeaker/fakespeaker.go`). This task is purely about
|
||||
presentation in soundtouch-player's device list — no protocol work required.
|
||||
**Lifecycle safety:**
|
||||
- A shared coordinator backs both the CLI and player. It freshly checks both
|
||||
speakers, their L/R capability, current group, and temporary-zone state
|
||||
before a mutation. Pair creation also requires one shared Marge account and
|
||||
backend.
|
||||
- After both create candidates are freshly verified as physically standalone,
|
||||
a fail-closed, read-only persistence barrier checks for a stored group before
|
||||
either speaker is mutated. The embedded service searches every account by
|
||||
device ID; standalone player and CLI query the speakers' current Marge
|
||||
backend. Creation stops and reports the exact stale generation when any
|
||||
record remains; pre-create checks never delete it.
|
||||
- Create sends the asymmetric master/slave payloads required by the speaker
|
||||
state machines, then freshly verifies that both members agree. A partial
|
||||
create is compensated only where the exact group generation returned by
|
||||
that speaker can be proven.
|
||||
- Rename and dissolve update both physical speakers and report a degraded
|
||||
result, including per-member detail, instead of claiming success after a
|
||||
partial transition.
|
||||
- Rename and dissolve carry the group ID displayed to the user and reject a
|
||||
stale request if either speaker now belongs to another generation.
|
||||
- A degraded dissolve retains the last exact L/R topology for a bounded retry.
|
||||
The retry freshly verifies both physical identities and states, and stored
|
||||
persistence must match that full topology before it can be retired.
|
||||
- Legacy Marge teardown callbacks without a group ID are acknowledged without
|
||||
deleting persistent state. After a verified physical dissolve, the embedded
|
||||
player retires the exact generation directly in its datastore; standalone
|
||||
player and CLI use the generation-aware endpoint derived from fresh speaker
|
||||
info. Physical verification and exact persistence cleanup share one
|
||||
coordinator lock, and a cleanup failure is returned as degraded.
|
||||
- Retired group IDs leave their small XML snapshot in the datastore and
|
||||
active/retired IDs are reserved across all accounts, so an account move or
|
||||
stale request cannot match a later physical generation.
|
||||
- Pair mutations are rejected while either member belongs to a temporary
|
||||
multi-room zone. The zone must be dissolved first.
|
||||
|
||||
!!! warning "Run lifecycle operations site-locally"
|
||||
Marge hostnames such as `unifi` are resolved from the caller's site, not
|
||||
from the speaker's site. Create, rename, and dissolve a pair through the
|
||||
Player/service deployment co-located with both speakers and their Marge
|
||||
backend; a cross-site registry entry is not a backend-routing mechanism.
|
||||
|
||||
!!! warning "Datastore downgrade boundary"
|
||||
Once this lifecycle has written a `Group_<id>.retired` snapshot, do not run an
|
||||
older service binary against the same datastore. Older allocators do not
|
||||
reserve these generation IDs globally and can reuse one. Restore both the
|
||||
binary and its pre-lifecycle datastore snapshot for a rollback, or upgrade
|
||||
forward.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -17,12 +17,17 @@ then **which build** matches your computer.
|
||||
AfterTouch is a small set of separate programs. Most people run one or
|
||||
two of them.
|
||||
|
||||
| Tool | What it does | You want this if… |
|
||||
|----------------------|-----------------------------------------------------------------------------------------------|----------------------------------------------------------|
|
||||
| `soundtouch-service` | The local cloud replacement ("AfterTouch"). Runs always-on and takes over from the Bose cloud. | You are migrating speakers off the Bose cloud. |
|
||||
| `soundtouch-player` | A browser control panel (radio browsing, device control). | You want a web UI to browse radio and control speakers. |
|
||||
| `soundtouch-cli` | Command-line control and setup (status, play, presets, groups, **migration**, …). | You want to script things, or run a migration by hand. |
|
||||
| `soundtouch-backup` | Backs up your Bose cloud account and each speaker's local state. | You are preparing before a shutdown / factory reset. |
|
||||
| Tool | What it does | You want this if… |
|
||||
|----------------------|------------------------------------------------------------------------------------------------|---------------------------------------------------------|
|
||||
| `soundtouch-service` | The local cloud replacement ("AfterTouch"). Runs always-on and takes over from the Bose cloud. | You are migrating speakers off the Bose cloud. |
|
||||
| `soundtouch-cli` | Command-line control and setup (status, play, presets, groups, **migration**, …). | You want to script things, or run a migration by hand. |
|
||||
| `soundtouch-player` | A browser control panel (radio browsing, device control). | You want a web UI to browse radio and control speakers. |
|
||||
| `soundtouch-backup` | Backs up your Bose cloud account and each speaker's local state. | You are preparing before a shutdown / factory reset. |
|
||||
|
||||
Most people only need **`soundtouch-service`** and **`soundtouch-cli`** — the
|
||||
release notes on each [GitHub release](https://github.com/gesellix/Bose-SoundTouch/releases/latest)
|
||||
link those two directly, one row per platform, so you don't have to hunt
|
||||
through the flat Assets list below.
|
||||
|
||||
> Running a migration from the command line (for example the telnet
|
||||
> re-migration in the
|
||||
|
||||
@@ -592,6 +592,9 @@ soundtouch-cli --host <device> account remove-amazon --user <USER>
|
||||
soundtouch-cli --host <device> account remove-deezer --user <USER>
|
||||
soundtouch-cli --host <device> account remove-iheart --user <USER>
|
||||
soundtouch-cli --host <device> account remove-nas --user <GUID/0> [--name <NAME>]
|
||||
|
||||
# Unpair the device from its Marge cloud account entirely
|
||||
soundtouch-cli --host <device> account unpair
|
||||
```
|
||||
|
||||
**Supported Services:**
|
||||
@@ -648,6 +651,11 @@ soundtouch-cli --host 192.0.2.10 account remove \
|
||||
- Network music libraries (STORED_MUSIC) don't require passwords, only the UPnP server GUID
|
||||
- After adding an account, use `source list` to verify it appears as available
|
||||
- Some services may require additional authentication steps through their mobile apps
|
||||
- `account unpair` is different from the above: it sends `UnPairDeviceWithAccount`
|
||||
over the speaker's own local WebSocket to remove its **Marge cloud account**
|
||||
pairing entirely (`margeAccountUUID`), not a single streaming-service login.
|
||||
See `setup revert` for the related "undo a migration" operation, which
|
||||
deliberately does *not* call this — the two are separate steps.
|
||||
|
||||
### Bass Control
|
||||
|
||||
@@ -847,6 +855,48 @@ soundtouch-cli --host 192.0.2.10 zone remove --member 192.0.2.12
|
||||
soundtouch-cli --host 192.0.2.10 zone dissolve
|
||||
```
|
||||
|
||||
### Stereo Pair Management
|
||||
|
||||
Create and manage a persistent LEFT/RIGHT pair of two SoundTouch 10 speakers.
|
||||
This is distinct from a temporary multi-room zone. Both speakers must be
|
||||
online, stereo-capable, standalone, and outside any zone before a lifecycle
|
||||
operation. Pair creation also requires both speakers to use the same Marge
|
||||
backend, though they need not share a Marge account. Run lifecycle commands
|
||||
from the site containing both speakers; site-relative Marge names such as
|
||||
`unifi` do not identify a remote site when resolved by the CLI host.
|
||||
|
||||
```bash
|
||||
# Inspect a standalone speaker or either member of a pair
|
||||
soundtouch-cli --host 192.0.2.10 group status
|
||||
|
||||
# Create a pair; the LEFT speaker becomes the master
|
||||
soundtouch-cli group create \
|
||||
--left 192.0.2.10 \
|
||||
--right 192.0.2.11 \
|
||||
--name "Living Room"
|
||||
|
||||
# Rename through either member
|
||||
soundtouch-cli --host 192.0.2.10 group rename --name "Living Room Pair"
|
||||
|
||||
# Dissolve the pair without removing either speaker from AfterTouch
|
||||
soundtouch-cli --host 192.0.2.10 group remove
|
||||
```
|
||||
|
||||
Create, rename, and remove verify fresh state on both speakers. Rename and
|
||||
remove first inspect the current group and carry its ID as a generation guard;
|
||||
if the pair changes before mutation, the operation fails without touching the
|
||||
newer pair. A partial transition is reported as degraded with per-speaker
|
||||
details rather than as a successful operation. A remove attempt carries the
|
||||
last exact L/R topology, freshly verifies both speakers, and retires
|
||||
persistence only if the stored generation still matches it. Before create,
|
||||
the CLI verifies
|
||||
both speakers as standalone, queries their current Marge backend for stale
|
||||
group records, and refuses to mutate either speaker while any record remains.
|
||||
After verified physical cleanup, the CLI removes the exact group ID through the
|
||||
Marge URL and account freshly read from the speaker. A backend cleanup failure
|
||||
is therefore visible as a degraded result instead of leaving an apparently
|
||||
successful stale generation.
|
||||
|
||||
### Browse and Navigation
|
||||
|
||||
Browse and navigate content sources on your device.
|
||||
@@ -1157,6 +1207,310 @@ soundtouch-cli --host 192.0.2.10 events subscribe --filter zone --no-reconnect
|
||||
- Events are displayed in real-time with emoji indicators
|
||||
- Verbose mode shows additional technical details
|
||||
|
||||
### Update Check
|
||||
|
||||
#### `update-check`
|
||||
|
||||
Check GitHub Releases for a newer `soundtouch-cli` version. Unlike
|
||||
`soundtouch-service`'s periodic background check, this doesn't need a
|
||||
`--host` or any device on the network: it's a single, on-demand GitHub API
|
||||
request. Running the command is itself the opt-in, so there's no config
|
||||
flag or persisted state.
|
||||
|
||||
**Usage:**
|
||||
```bash
|
||||
soundtouch-cli update-check
|
||||
```
|
||||
|
||||
**Example output:**
|
||||
```
|
||||
A newer version is available: v1.3.0 (you're on v1.2.0)
|
||||
https://github.com/gesellix/Bose-SoundTouch/releases/tag/v1.3.0
|
||||
```
|
||||
|
||||
**Notes:**
|
||||
- `soundtouch-backup` has the same `update-check` command.
|
||||
- If the running binary isn't a released version (e.g. a dev build),
|
||||
the command reports that and skips the comparison.
|
||||
|
||||
### Setup & Migration
|
||||
|
||||
The `setup <subcommand>` group provisions a speaker end-to-end: enabling
|
||||
SSH, factory-reset + Wi-Fi re-provisioning, pointing it at AfterTouch, CA
|
||||
trust, account pairing, reverting, and one-shot data sync. Each subcommand
|
||||
wraps an existing `pkg/service/setup` helper directly — there's no separate
|
||||
business logic in the CLI layer. Manual provisioning-loop background:
|
||||
[docs/analysis/SETUP-WEBSOCKET-EXPERIMENT.md](../analysis/SETUP-WEBSOCKET-EXPERIMENT.md)
|
||||
and [Device Initial Setup](DEVICE-INITIAL-SETUP.md).
|
||||
|
||||
#### `setup inspect`
|
||||
|
||||
Non-destructive snapshot of the speaker: identity, pairing state, Wi-Fi,
|
||||
sources, presets, and (with `--telnet`) the runtime URL configuration via
|
||||
`getpdo`. Good first command to run against an unfamiliar speaker.
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <device> setup inspect
|
||||
soundtouch-cli --host <device> setup inspect --telnet # also reads runtime URLs (slower)
|
||||
```
|
||||
|
||||
#### `setup ssh-check`
|
||||
|
||||
Probes whether port 22 is reachable. On failure, prints the `enable-ssh`
|
||||
suggestion and the USB-stick fallback procedure.
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <device> setup ssh-check [--timeout 3s]
|
||||
```
|
||||
|
||||
#### `setup enable-ssh`
|
||||
|
||||
Bootstraps SSH on a speaker with no prior access, via the port-17000
|
||||
`envswitch` trick (#471) — no USB stick needed. Auto-pairs an unpaired
|
||||
(factory-reset) device first by default (the injection needs something to
|
||||
poll), waits for `:22`, and persists the `remote_services` marker so SSH
|
||||
survives a reboot.
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <device> setup enable-ssh
|
||||
soundtouch-cli --host <device> setup enable-ssh --service-url https://192.0.2.10:8443
|
||||
```
|
||||
|
||||
Flags:
|
||||
- `--service-url` — optional; only the vehicle for the injection, no live
|
||||
server required. Set the real URL later via `setup migrate`.
|
||||
- `--wait` (default `90s`) — how long to wait for `:22` after injection.
|
||||
- `--full-config` — for stubborn devices (ST Portable, CineMate 520) where
|
||||
the default injection is accepted but `sshd` never starts: writes all
|
||||
four config URLs (the #515 sequence) and reboots.
|
||||
- `--command-delay` — only affects `--full-config`; pause between its 6
|
||||
steps.
|
||||
- `--no-auto-pair` / `--account` — skip or control the automatic pairing
|
||||
check.
|
||||
- `--no-reset-urls` — skip restoring clean `boseurls` after SSH is up.
|
||||
- `--no-persist` — skip persisting `remote_services` (SSH won't survive a
|
||||
reboot).
|
||||
- `--authorized-key` — opt-in hardening: install an SSH public key instead
|
||||
of relying on the empty-password login.
|
||||
- `--close-17000` — opt-in hardening: firewall off port 17000 from the LAN
|
||||
(loopback access kept).
|
||||
|
||||
#### `setup remote-services`
|
||||
|
||||
Enables (default) or removes the `remote_services` SSH-enablement marker.
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <device> setup remote-services # ensure it's present
|
||||
soundtouch-cli --host <device> setup remote-services --remove # disable SSH after next reboot
|
||||
```
|
||||
|
||||
#### `setup factory-reset`
|
||||
|
||||
Issues `sys factorydefault` over telnet — wipes account, presets, and
|
||||
Wi-Fi, and reboots the speaker into its own setup-mode AP. Prints the next
|
||||
steps (`wait-ap`, then `wifi-push`).
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <device> setup factory-reset
|
||||
```
|
||||
|
||||
> **Heads-up:** just before resetting, the speaker sends
|
||||
> `DELETE /streaming/account/{id}/device/{id}` to whatever `margeURL` is
|
||||
> *currently* configured. If that still points at `streaming.bose.com`
|
||||
> (not AfterTouch), AfterTouch keeps a stale datastore entry — migrate
|
||||
> first if you want a clean record.
|
||||
|
||||
#### `setup wait-ap`
|
||||
|
||||
Polls the speaker's setup-mode AP (default `192.0.2.1`) until `/info`
|
||||
responds, after a factory reset.
|
||||
|
||||
```bash
|
||||
soundtouch-cli setup wait-ap [--ap-host 192.0.2.1] [--interval 2s] [--timeout 5m]
|
||||
```
|
||||
|
||||
#### `setup wifi-push`
|
||||
|
||||
POSTs `AddWirelessProfile` to the speaker's setup-mode endpoint — pushes
|
||||
your home Wi-Fi credentials while connected to the speaker's AP.
|
||||
|
||||
```bash
|
||||
soundtouch-cli setup wifi-push --ssid="YourHomeSSID" --pass='your-password'
|
||||
```
|
||||
|
||||
Flags: `--security` (default `wpa_or_wpa2`), `--ap-host` (default
|
||||
`192.0.2.1`), `--request-timeout` (default `30s` — the speaker can be slow
|
||||
to ACK before tearing down AP mode; 10s often races).
|
||||
|
||||
#### `setup wait-online`
|
||||
|
||||
Polls mDNS until a speaker matching `--match` comes online on the home
|
||||
network — run this after switching back from the speaker's AP.
|
||||
|
||||
```bash
|
||||
soundtouch-cli setup wait-online --match=<last-6-hex-of-deviceID>
|
||||
```
|
||||
|
||||
`--match` is empty by default (first speaker seen); `--interval` (`3s`) and
|
||||
`--timeout` (`5m`) control the poll.
|
||||
|
||||
#### `setup install-ca`
|
||||
|
||||
Fetches AfterTouch's CA cert from `/api/setup/ca.crt` and injects it into
|
||||
the speaker's trust store via SSH.
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <device> setup install-ca --service-url https://192.0.2.10:8443
|
||||
```
|
||||
|
||||
`--auth` (`user:pass`) supplies basic-auth credentials up front; omit it to
|
||||
be prompted interactively if the endpoint returns 401.
|
||||
|
||||
#### `setup migrate`
|
||||
|
||||
Applies a migration method to point the speaker at AfterTouch — the CLI
|
||||
equivalent of the web UI's Migrate tab.
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <device> setup migrate --service-url http://192.0.2.10:8000 --method telnet
|
||||
```
|
||||
|
||||
`--method` is one of `telnet` (default) | `hosts` | `resolv` | `xml`.
|
||||
`--proxy-url` sets an optional upstream proxy (only used by `--method=xml`).
|
||||
`--skip-preflight` skips AfterTouch's settings preflight check (useful when
|
||||
that endpoint is unreachable).
|
||||
|
||||
`--marge-url`/`--stats-url`/`--sw-update-url`/`--bmx-url` override the
|
||||
corresponding field instead of deriving it from `--service-url` (applies to
|
||||
both `--method=telnet` and `--method=xml`). Useful beyond soundcork-style
|
||||
setups: e.g. pointing a speaker back at the **original Bose cloud URLs**
|
||||
without a full `setup revert` — telnet writes both the runtime and
|
||||
persisted layers in a single connection, no SSH or `.original` backup
|
||||
needed:
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <device> setup migrate --method telnet \
|
||||
--service-url https://streaming.bose.com \
|
||||
--marge-url https://streaming.bose.com \
|
||||
--stats-url https://events.api.bosecm.com \
|
||||
--sw-update-url https://worldwide.bose.com/updates/soundtouch \
|
||||
--bmx-url https://content.api.bose.io/bmx/registry/v1/services
|
||||
```
|
||||
|
||||
#### `setup revert`
|
||||
|
||||
Undoes a migration. The default `--method ssh` is the CLI equivalent of the
|
||||
web UI's **Revert to Defaults** button: it restores
|
||||
`SoundTouchSdkPrivateCfg.xml`, `/etc/hosts`, and `/etc/resolv.conf` from their
|
||||
`.original` backups, removes the AfterTouch DNS-hook artifacts, and strips
|
||||
just the AfterTouch-labeled certificate out of the trust bundle.
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <device> setup revert
|
||||
```
|
||||
|
||||
For a telnet-only migration, `--method telnet` restores the four canonical
|
||||
Bose service URLs without requiring SSH or an XML backup:
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <device> setup revert --method telnet
|
||||
```
|
||||
|
||||
This only changes `margeServerUrl`, `statsServerUrl`, `swUpdateUrl`, and
|
||||
`bmxRegistryUrl`. It does not restore filesystem, DNS, CA, SSH, or account
|
||||
state. Reboot the speaker afterwards and verify all four persisted values.
|
||||
The `--marge-url`, `--stats-url`, `--sw-update-url`, and `--bmx-url` flags can
|
||||
override the canonical defaults for firmware- or region-specific values.
|
||||
These flags require `--method telnet`; using them with the default SSH method
|
||||
is an error. Each value must be an absolute HTTP or HTTPS service URL without
|
||||
userinfo, query parameters, fragments, whitespace, control characters, or
|
||||
shell metacharacters.
|
||||
Telnet writes are sequential rather than transactional. If the command reports
|
||||
an error, read back and reconcile all four fields before retrying or rebooting;
|
||||
the error distinguishes a partial runtime update from an uncertain persistence
|
||||
outcome after `envswitch`.
|
||||
|
||||
**Out of scope for this command** (matches the web UI button): SSH /
|
||||
`remote_services` persistence (use `setup remote-services --remove`) and
|
||||
account pairing (use `account unpair`) are untouched — revert them
|
||||
separately if you want a fully clean speaker.
|
||||
|
||||
#### `setup reboot`
|
||||
|
||||
Reboots the speaker — useful to force the envswitch parallel-persistence
|
||||
layer to apply after a migration.
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <device> setup reboot [--method telnet|ssh]
|
||||
```
|
||||
|
||||
`--method` defaults to `telnet`, which works without SSH on modern
|
||||
firmware.
|
||||
|
||||
#### `setup verify`
|
||||
|
||||
Read-only status probe across every migration axis (transports, URL
|
||||
configuration, DNS interception, CA/TLS, pairing) — doubles as a preflight
|
||||
check before applying changes and a verification step afterward. Exits
|
||||
non-zero if nothing reports migrated, so it's usable as a CI gate.
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <device> setup verify --service-url http://192.0.2.10:8000
|
||||
```
|
||||
|
||||
#### `setup plan`
|
||||
|
||||
Recommends the next setup/migration steps based on `inspect` + `verify`
|
||||
state — prints a ready-to-run command for each recommended step.
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <device> setup plan --service-url http://192.0.2.10:8000
|
||||
soundtouch-cli --host <device> setup plan --service-url http://192.0.2.10:8000 --reset # plan a full factory-reset → Wi-Fi → migrate → pair flow
|
||||
```
|
||||
|
||||
`--wifi-ssid` overrides the SSID used for the `wifi-push` step in a reset
|
||||
plan (default: reuse the SSID `inspect` found). `--include-pair` (default
|
||||
`true`) can be disabled if you'll pair manually.
|
||||
|
||||
#### `setup pair`
|
||||
|
||||
Pairs the speaker with an account via the WebSocket `SETUP` state machine
|
||||
(`--mode=full`, matching the Bose app's own flow) or a minimal
|
||||
`setMargeAccount`-only call (`--mode=bare`, the same underlying call the
|
||||
Health tab's "empty margeAccountUUID" QuickFix uses).
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <device> setup pair --mode=full --account=1111111 --service-url http://192.0.2.10:8000
|
||||
soundtouch-cli --host <device> setup pair --mode=bare --account=1111111 --service-url http://192.0.2.10:8000
|
||||
```
|
||||
|
||||
`--account` empty generates a fresh 7-digit ID. `--name` sets the speaker
|
||||
name during pairing (empty keeps current). `--language` defaults to `3`
|
||||
(English). `--token` defaults to a built-in placeholder matching the Bose
|
||||
app's token shape.
|
||||
|
||||
`--mode=full` first reads `/supportedURLs` and `/soundTouchConfigurationStatus`
|
||||
and only runs the state machine when the device reports
|
||||
`SOUNDTOUCH_NOT_CONFIGURED` (see [#615](https://github.com/gesellix/Bose-SoundTouch/issues/615):
|
||||
a speaker can be reachable, named, and already account-paired yet still
|
||||
report `SOUNDTOUCH_NOT_CONFIGURED`, leaving the "install the Bose app"
|
||||
prompt on screen — only a full pass through the state machine clears it).
|
||||
An already-configured device is a no-op; an unsupported route or an
|
||||
unrecognised status value fails the command instead of guessing.
|
||||
|
||||
#### `setup sync`
|
||||
|
||||
Pulls presets, recents, and sources from the speaker into AfterTouch's
|
||||
datastore — the CLI equivalent of the web UI's Devices → Sync Data button.
|
||||
Read-only towards the speaker: it never writes anything back.
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <device> setup sync --service-url http://192.0.2.10:8000
|
||||
```
|
||||
|
||||
`--auth` (`user:pass`) supplies basic-auth credentials up front; omit it to
|
||||
be prompted interactively if the endpoint returns 401.
|
||||
|
||||
## Common Usage Patterns
|
||||
|
||||
### Quick Device Setup
|
||||
|
||||
@@ -115,25 +115,25 @@ type ProductionSoundTouchService struct {
|
||||
type Config struct {
|
||||
// Server settings
|
||||
ListenAddr string `env:"LISTEN_ADDR" default:":8080"`
|
||||
|
||||
|
||||
// SoundTouch settings
|
||||
DeviceHosts []string `env:"DEVICE_HOSTS" separator:","`
|
||||
DiscoveryTimeout time.Duration `env:"DISCOVERY_TIMEOUT" default:"30s"`
|
||||
RequestTimeout time.Duration `env:"REQUEST_TIMEOUT" default:"15s"`
|
||||
MaxRetries int `env:"MAX_RETRIES" default:"3"`
|
||||
|
||||
|
||||
// Connection pool
|
||||
MaxConnections int `env:"MAX_CONNECTIONS" default:"10"`
|
||||
IdleTimeout time.Duration `env:"IDLE_TIMEOUT" default:"5m"`
|
||||
|
||||
|
||||
// Monitoring
|
||||
MetricsEnabled bool `env:"METRICS_ENABLED" default:"true"`
|
||||
HealthCheckInterval time.Duration `env:"HEALTH_CHECK_INTERVAL" default:"30s"`
|
||||
|
||||
|
||||
// Logging
|
||||
LogLevel string `env:"LOG_LEVEL" default:"info"`
|
||||
LogFormat string `env:"LOG_FORMAT" default:"json"`
|
||||
|
||||
|
||||
// Security
|
||||
EnableTLS bool `env:"ENABLE_TLS" default:"false"`
|
||||
TLSCertFile string `env:"TLS_CERT_FILE"`
|
||||
@@ -145,7 +145,7 @@ func LoadConfig() (*Config, error) {
|
||||
if err := env.Parse(cfg); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse config: %w", err)
|
||||
}
|
||||
|
||||
|
||||
return cfg, cfg.Validate()
|
||||
}
|
||||
|
||||
@@ -153,15 +153,15 @@ func (c *Config) Validate() error {
|
||||
if len(c.DeviceHosts) == 0 {
|
||||
return fmt.Errorf("at least one device host must be specified")
|
||||
}
|
||||
|
||||
|
||||
if c.RequestTimeout < time.Second {
|
||||
return fmt.Errorf("request timeout must be at least 1 second")
|
||||
}
|
||||
|
||||
|
||||
if c.EnableTLS && (c.TLSCertFile == "" || c.TLSKeyFile == "") {
|
||||
return fmt.Errorf("TLS cert and key files required when TLS is enabled")
|
||||
}
|
||||
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
@@ -191,7 +191,7 @@ pool:
|
||||
monitoring:
|
||||
metrics_enabled: true
|
||||
health_check_interval: "30s"
|
||||
|
||||
|
||||
logging:
|
||||
level: "info"
|
||||
format: "json"
|
||||
@@ -203,12 +203,12 @@ func LoadConfigFromFile(path string) (*Config, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
var cfg Config
|
||||
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
return &cfg, cfg.Validate()
|
||||
}
|
||||
```
|
||||
@@ -224,14 +224,14 @@ func LoadConfigFromFile(path string) (*Config, error) {
|
||||
type SecureNetworkConfig struct {
|
||||
// Allowed source IP ranges
|
||||
AllowedCIDRs []string
|
||||
|
||||
|
||||
// Rate limiting
|
||||
RateLimit int
|
||||
RateLimitWindow time.Duration
|
||||
|
||||
|
||||
// TLS configuration
|
||||
TLSConfig *tls.Config
|
||||
|
||||
|
||||
// Timeouts for security
|
||||
ReadTimeout time.Duration
|
||||
WriteTimeout time.Duration
|
||||
@@ -240,7 +240,7 @@ type SecureNetworkConfig struct {
|
||||
|
||||
func NewSecureServer(config SecureNetworkConfig) *http.Server {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
|
||||
// Add middleware
|
||||
handler := applyMiddleware(mux,
|
||||
corsMiddleware(),
|
||||
@@ -249,7 +249,7 @@ func NewSecureServer(config SecureNetworkConfig) *http.Server {
|
||||
loggingMiddleware(),
|
||||
metricsMiddleware(),
|
||||
)
|
||||
|
||||
|
||||
return &http.Server{
|
||||
Handler: handler,
|
||||
TLSConfig: config.TLSConfig,
|
||||
@@ -275,12 +275,12 @@ func (r *DeviceControlRequest) Validate() error {
|
||||
if err := validate.Struct(r); err != nil {
|
||||
return fmt.Errorf("validation failed: %w", err)
|
||||
}
|
||||
|
||||
|
||||
// Additional business logic validation
|
||||
if r.Action == "volume" && r.Volume == nil {
|
||||
return fmt.Errorf("volume value required for volume action")
|
||||
}
|
||||
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
@@ -302,12 +302,12 @@ func loadSecretsFromK8s() (*SecretsConfig, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
tlsKey, err := os.ReadFile("/etc/secrets/tls.key")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
return &SecretsConfig{
|
||||
TLSCert: string(tlsCert),
|
||||
TLSKey: string(tlsKey),
|
||||
@@ -335,21 +335,21 @@ type Logger struct {
|
||||
|
||||
func NewLogger(level, format, component string) (*Logger, error) {
|
||||
logger := logrus.New()
|
||||
|
||||
|
||||
// Set level
|
||||
logLevel, err := logrus.ParseLevel(level)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logger.SetLevel(logLevel)
|
||||
|
||||
|
||||
// Set format
|
||||
if format == "json" {
|
||||
logger.SetFormatter(&logrus.JSONFormatter{
|
||||
TimestampFormat: time.RFC3339,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
return &Logger{
|
||||
Logger: logger,
|
||||
component: component,
|
||||
@@ -376,15 +376,15 @@ type Metrics struct {
|
||||
RequestsTotal prometheus.CounterVec
|
||||
RequestDuration prometheus.HistogramVec
|
||||
RequestsInFlight prometheus.GaugeVec
|
||||
|
||||
|
||||
// Device metrics
|
||||
DevicesConnected prometheus.Gauge
|
||||
DeviceHealth prometheus.GaugeVec
|
||||
WebSocketConnections prometheus.Gauge
|
||||
|
||||
|
||||
// Error metrics
|
||||
ErrorsTotal prometheus.CounterVec
|
||||
|
||||
|
||||
// Business metrics
|
||||
VolumeChanges prometheus.CounterVec
|
||||
SourceChanges prometheus.CounterVec
|
||||
@@ -400,7 +400,7 @@ func NewMetrics() *Metrics {
|
||||
},
|
||||
[]string{"method", "endpoint", "status"},
|
||||
),
|
||||
|
||||
|
||||
RequestDuration: *prometheus.NewHistogramVec(
|
||||
prometheus.HistogramOpts{
|
||||
Name: "soundtouch_request_duration_seconds",
|
||||
@@ -409,14 +409,14 @@ func NewMetrics() *Metrics {
|
||||
},
|
||||
[]string{"method", "endpoint"},
|
||||
),
|
||||
|
||||
|
||||
DevicesConnected: prometheus.NewGauge(
|
||||
prometheus.GaugeOpts{
|
||||
Name: "soundtouch_devices_connected",
|
||||
Help: "Number of connected devices",
|
||||
},
|
||||
),
|
||||
|
||||
|
||||
DeviceHealth: *prometheus.NewGaugeVec(
|
||||
prometheus.GaugeOpts{
|
||||
Name: "soundtouch_device_health",
|
||||
@@ -425,7 +425,7 @@ func NewMetrics() *Metrics {
|
||||
[]string{"device_id", "device_name"},
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
// Register metrics
|
||||
prometheus.MustRegister(
|
||||
m.RequestsTotal,
|
||||
@@ -433,7 +433,7 @@ func NewMetrics() *Metrics {
|
||||
m.DevicesConnected,
|
||||
m.DeviceHealth,
|
||||
)
|
||||
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
@@ -457,7 +457,7 @@ type HealthChecker struct {
|
||||
func (hc *HealthChecker) Start(ctx context.Context) {
|
||||
ticker := time.NewTicker(hc.interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -470,7 +470,7 @@ func (hc *HealthChecker) Start(ctx context.Context) {
|
||||
|
||||
func (hc *HealthChecker) checkAllDevices() {
|
||||
var wg sync.WaitGroup
|
||||
|
||||
|
||||
for deviceID, device := range hc.manager.devices {
|
||||
wg.Add(1)
|
||||
go func(id string, dev *DeviceInfo) {
|
||||
@@ -478,18 +478,18 @@ func (hc *HealthChecker) checkAllDevices() {
|
||||
hc.checkDevice(id, dev)
|
||||
}(deviceID, device)
|
||||
}
|
||||
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (hc *HealthChecker) checkDevice(deviceID string, device *DeviceInfo) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), hc.timeout)
|
||||
defer cancel()
|
||||
|
||||
|
||||
start := time.Now()
|
||||
err := device.Client.Ping()
|
||||
duration := time.Since(start)
|
||||
|
||||
|
||||
if err != nil {
|
||||
device.Status = DeviceStatusUnhealthy
|
||||
hc.metrics.DeviceHealth.WithLabelValues(deviceID, device.Name).Set(0)
|
||||
@@ -507,14 +507,14 @@ func (hc *HealthChecker) HealthHandler() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
healthy := 0
|
||||
total := 0
|
||||
|
||||
|
||||
for _, device := range hc.manager.devices {
|
||||
total++
|
||||
if device.Status == DeviceStatusHealthy {
|
||||
healthy++
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
status := map[string]interface{}{
|
||||
"status": "ok",
|
||||
"devices": map[string]interface{}{
|
||||
@@ -524,14 +524,14 @@ func (hc *HealthChecker) HealthHandler() http.HandlerFunc {
|
||||
},
|
||||
"timestamp": time.Now().UTC(),
|
||||
}
|
||||
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
|
||||
if healthy < total {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
status["status"] = "degraded"
|
||||
}
|
||||
|
||||
|
||||
json.NewEncoder(w).Encode(status)
|
||||
}
|
||||
}
|
||||
@@ -560,16 +560,16 @@ func NewConnectionPool(maxIdle, maxActive int, idleTimeout time.Duration) *Conne
|
||||
maxActive: maxActive,
|
||||
idleTimeout: idleTimeout,
|
||||
}
|
||||
|
||||
|
||||
// Start cleanup goroutine
|
||||
go cp.cleanup()
|
||||
|
||||
|
||||
return cp
|
||||
}
|
||||
|
||||
func (cp *ConnectionPool) Get(host string, port int) (*client.Client, error) {
|
||||
key := fmt.Sprintf("%s:%d", host, port)
|
||||
|
||||
|
||||
// Check if connection exists and is valid
|
||||
if val, ok := cp.clients.Load(key); ok {
|
||||
conn := val.(*pooledConnection)
|
||||
@@ -580,35 +580,35 @@ func (cp *ConnectionPool) Get(host string, port int) (*client.Client, error) {
|
||||
// Connection expired, remove it
|
||||
cp.clients.Delete(key)
|
||||
}
|
||||
|
||||
|
||||
// Check active connection limit
|
||||
if atomic.LoadInt64(&cp.activeCount) >= int64(cp.maxActive) {
|
||||
return nil, fmt.Errorf("connection pool exhausted")
|
||||
}
|
||||
|
||||
|
||||
// Create new connection
|
||||
config := client.ClientConfig{
|
||||
Host: host,
|
||||
Port: port,
|
||||
Timeout: 15 * time.Second,
|
||||
}
|
||||
|
||||
|
||||
newClient := client.NewClient(config)
|
||||
|
||||
|
||||
// Test connection
|
||||
if err := newClient.Ping(); err != nil {
|
||||
return nil, fmt.Errorf("failed to connect to %s:%d: %w", host, port, err)
|
||||
}
|
||||
|
||||
|
||||
conn := &pooledConnection{
|
||||
client: newClient,
|
||||
lastUsed: time.Now(),
|
||||
created: time.Now(),
|
||||
}
|
||||
|
||||
|
||||
cp.clients.Store(key, conn)
|
||||
atomic.AddInt64(&cp.activeCount, 1)
|
||||
|
||||
|
||||
return newClient, nil
|
||||
}
|
||||
|
||||
@@ -621,7 +621,7 @@ type pooledConnection struct {
|
||||
func (cp *ConnectionPool) cleanup() {
|
||||
ticker := time.NewTicker(cp.idleTimeout / 2)
|
||||
defer ticker.Stop()
|
||||
|
||||
|
||||
for range ticker.C {
|
||||
now := time.Now()
|
||||
cp.clients.Range(func(key, val interface{}) bool {
|
||||
@@ -649,10 +649,10 @@ func NewCacheManager() *CacheManager {
|
||||
return &CacheManager{
|
||||
// Device info rarely changes, cache for 1 hour
|
||||
deviceInfoCache: cache.New(1*time.Hour, 2*time.Hour),
|
||||
|
||||
|
||||
// Capabilities never change, cache for 24 hours
|
||||
capabilitiesCache: cache.New(24*time.Hour, 48*time.Hour),
|
||||
|
||||
|
||||
// Volume changes frequently, cache for 5 seconds
|
||||
volumeCache: cache.New(5*time.Second, 10*time.Second),
|
||||
}
|
||||
@@ -662,12 +662,12 @@ func (cm *CacheManager) GetDeviceInfo(deviceID string, fetcher func() (*models.D
|
||||
if cached, found := cm.deviceInfoCache.Get(deviceID); found {
|
||||
return cached.(*models.DeviceInfo), nil
|
||||
}
|
||||
|
||||
|
||||
info, err := fetcher()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
cm.deviceInfoCache.Set(deviceID, info, cache.DefaultExpiration)
|
||||
return info, nil
|
||||
}
|
||||
@@ -702,7 +702,7 @@ func NewResilientSoundTouchService(client *client.Client) *ResilientSoundTouchSe
|
||||
log.Printf("Circuit breaker '%s' changed from '%s' to '%s'", name, from, to)
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
return &ResilientSoundTouchService{
|
||||
client: client,
|
||||
cb: gobreaker.NewCircuitBreaker(settings),
|
||||
@@ -713,12 +713,12 @@ func (r *ResilientSoundTouchService) SetVolume(deviceID string, volume int) erro
|
||||
result, err := r.cb.Execute(func() (interface{}, error) {
|
||||
return nil, r.client.SetVolume(volume)
|
||||
})
|
||||
|
||||
|
||||
if err != nil {
|
||||
r.metrics.ErrorsTotal.WithLabelValues("circuit_breaker", "volume").Inc()
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
return result.(error)
|
||||
}
|
||||
```
|
||||
@@ -730,16 +730,16 @@ func (app *Application) Run(ctx context.Context) error {
|
||||
// Setup signal handling
|
||||
sigChan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
|
||||
// Start services
|
||||
g, ctx := errgroup.WithContext(ctx)
|
||||
|
||||
|
||||
// HTTP server
|
||||
server := &http.Server{
|
||||
Addr: app.config.ListenAddr,
|
||||
Handler: app.handler,
|
||||
}
|
||||
|
||||
|
||||
g.Go(func() error {
|
||||
app.logger.Info("Starting HTTP server", "addr", app.config.ListenAddr)
|
||||
if err := server.ListenAndServe(); err != http.ErrServerClosed {
|
||||
@@ -747,38 +747,38 @@ func (app *Application) Run(ctx context.Context) error {
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
|
||||
// Health checker
|
||||
g.Go(func() error {
|
||||
return app.healthChecker.Start(ctx)
|
||||
})
|
||||
|
||||
|
||||
// WebSocket manager
|
||||
g.Go(func() error {
|
||||
return app.wsManager.Start(ctx)
|
||||
})
|
||||
|
||||
|
||||
// Wait for shutdown signal
|
||||
go func() {
|
||||
<-sigChan
|
||||
app.logger.Info("Shutdown signal received")
|
||||
|
||||
|
||||
// Graceful shutdown with timeout
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
|
||||
// Shutdown HTTP server
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
app.logger.Error("HTTP server shutdown error", "error", err)
|
||||
}
|
||||
|
||||
|
||||
// Close WebSocket connections
|
||||
app.wsManager.Shutdown(shutdownCtx)
|
||||
|
||||
|
||||
// Close connection pool
|
||||
app.connectionPool.Close()
|
||||
}()
|
||||
|
||||
|
||||
return g.Wait()
|
||||
}
|
||||
```
|
||||
@@ -791,7 +791,7 @@ func (app *Application) Run(ctx context.Context) error {
|
||||
|
||||
```dockerfile
|
||||
# Dockerfile
|
||||
FROM golang:1.25-alpine AS builder
|
||||
FROM golang:1.27.0-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY go.mod go.sum ./
|
||||
@@ -830,7 +830,7 @@ services:
|
||||
networks:
|
||||
- soundtouch-net
|
||||
restart: unless-stopped
|
||||
|
||||
|
||||
prometheus:
|
||||
image: prom/prometheus:latest
|
||||
ports:
|
||||
@@ -839,7 +839,7 @@ services:
|
||||
- ./prometheus.yml:/etc/prometheus/prometheus.yml
|
||||
networks:
|
||||
- soundtouch-net
|
||||
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:latest
|
||||
ports:
|
||||
@@ -1011,7 +1011,7 @@ groups:
|
||||
annotations:
|
||||
summary: "SoundTouch device {{ $labels.device_name }} is unhealthy"
|
||||
description: "Device {{ $labels.device_id }} has been unhealthy for more than 2 minutes"
|
||||
|
||||
|
||||
- alert: HighErrorRate
|
||||
expr: rate(soundtouch_errors_total[5m]) > 0.1
|
||||
for: 5m
|
||||
@@ -1020,7 +1020,7 @@ groups:
|
||||
annotations:
|
||||
summary: "High error rate detected"
|
||||
description: "Error rate is {{ $value }} errors/second over the last 5 minutes"
|
||||
|
||||
|
||||
- alert: ServiceDown
|
||||
expr: up{job="soundtouch"} == 0
|
||||
for: 1m
|
||||
@@ -1040,33 +1040,33 @@ func (m *Manager) BackupConfigurations() error {
|
||||
Timestamp: time.Now(),
|
||||
Devices: make(map[string]DeviceConfig),
|
||||
}
|
||||
|
||||
|
||||
for deviceID, device := range m.devices {
|
||||
config := DeviceConfig{}
|
||||
|
||||
|
||||
// Backup presets
|
||||
if presets, err := device.Client.GetPresets(); err == nil {
|
||||
config.Presets = presets
|
||||
}
|
||||
|
||||
|
||||
// Backup settings
|
||||
if volume, err := device.Client.GetVolume(); err == nil {
|
||||
config.Volume = volume.TargetVolume
|
||||
}
|
||||
|
||||
|
||||
if bass, err := device.Client.GetBass(); err == nil {
|
||||
config.Bass = bass.TargetBass
|
||||
}
|
||||
|
||||
|
||||
backup.Devices[deviceID] = config
|
||||
}
|
||||
|
||||
|
||||
// Save to file
|
||||
data, err := json.MarshalIndent(backup, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
filename := fmt.Sprintf("backup_%s.json", time.Now().Format("2006-01-02_15-04-05"))
|
||||
return os.WriteFile(filepath.Join(m.config.BackupDir, filename), data, 0644)
|
||||
}
|
||||
@@ -1083,7 +1083,7 @@ func init() {
|
||||
runtime.GOMAXPROCS(int(limit))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Set GC target percentage
|
||||
if os.Getenv("GOGC") == "" {
|
||||
debug.SetGCPerc
|
||||
|
||||
@@ -99,18 +99,28 @@ After factory restore the speaker enters setup mode automatically; no power-cycl
|
||||
|
||||
## 6. AP Mode Wi-Fi Provisioning via Console
|
||||
|
||||
When BLE is unavailable (e.g. when using an Android emulator), use AP mode to push Wi-Fi credentials from the Mac command line.
|
||||
When BLE is unavailable (e.g. when using an Android emulator), use AP mode to push Wi-Fi credentials from the command line. The HTTP steps below (6.2, 6.3) are OS-agnostic; only the Wi-Fi-network-switching commands (6.1, 6.4) are platform-specific — macOS is shown inline, with Linux and Windows equivalents alongside.
|
||||
|
||||
### 6.1 Connect Mac to Speaker AP
|
||||
### 6.1 Connect your machine to the Speaker AP
|
||||
|
||||
After factory reset the speaker broadcasts an SSID like `Bose SoundTouch XXXX`. Connect the Mac to it:
|
||||
After factory reset the speaker broadcasts an SSID like `Bose SoundTouch XXXX`. Connect to it:
|
||||
|
||||
```bash
|
||||
# List nearby SSIDs — use System Settings → Wi-Fi (the airport command was removed in macOS Sequoia+)
|
||||
# Connect (replace with actual SSID)
|
||||
# macOS — list nearby SSIDs via System Settings → Wi-Fi (the `airport`
|
||||
# command was removed in macOS Sequoia+); connect (replace with actual SSID):
|
||||
networksetup -setairportnetwork en0 "Bose SoundTouch XXXX"
|
||||
```
|
||||
|
||||
```bash
|
||||
# Linux (NetworkManager) — one-shot connect, no password (open AP):
|
||||
nmcli device wifi connect "Bose SoundTouch XXXX"
|
||||
```
|
||||
|
||||
```powershell
|
||||
# Windows — connect via the built-in Wi-Fi menu, or from PowerShell:
|
||||
netsh wlan connect name="Bose SoundTouch XXXX"
|
||||
```
|
||||
|
||||
The speaker's web UI gateway is at `192.0.2.1` (verified: ST10 assigns `192.0.2.2` to the client via DHCP).
|
||||
|
||||
```bash
|
||||
@@ -143,20 +153,37 @@ Expected response: `<?xml version="1.0" encoding="UTF-8" ?><AddWirelessProfileRe
|
||||
|
||||
The speaker will disconnect from AP mode and join the home network within ~15–30 s.
|
||||
|
||||
### 6.4 Reconnect Mac to Home Network
|
||||
### 6.4 Reconnect to your Home Network
|
||||
|
||||
```bash
|
||||
# macOS
|
||||
networksetup -setairportnetwork en0 "MyHomeNetwork" "MyPassword"
|
||||
```
|
||||
|
||||
```bash
|
||||
# Linux (NetworkManager) — assumes the connection profile already exists
|
||||
# (e.g. from a prior manual connect); use `nmcli device wifi connect
|
||||
# "MyHomeNetwork" password "MyPassword"` instead for a first-time connect.
|
||||
nmcli connection up "MyHomeNetwork"
|
||||
```
|
||||
|
||||
```powershell
|
||||
# Windows
|
||||
netsh wlan connect name="MyHomeNetwork"
|
||||
```
|
||||
|
||||
Wait ~15 s for the speaker to join the home network, then verify:
|
||||
|
||||
```bash
|
||||
# Discover the speaker's new IP via mDNS
|
||||
dns-sd -B _soundtouch._tcp local &
|
||||
sleep 5 ; kill %1
|
||||
# macOS/Linux — discover the speaker's new IP via mDNS.
|
||||
# macOS: dns-sd ships with the OS. Linux: use avahi-browse (avahi-utils package).
|
||||
dns-sd -B _soundtouch._tcp local & # macOS
|
||||
avahi-browse -r _soundtouch._tcp # Linux — Ctrl-C to stop
|
||||
sleep 5 ; kill %1 2>/dev/null # only needed for the dns-sd form
|
||||
```
|
||||
|
||||
Windows has no equivalent built-in mDNS browser; use `soundtouch-cli discover devices` (this repo's own mDNS/UPnP discovery, cross-platform) or check your router's DHCP client list instead.
|
||||
|
||||
---
|
||||
|
||||
## Comparison: Initial Setup vs. Migration
|
||||
|
||||
@@ -40,7 +40,7 @@ systemd unit that starts on boot.
|
||||
To pin a specific version instead of the latest:
|
||||
|
||||
```bash
|
||||
sudo bash install.sh v0.111.3
|
||||
sudo bash install.sh v0.123.0
|
||||
```
|
||||
|
||||
Check that the service is running:
|
||||
@@ -278,7 +278,7 @@ curl -s http://192.0.2.1:8090/presets
|
||||
|
||||
```bash
|
||||
sudo bash install.sh # updates to latest release
|
||||
sudo bash install.sh v0.111.3 # updates to a specific version
|
||||
sudo bash install.sh v0.123.0 # updates to a specific version
|
||||
```
|
||||
|
||||
The installer stops the service, downloads the new binary, and restarts
|
||||
|
||||
@@ -107,6 +107,10 @@ Open `http://<server>:8000` and go to the **Settings** tab.
|
||||
|
||||
Set the **Target Domain** to the address your speakers can reach — for example `https://soundtouch.fritz.box` or `http://192.0.2.100:8000`. This must be the host's address on your local network, not `localhost`.
|
||||
|
||||
> **Changing this later?** Saving Settings only updates AfterTouch's own record of its address — it does **not** reach out to any already-migrated speaker. Each speaker only learns a new address when you (re-)run Migrate for it (Step 5 below), regardless of migration method. If you change Target Domain after some speakers are already migrated, re-migrate each of them too, or they'll keep using whatever address they were originally migrated with. See [Troubleshooting: Changing Target Domain doesn't change what a speaker actually uses](TROUBLESHOOTING.md#settings-vs-migrate).
|
||||
|
||||
> **On-device install:** this "not `localhost`" rule is for the local-network-host and cloud/VPS scenarios above, where the service runs on a *different* machine than the speaker. If you're running AfterTouch directly on the speaker itself (see the [On-Device Install Walkthrough](ON-DEVICE-INSTALL-WALKTHROUGH.md)), the speaker and the service are the same machine — `http://localhost:8000` is exactly right there, and is the recommended value: it needs no DNS/mDNS to resolve and survives DHCP address changes since it never depends on the LAN address at all. Installs built after issue #546's fix set this automatically (via `DEPLOYMENT_MODE=on-device`); on older installs, or if the field still shows the speaker's own unresolvable Linux hostname (e.g. `http://spotty:8000`), set it here by hand.
|
||||
|
||||
If you plan to use DNS/DHCP redirect, enable the **DNS Discovery Server** and set the **DNS Bind Address** to `:53`. The upstream DNS should be your router's IP, not the service's own address.
|
||||
|
||||
> **Tip**: If you change settings and they don't seem to take effect, check `data/settings.json` — settings saved in the UI take precedence over environment variables.
|
||||
@@ -127,6 +131,14 @@ The XML migration writes updated configuration to the speaker's filesystem, whic
|
||||
4. Power-cycle the speaker (unplug the power cable, wait 10 seconds, reconnect).
|
||||
5. After boot, root SSH is available with no password: `ssh -oHostKeyAlgorithms=+ssh-rsa root@<SPEAKER-IP>`
|
||||
|
||||
**Or, without a USB stick:** `soundtouch-cli setup enable-ssh` (#471) bootstraps SSH purely over the network, using the speaker's telnet:17000 diagnostic shell (open by default on most firmware) to inject the SSH-enable command:
|
||||
|
||||
```shell
|
||||
soundtouch-cli --host <SPEAKER-IP> setup enable-ssh
|
||||
```
|
||||
|
||||
It waits for `:22` to come up and persists the change (survives a reboot) by default. Falls back to the USB-stick method above if telnet:17000 is closed or the injection doesn't take on your model.
|
||||
|
||||
You only need to do this once per speaker. SSH can remain enabled for future maintenance or be disabled after migration — your choice.
|
||||
|
||||
**To disable SSH after migration:**
|
||||
@@ -162,6 +174,20 @@ Once the speaker appears, click **Sync Data**. This connects to the speaker and
|
||||
|
||||
Sync pulls the speaker's local state into AfterTouch's datastore, creating an off-device backup of its configuration. If you ran this before May 6, 2026, your account data from Bose's servers was also captured at that time.
|
||||
|
||||
Migration is refused until the service has a valid snapshot for that exact
|
||||
account and device and verifies that its rendered account data preserves every
|
||||
live preset slot. If the migration page asks for Data Sync, sync the device and
|
||||
retry instead of bypassing the check.
|
||||
|
||||
If the account already contains other devices, migration proceeds but the log
|
||||
says so. Some speaker firmware has been reported to wipe its presets after a
|
||||
reboot-triggered resync of a shared account even when `/full` contains the
|
||||
correct data (see issue #614, where the root cause is still open). One account
|
||||
holding every speaker in the household is the normal arrangement, so this is a
|
||||
warning rather than a refusal; if you do hit the preset wipe, moving that
|
||||
speaker to a dedicated account and running Data Sync for it is the known
|
||||
workaround.
|
||||
|
||||
---
|
||||
|
||||
## Step 5: Migrate
|
||||
@@ -319,7 +345,7 @@ The wizard is still the recommended path for a one-off migration of an existing
|
||||
If you need to undo a migration:
|
||||
|
||||
- **From the web UI**: Use the **Revert to Defaults** action on the device — this restores the `.original` backup files created on the speaker during the XML migration.
|
||||
- **Telnet-only migrations**: the wizard writes both the runtime configuration layer (`sys configuration …`) and the persistent layer (`envswitch boseurls set …`) so the migration survives reboot. If you want to revert quickly, the cleanest path is to re-run the wizard with the original Bose URLs in the URL editor.
|
||||
- **Telnet-only migrations**: the wizard writes both the runtime configuration layer (`sys configuration …`) and the persistent layer (`envswitch boseurls set …`) so the migration survives reboot. Use **Restore Bose URLs via Telnet** in the web UI or run `soundtouch-cli --host <device> setup revert --method telnet`. This restores only the four canonical Bose URL fields; use the CLI URL override flags if your original firmware- or region-specific values differ. The web action is offered whenever the live telnet configuration contains a non-canonical URL, including a URL for an older AfterTouch backend.
|
||||
- **Via SSH**: The original XML config is backed up on the speaker with a `.original` suffix. Restore it manually if the UI is unreachable.
|
||||
- **Factory reset**: As a last resort, perform a factory reset (see [Device Initial Setup](DEVICE-INITIAL-SETUP.md) for button sequences). This wipes all configuration and returns the speaker to out-of-box state.
|
||||
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
---
|
||||
title: "Migration & Safety Guide"
|
||||
---
|
||||
Starting a migration on real hardware requires a "Safety First" approach. This guide outlines the safety features implemented in the `soundtouch-service` and provides a checklist for a successful migration.
|
||||
Starting a migration on real hardware requires a "Safety First" approach. This guide outlines the safety features implemented in the `soundtouch-service` and provides a checklist for a successful migration. The available safeguards depend on the migration method: SSH-backed methods can preserve files, while telnet-only URL migration is sequential and creates no filesystem backup.
|
||||
|
||||
#### 🛠 Technical Safety Enhancements
|
||||
|
||||
The following features are built into the `soundtouch-service` to ensure stability and easy rollbacks:
|
||||
|
||||
1. **Off-Device Backups**: Before any migration starts, the service automatically fetches the original `SoundTouchSdkPrivateCfg.xml` and `/etc/hosts` from your speaker and saves them locally in your `data/default/devices/<SERIAL>/` directory. This ensures you have a recovery path even if the speaker's filesystem becomes inaccessible.
|
||||
2. **Pre-flight Write Verification**: The migration process includes a mandatory check for SSH write access (`rw`) before attempting any modifications. This prevents "half-baked" migrations where a script might fail halfway through due to a read-only filesystem.
|
||||
1. **Off-Device Backups**: Before an SSH-backed migration starts, the service fetches the original `SoundTouchSdkPrivateCfg.xml` and `/etc/hosts` from your speaker and saves them locally in your `data/default/devices/<SERIAL>/` directory. This ensures you have a recovery path even if the speaker's filesystem becomes inaccessible. Telnet-only migration does not create these files.
|
||||
2. **Pre-flight Write Verification**: SSH-backed migration checks for write access (`rw`) before modifying files. Telnet migration instead checks each command response and reads back all four runtime URL fields; its writes remain sequential rather than atomic.
|
||||
3. **Automatic Safety on Sync**: Running a "Sync" in the Web UI or CLI automatically triggers an off-device backup, making it the perfect first step for any new device discovery.
|
||||
|
||||
#### 📋 Professional Migration Checklist
|
||||
|
||||
Before you proceed with the actual migration, follow these steps:
|
||||
|
||||
1. **Enable SSH Access (Prerequisite)**: This toolkit requires SSH access to your speakers, which is not enabled by default.
|
||||
1. **Enable SSH Access (SSH-backed methods only)**: SSH is not enabled by default. Skip this step for a telnet-only URL migration.
|
||||
- Create a file named `remote_services` on a FAT-formatted USB drive. The drive may need its bootable flag set — see [SoundCork issue #172](https://github.com/deborahgu/soundcork/issues/172) for details.
|
||||
- Insert the USB stick into the SoundTouch speaker's **SERVICE** port.
|
||||
- Reboot the speaker (unplug and replug).
|
||||
@@ -25,14 +25,15 @@ Before you proceed with the actual migration, follow these steps:
|
||||
3. **Initial Discovery & Sync**:
|
||||
- Run `soundtouch-cli discover devices` to ensure connectivity.
|
||||
- Use the Web UI or CLI to "Sync" the device. This will automatically backup your presets and system configuration files to your local server.
|
||||
4. **Validate SSH Access**: Confirm the device responds to SSH without a password.
|
||||
4. **Validate SSH Access (SSH-backed methods only)**: Confirm the device responds to SSH without a password.
|
||||
- In the Web UI **Migration** tab, select your speaker and verify that the "SSH Connection" status shows ✅ Success.
|
||||
- This toolkit automatically handles the necessary SSH parameters (ciphers and key exchanges) required by older Bose firmware.
|
||||
5. **Migration Methods**:
|
||||
- **XML redirect (default)**: Uploads a config file to the speaker via the Web API. Less invasive — only changes the application-level service URLs. Best for testing or single-device migration.
|
||||
- **Telnet URL redirect**: Writes the four service URLs through the port-17000 diagnostic shell without SSH. The commands are sequential, so a failed run can leave partial runtime state and must be inspected before retry or reboot.
|
||||
- **DNS/DHCP redirect**: Configures the speaker to use a custom DNS server that resolves Bose hostnames to the local service. Best for all-device coverage; requires the AfterTouch DNS server running on port 53. The service includes a pre-flight check before applying this method.
|
||||
|
||||
The web UI walks you through both methods. Both require the CA certificate to be trusted on the speaker for HTTPS to work — the web UI handles this as part of the migration flow.
|
||||
The web UI walks you through the available methods. When the target uses HTTPS, its CA certificate must be trusted on the speaker; the web UI handles this as part of the migration flow.
|
||||
6. **Monitor Logs**: Run the `soundtouch-service` with `DEBUG` or `INFO` logging to see the step-by-step progress of the migration.
|
||||
|
||||
#### 🔄 Rollback Strategy
|
||||
@@ -40,6 +41,8 @@ Before you proceed with the actual migration, follow these steps:
|
||||
If something goes wrong or you want to return to the original Bose cloud services:
|
||||
|
||||
* **Standard Revert**: Use the "Revert Migration" button in the Web UI or the corresponding CLI command. This restores the `.original` files created on the device.
|
||||
* **Telnet URL Restore**: A telnet-only migration creates no filesystem backup. Use **Restore Bose URLs via Telnet** or `setup revert --method telnet` to restore the four canonical Bose URL fields, then reboot and verify them. This does not restore DNS, CA, SSH, account, or filesystem state; pass explicit URL overrides when the device's original values differ from the canonical defaults. If any command fails, read back and reconcile all four fields before rebooting because earlier runtime writes or the `envswitch` persistence commit may already have taken effect.
|
||||
* **Concurrent Telnet Operations**: The service keeps URL-changing telnet sequences and telnet reboot operations contiguous per speaker. This process-local serialization prevents two HTTP requests from interleaving commands, but it cannot coordinate a separate CLI process or another service instance and does not make the device's multi-command update transactional.
|
||||
* **Emergency Recovery**: If the device is unreachable via the UI but SSH still works, you can manually restore the files from your local `data/` directory using `scp` or the backups created on-device (`.original`).
|
||||
* **Factory Reset**: As a last resort, Bose SoundTouch devices can be factory reset (usually by holding '1' and 'Volume Down' while plugging in). This will wipe all settings and return the device to the stock firmware configuration (the firmware itself remains at the current version, but configurations are reset).
|
||||
|
||||
|
||||
@@ -14,7 +14,9 @@ documenting a successful fresh installation on a SoundTouch 20 Series I.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- SSH enabled on the speaker (the usual "Stick with remote_services" procedure).
|
||||
- SSH enabled on the speaker — either the usual "USB stick with
|
||||
`remote_services`" procedure, or `soundtouch-cli setup enable-ssh`
|
||||
(no stick needed, see Step 1).
|
||||
- Your machine can reach the speaker on the LAN.
|
||||
- The speaker's LAN IP address — replace `192.0.2.1` throughout with the
|
||||
actual address shown in your router or `arp -a`.
|
||||
@@ -29,6 +31,23 @@ documenting a successful fresh installation on a SoundTouch 20 Series I.
|
||||
|
||||
## Step 1 — Connect to the speaker via SSH
|
||||
|
||||
If SSH isn't enabled yet, you don't need a USB stick: `soundtouch-cli` can
|
||||
bootstrap it purely over the network (#471), using the speaker's
|
||||
telnet:17000 diagnostic shell (open by default on most firmware) to inject
|
||||
the SSH-enable command:
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host 192.0.2.1 setup enable-ssh
|
||||
```
|
||||
|
||||
This waits for `:22` to come up and persists it (survives a reboot) by
|
||||
default. The USB-stick method (format FAT32, create an empty
|
||||
`remote_services` file in its root, insert, power-cycle) still works as a
|
||||
fallback if telnet:17000 is closed or the injection doesn't take on your
|
||||
model.
|
||||
|
||||
Either way, connect the same way:
|
||||
|
||||
```bash
|
||||
ssh -oHostKeyAlgorithms=+ssh-rsa root@192.0.2.1
|
||||
```
|
||||
@@ -65,7 +84,7 @@ rm -f /mnt/nv/aftertouch/soundtouch-cli
|
||||
df -h /mnt/nv # confirm space recovered
|
||||
```
|
||||
|
||||
> **From v0.89.0 onwards the installer prunes stale artefacts automatically**
|
||||
> **From v0.93.0 onwards the installer prunes stale artefacts automatically**
|
||||
> during every upgrade — manual cleanup should no longer be necessary on
|
||||
> fresh installs.
|
||||
|
||||
@@ -85,11 +104,14 @@ By default this installs the **latest release** — the script resolves it from
|
||||
GitHub's `releases/latest` redirect. To target a specific version instead:
|
||||
|
||||
```bash
|
||||
# Via environment variable (works with pipe-to-sh)
|
||||
VERSION=0.111.3 rw && curl -sSL https://raw.githubusercontent.com/gesellix/Bose-SoundTouch/main/scripts/on-device-install/install.sh | sh
|
||||
# Via environment variable — note it goes on `sh`, not `curl`: shell
|
||||
# variable-assignment prefixes only apply to the one command they're
|
||||
# attached to, and in a pipe each command is a separate process.
|
||||
# `VERSION=0.123.0 curl ... | sh` silently does NOT set it for `sh`.
|
||||
rw && curl -sSL https://raw.githubusercontent.com/gesellix/Bose-SoundTouch/main/scripts/on-device-install/install.sh | VERSION=0.123.0 sh
|
||||
|
||||
# Via command-line flag (pass args after sh -s --)
|
||||
curl -sSL https://raw.githubusercontent.com/gesellix/Bose-SoundTouch/main/scripts/on-device-install/install.sh | sh -s -- --version 0.111.3
|
||||
curl -sSL https://raw.githubusercontent.com/gesellix/Bose-SoundTouch/main/scripts/on-device-install/install.sh | sh -s -- --version 0.123.0
|
||||
```
|
||||
|
||||
Verify the installed version:
|
||||
@@ -98,7 +120,7 @@ Verify the installed version:
|
||||
wget -qO- http://localhost:8000/health
|
||||
```
|
||||
|
||||
The JSON response should include `"version":"v0.111.3"` (or whichever
|
||||
The JSON response should include `"version":"v0.123.0"` (or whichever
|
||||
version you installed).
|
||||
|
||||
---
|
||||
@@ -131,13 +153,69 @@ ssh -oHostKeyAlgorithms=+ssh-rsa -L 8000:localhost:8000 root@192.0.2.1
|
||||
Keep this terminal open. Navigate to **http://localhost:8000** in your
|
||||
browser.
|
||||
|
||||
> Skip this step if your speaker's firmware exposes port 8000 on the LAN
|
||||
> directly — you can reach `http://192.0.2.1:8000` without a tunnel in that
|
||||
> case.
|
||||
> **You may not need the tunnel at all.** Try `http://192.0.2.1:8000` first.
|
||||
> If that doesn't load, try **`http://192.0.2.1:17008`**: on speakers whose
|
||||
> Wi-Fi co-processor refuses to pass `:8000` through (the ST20 and likely
|
||||
> others), the installer automatically redirects port `17008` to AfterTouch,
|
||||
> so the Admin UI is reachable from the LAN without any tunnel. Check with
|
||||
> `/etc/init.d/aftertouch status` on the speaker, which reports the LAN port
|
||||
> when the redirect is active. Details and per-model status:
|
||||
> [Model Support Matrix](../reference/MODEL-SUPPORT-MATRIX.md).
|
||||
>
|
||||
> Keep the tunnel in mind anyway for **linking music-service accounts**:
|
||||
> Spotify only accepts `https://` or *loopback* OAuth redirect URIs, so
|
||||
> `http://localhost:8000` through a tunnel succeeds where a plain LAN
|
||||
> address is rejected.
|
||||
|
||||
---
|
||||
|
||||
## Step 6 — Run the Health QuickFix for empty `margeAccountUUID`
|
||||
## Step 6 — Migrate (point the speaker at itself)
|
||||
|
||||
The speaker isn't pointed at the AfterTouch instance you just installed yet
|
||||
— this step does that. On-device, the speaker and the AfterTouch instance
|
||||
are the same machine, so **loopback is the correct and recommended Target
|
||||
Domain value**: `http://localhost:8000`. This is the one case where the
|
||||
general migration guide's "must not be `localhost`" warning does not
|
||||
apply — that warning is about the external-host/cloud scenarios, where
|
||||
`localhost` would resolve on the wrong machine (the service host, not the
|
||||
speaker). Here there is no wrong machine to resolve on.
|
||||
|
||||
> **Note:** as of the fix for issue #546, the on-device init script already
|
||||
> sets `DEPLOYMENT_MODE=on-device`, so a fresh (or reinstalled/updated)
|
||||
> on-device install's own Target Domain already defaults to
|
||||
> `http://localhost:8000` automatically — no manual Settings-tab step
|
||||
> needed for that part. Older installs still default to the speaker's own
|
||||
> unresolvable Linux hostname (e.g. `http://spotty:8000`) until reinstalled
|
||||
> with a build that includes the fix, or until the Target Domain is
|
||||
> corrected by hand. Either way, you still need to run Migrate below — that
|
||||
> step tells the *speaker* to use this address, which is separate from what
|
||||
> the service defaults its own identity to.
|
||||
|
||||
**Via the Admin UI:**
|
||||
|
||||
1. Go to **Settings**, set **Target Domain** to `http://localhost:8000`.
|
||||
2. Go to **Devices**, find your speaker (it self-discovers on its own LAN
|
||||
IP), click **Migrate**.
|
||||
3. Accept the suggested plan and let it apply.
|
||||
4. Reboot to apply the change:
|
||||
```bash
|
||||
sync
|
||||
reboot
|
||||
```
|
||||
|
||||
**Or via the CLI** (equivalent, no browser needed — grab `soundtouch-cli`
|
||||
from Step 9 below first if you want this path):
|
||||
|
||||
```bash
|
||||
/mnt/nv/aftertouch/soundtouch-cli --host 127.0.0.1 setup migrate \
|
||||
--service-url http://localhost:8000 --method telnet
|
||||
sync
|
||||
reboot
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 7 — Run the Health QuickFix for empty `margeAccountUUID`
|
||||
|
||||
In the AfterTouch UI:
|
||||
|
||||
@@ -148,6 +226,14 @@ In the AfterTouch UI:
|
||||
4. Click the **QuickFix** button (labelled "Fix", "Pair account", or
|
||||
"Apply QuickFix" depending on the version) and confirm.
|
||||
|
||||
Or via the CLI (same underlying pairing call, `--mode=bare` matches what
|
||||
the QuickFix does — see Step 9 to grab `soundtouch-cli` first):
|
||||
|
||||
```bash
|
||||
/mnt/nv/aftertouch/soundtouch-cli --host 127.0.0.1 setup pair \
|
||||
--mode=bare --account=1111111 --service-url http://localhost:8000
|
||||
```
|
||||
|
||||
Then reboot again to let the pairing take effect:
|
||||
|
||||
```bash
|
||||
@@ -157,7 +243,7 @@ reboot
|
||||
|
||||
---
|
||||
|
||||
## Step 7 — Verify pairing and sources
|
||||
## Step 8 — Verify pairing and sources
|
||||
|
||||
After the reboot reconnect via SSH and check:
|
||||
|
||||
@@ -171,32 +257,37 @@ wget -qO- http://localhost:8090/info | grep margeAccountUUID
|
||||
wget -qO- http://localhost:8090/sources
|
||||
```
|
||||
|
||||
If `margeAccountUUID` is still empty, re-run the Health QuickFix (Step 6)
|
||||
If `margeAccountUUID` is still empty, re-run the Health QuickFix (Step 7)
|
||||
and reboot again.
|
||||
|
||||
---
|
||||
|
||||
## Step 8 — Download soundtouch-cli (optional, for preset setup)
|
||||
## Step 9 — Download soundtouch-cli (optional, for preset setup)
|
||||
|
||||
If you want to program preset buttons from the command line, download the
|
||||
CLI binary to the speaker's `/tmp` (tmpfs, so it survives only until the
|
||||
next reboot — which is fine for a one-time setup run):
|
||||
CLI binary to `/mnt/nv/aftertouch` (the same persistent partition
|
||||
AfterTouch itself lives on) rather than `/tmp`: `/tmp` is tmpfs and gets
|
||||
wiped on every reboot, and if you used the CLI alternatives in Steps 6/7
|
||||
above, it needs to survive those steps' reboots too, not just the final
|
||||
one:
|
||||
|
||||
```bash
|
||||
cd /tmp
|
||||
cd /mnt/nv/aftertouch
|
||||
|
||||
curl -L --fail -o soundtouch-cli \
|
||||
https://github.com/gesellix/Bose-SoundTouch/releases/download/v0.111.3/soundtouch-cli-v0.111.3-linux-armv7
|
||||
https://github.com/gesellix/Bose-SoundTouch/releases/download/v0.123.0/soundtouch-cli-v0.123.0-linux-armv7
|
||||
chmod +x soundtouch-cli
|
||||
|
||||
/tmp/soundtouch-cli --version
|
||||
/mnt/nv/aftertouch/soundtouch-cli --version
|
||||
```
|
||||
|
||||
Replace `v0.111.3` with the version you installed.
|
||||
Replace `v0.123.0` with the version you installed. If you want the CLI
|
||||
alternatives in Steps 6/7, download it here first, before doing those
|
||||
steps — it'll be in place and already persistent either way.
|
||||
|
||||
---
|
||||
|
||||
## Step 9 — Store custom radio streams to preset buttons
|
||||
## Step 10 — Store custom radio streams to preset buttons
|
||||
|
||||
Each station must be playing before it can be saved. The `sleep 5` gives
|
||||
the speaker time to buffer and confirm the stream before storing.
|
||||
@@ -206,52 +297,52 @@ the speaker time to buffer and confirm the stream before storing.
|
||||
|
||||
```bash
|
||||
# Preset 1 — Hitradio OE3
|
||||
/tmp/soundtouch-cli --host 127.0.0.1 source custom-radio \
|
||||
/mnt/nv/aftertouch/soundtouch-cli --host 127.0.0.1 source custom-radio \
|
||||
--url "http://orf-live.ors-shoutcast.at/oe3-q2a" \
|
||||
--name "Hitradio OE3" \
|
||||
--service-url "http://localhost:8000"
|
||||
sleep 5
|
||||
/tmp/soundtouch-cli --host 127.0.0.1 preset store-current --slot 1
|
||||
/mnt/nv/aftertouch/soundtouch-cli --host 127.0.0.1 preset store-current --slot 1
|
||||
|
||||
# Preset 2 — Lounge FM
|
||||
/tmp/soundtouch-cli --host 127.0.0.1 source custom-radio \
|
||||
/mnt/nv/aftertouch/soundtouch-cli --host 127.0.0.1 source custom-radio \
|
||||
--url "http://188.138.9.183/digital.mp3" \
|
||||
--name "Lounge FM" \
|
||||
--service-url "http://localhost:8000"
|
||||
sleep 5
|
||||
/tmp/soundtouch-cli --host 127.0.0.1 preset store-current --slot 2
|
||||
/mnt/nv/aftertouch/soundtouch-cli --host 127.0.0.1 preset store-current --slot 2
|
||||
|
||||
# Preset 3 — Country Nonstop
|
||||
/tmp/soundtouch-cli --host 127.0.0.1 source custom-radio \
|
||||
/mnt/nv/aftertouch/soundtouch-cli --host 127.0.0.1 source custom-radio \
|
||||
--url "https://stream.laut.fm/country-nonstop" \
|
||||
--name "Country Nonstop" \
|
||||
--service-url "http://localhost:8000"
|
||||
sleep 5
|
||||
/tmp/soundtouch-cli --host 127.0.0.1 preset store-current --slot 3
|
||||
/mnt/nv/aftertouch/soundtouch-cli --host 127.0.0.1 preset store-current --slot 3
|
||||
|
||||
# Preset 4 — Radio Piterpan
|
||||
/tmp/soundtouch-cli --host 127.0.0.1 source custom-radio \
|
||||
/mnt/nv/aftertouch/soundtouch-cli --host 127.0.0.1 source custom-radio \
|
||||
--url "https://klasse1.fluidstream.eu/piterpan.mp3?FLID=8" \
|
||||
--name "Radio Piterpan" \
|
||||
--service-url "http://localhost:8000"
|
||||
sleep 5
|
||||
/tmp/soundtouch-cli --host 127.0.0.1 preset store-current --slot 4
|
||||
/mnt/nv/aftertouch/soundtouch-cli --host 127.0.0.1 preset store-current --slot 4
|
||||
|
||||
# Preset 5 — kronehit
|
||||
/tmp/soundtouch-cli --host 127.0.0.1 source custom-radio \
|
||||
/mnt/nv/aftertouch/soundtouch-cli --host 127.0.0.1 source custom-radio \
|
||||
--url "https://secureonair.krone.at/kronehit-hp.mp3" \
|
||||
--name "kronehit" \
|
||||
--service-url "http://localhost:8000"
|
||||
sleep 5
|
||||
/tmp/soundtouch-cli --host 127.0.0.1 preset store-current --slot 5
|
||||
/mnt/nv/aftertouch/soundtouch-cli --host 127.0.0.1 preset store-current --slot 5
|
||||
|
||||
# Preset 6 — Radio Niederösterreich
|
||||
/tmp/soundtouch-cli --host 127.0.0.1 source custom-radio \
|
||||
/mnt/nv/aftertouch/soundtouch-cli --host 127.0.0.1 source custom-radio \
|
||||
--url "http://orf-live.ors-shoutcast.at/noe-q2a" \
|
||||
--name "Radio Niederoesterreich" \
|
||||
--service-url "http://localhost:8000"
|
||||
sleep 5
|
||||
/tmp/soundtouch-cli --host 127.0.0.1 preset store-current --slot 6
|
||||
/mnt/nv/aftertouch/soundtouch-cli --host 127.0.0.1 preset store-current --slot 6
|
||||
```
|
||||
|
||||
These are the stations from weissigera's setup (Austrian public and
|
||||
@@ -260,7 +351,7 @@ pattern is the same regardless of station.
|
||||
|
||||
---
|
||||
|
||||
## Step 10 — Verify presets and final reboot
|
||||
## Step 11 — Verify presets and final reboot
|
||||
|
||||
```bash
|
||||
wget -qO- http://localhost:8090/presets
|
||||
@@ -286,7 +377,7 @@ should start playing the corresponding stream.
|
||||
| SSH "no matching host key type" | Add `-oHostKeyAlgorithms=+ssh-rsa` |
|
||||
| Port 8000 not reachable from LAN | Use the SSH tunnel (Step 5) |
|
||||
| `margeAccountUUID` still empty after reboot | Re-run Health QuickFix, reboot again |
|
||||
| Radio source error 1005 | `margeAccountUUID` is empty — complete Step 6 first |
|
||||
| Radio source error 1005 | `margeAccountUUID` is empty — complete Step 7 first |
|
||||
| `http://localhost:8000` not responding after install | `logread \| grep aftertouch \| tail -20` |
|
||||
| No space left on device during install | Run the cleanup in Step 2; check `df -h /mnt/nv` |
|
||||
|
||||
@@ -305,14 +396,21 @@ older artefacts to keep `/mnt/nv` free:
|
||||
rw && curl -sSL https://raw.githubusercontent.com/gesellix/Bose-SoundTouch/main/scripts/on-device-install/install.sh | sh
|
||||
|
||||
# Update to a specific version — three equivalent forms
|
||||
VERSION=0.111.3 rw && curl -sSL https://raw.githubusercontent.com/gesellix/Bose-SoundTouch/main/scripts/on-device-install/install.sh | sh
|
||||
rw && curl -sSL https://raw.githubusercontent.com/gesellix/Bose-SoundTouch/main/scripts/on-device-install/install.sh | VERSION=0.123.0 sh
|
||||
|
||||
rw && curl -sSL https://raw.githubusercontent.com/gesellix/Bose-SoundTouch/main/scripts/on-device-install/install.sh | sh -s -- --version 0.111.3
|
||||
rw && curl -sSL https://raw.githubusercontent.com/gesellix/Bose-SoundTouch/main/scripts/on-device-install/install.sh | sh -s -- --version 0.123.0
|
||||
|
||||
curl -sSLo install.sh https://raw.githubusercontent.com/gesellix/Bose-SoundTouch/main/scripts/on-device-install/install.sh
|
||||
sh install.sh --version 0.111.3
|
||||
sh install.sh --version 0.123.0
|
||||
```
|
||||
|
||||
The script's own final output already confirms the new version came up and
|
||||
is answering on `:8000`. If you separately check the version yourself
|
||||
(`wget -qO- http://localhost:8000/health`, or the Admin UI), **reboot the
|
||||
speaker first**: an Admin UI tab left open from before the update, or a
|
||||
browser cache of the previous page load, can otherwise still show the old
|
||||
version even though the new binary is already running.
|
||||
|
||||
**Rollback:** the installer keeps a `.backup` file alongside the binary:
|
||||
|
||||
```bash
|
||||
@@ -322,6 +420,39 @@ cp /mnt/nv/aftertouch/aftertouch-service.<old-version>.backup \
|
||||
/etc/init.d/aftertouch restart
|
||||
```
|
||||
|
||||
**Testing a pre-release build (from `main`, not yet tagged):** `install.sh`
|
||||
only ever downloads from GitHub Releases, so there's no one-line installer
|
||||
for an unreleased commit. Cross-compile and swap the binary manually
|
||||
instead — this is a direct extension of the rollback procedure above:
|
||||
|
||||
```bash
|
||||
# On your own machine, from a checkout of the branch/commit you want:
|
||||
make build-linux-armv7 # builds build/soundtouch-service-linux-armv7,
|
||||
# build/soundtouch-cli-linux-armv7, and
|
||||
# build/soundtouch-backup-linux-armv7
|
||||
|
||||
scp build/soundtouch-service-linux-armv7 root@192.0.2.1:/mnt/nv/aftertouch/aftertouch-service.new
|
||||
ssh -oHostKeyAlgorithms=+ssh-rsa root@192.0.2.1
|
||||
|
||||
rw
|
||||
/etc/init.d/aftertouch stop
|
||||
cp /mnt/nv/aftertouch/aftertouch-service /mnt/nv/aftertouch/aftertouch-service.pre-test.backup
|
||||
mv /mnt/nv/aftertouch/aftertouch-service.new /mnt/nv/aftertouch/aftertouch-service
|
||||
chmod +x /mnt/nv/aftertouch/aftertouch-service
|
||||
/etc/init.d/aftertouch start
|
||||
```
|
||||
|
||||
If you're testing an unreleased `soundtouch-cli` change (not just the
|
||||
service), swap that binary too — same idea, and it lands in the same
|
||||
`/mnt/nv/aftertouch` directory Step 9 above uses:
|
||||
|
||||
```bash
|
||||
scp build/soundtouch-cli-linux-armv7 root@192.0.2.1:/mnt/nv/aftertouch/soundtouch-cli
|
||||
ssh -oHostKeyAlgorithms=+ssh-rsa root@192.0.2.1 chmod +x /mnt/nv/aftertouch/soundtouch-cli
|
||||
```
|
||||
|
||||
Roll back the same way as above, using the `.pre-test.backup` file.
|
||||
|
||||
---
|
||||
|
||||
## Service management
|
||||
|
||||
@@ -40,14 +40,14 @@ sudo bash install.sh
|
||||
Install a specific version:
|
||||
|
||||
```bash
|
||||
sudo bash install.sh v0.111.3
|
||||
sudo bash install.sh v0.123.0
|
||||
```
|
||||
|
||||
Override defaults at install time:
|
||||
|
||||
```bash
|
||||
sudo \
|
||||
VERSION=v0.111.3 \
|
||||
VERSION=v0.123.0 \
|
||||
HOSTNAME_FQDN=soundtouch.local \
|
||||
HTTP_PORT=80 \
|
||||
HTTPS_PORT=443 \
|
||||
@@ -105,7 +105,7 @@ journalctl -u soundtouch-service -b # this boot only
|
||||
|
||||
```bash
|
||||
sudo bash install.sh # update to latest release
|
||||
sudo bash install.sh v0.111.3 # update to a specific version
|
||||
sudo bash install.sh v0.123.0 # update to a specific version
|
||||
```
|
||||
|
||||
The script stops the service, downloads the new binary (backs up the old one to
|
||||
@@ -157,14 +157,14 @@ sudo bash install-player.sh
|
||||
Install a specific version:
|
||||
|
||||
```bash
|
||||
sudo bash install-player.sh v0.111.3
|
||||
sudo bash install-player.sh v0.123.0
|
||||
```
|
||||
|
||||
Override defaults at install time:
|
||||
|
||||
```bash
|
||||
sudo \
|
||||
VERSION=v0.111.3 \
|
||||
VERSION=v0.123.0 \
|
||||
HTTP_PORT=8081 \
|
||||
bash install-player.sh
|
||||
```
|
||||
@@ -252,7 +252,7 @@ journalctl -u soundtouch-player -f
|
||||
|
||||
```bash
|
||||
sudo bash install-player.sh # update to latest release
|
||||
sudo bash install-player.sh v0.111.3 # update to a specific version
|
||||
sudo bash install-player.sh v0.123.0 # update to a specific version
|
||||
```
|
||||
|
||||
### Removal
|
||||
|
||||
@@ -156,30 +156,35 @@ The service supports multiple ways to configure its behavior. When multiple sour
|
||||
|
||||
### Configuration Options
|
||||
|
||||
| Variable | Flag | Description | Default |
|
||||
|------------------------------------|----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------|
|
||||
| `PORT` | `--port`, `-p` | HTTP port to bind the service to | `8000` |
|
||||
| `BIND_ADDR` | `--bind` | Network interface to bind to | all (ipv4 and ipv6) |
|
||||
| `DATA_DIR` | `--data-dir` | Directory for persistent data | `./data` |
|
||||
| `SERVER_URL` | `--server-url`, `-s` | External URL of this service | `http://<hostname>:8000` |
|
||||
| `HTTPS_PORT` | `--https-port` | HTTPS port to bind the service to | `8443` |
|
||||
| `HTTPS_SERVER_URL` | `--https-server-url`, `-S` | External HTTPS URL. An override: when empty it is derived from `SERVER_URL` (same host, `https`, on `HTTPS_PORT`), and can also be viewed/overridden in Settings. | derived from `SERVER_URL` |
|
||||
| `PYTHON_BACKEND_URL`, `TARGET_URL` | `--target-url` | URL for Python-based service components (legacy) | `http://localhost:8001` |
|
||||
| `REDACT_PROXY_LOGS` | `--redact-logs` | Redact sensitive data in proxy logs | `true` |
|
||||
| `LOG_PROXY_BODY` | `--log-bodies` | Log full request/response bodies | `false` |
|
||||
| `RECORD_INTERACTIONS` | `--record-interactions` | Record HTTP interactions to disk | `true` |
|
||||
| `DISCOVERY_INTERVAL` | `--discovery-interval` | Device discovery interval | `5m` |
|
||||
| `ENABLE_DNS_DISCOVERY` | `--dns-discovery` | Enable DNS discovery server | `false` |
|
||||
| `DNS_UPSTREAM` | `--dns-upstream` | Upstream DNS server for non-Bose queries | `8.8.8.8` |
|
||||
| `DNS_BIND_ADDR` | `--dns-bind` | Bind address for the DNS discovery server (standard port `:53` is required for DNS/DHCP migration) | `:53` |
|
||||
| `INTERNAL_PATHS` | `--internal-paths` | Paths for internal requests to exclude from recording (e.g., `/setup/*`, `/web/*`) | `[]` |
|
||||
| `DISCOVERY_DISABLED` | | Disable automated device discovery | `false` |
|
||||
| `MGMT_USERNAME` | `--mgmt-username` | Username for HTTP Basic Auth on the Management API (`/api/mgmt/*`, `/mgmt/*`) — Spotify/Amazon account linking, Local Accounts | `admin` |
|
||||
| `MGMT_PASSWORD` | `--mgmt-password` | Password for the same Management API Basic Auth. **Change this if AfterTouch is reachable beyond a trusted LAN** — the default is published in this doc. | `change_me!` |
|
||||
| `STOCKHOLM_DIR` | `--stockholm-dir` | Path to extracted Stockholm frontend directory — enables the Stockholm UI when set | *(disabled)* |
|
||||
| `MARGE_URL` | | Streaming/marge base URL used when rewriting `stockholm/json/config.json`. Defaults to `SERVER_URL`. Set to `SERVER_URL/marge` only when using a soundcork backend. | *(same as `SERVER_URL`)* |
|
||||
| `MARGE_AUTH_TOKEN` | | Pre-seeds the Stockholm `margeAuthToken` state (skips the login step for the first session) | *(empty)* |
|
||||
| `MARGE_ACCOUNT_ID` | | Pre-seeds the Stockholm `margeAccountID` state (used to filter device-discovery results by account) | *(empty)* |
|
||||
| Variable | Flag | Description | Default |
|
||||
|------------------------------------|--------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------|
|
||||
| `PORT` | `--port`, `-p` | HTTP port to bind the service to | `8000` |
|
||||
| `BIND_ADDR` | `--bind` | Network interface to bind to | all (ipv4 and ipv6) |
|
||||
| `DATA_DIR` | `--data-dir` | Directory for persistent data | `./data` |
|
||||
| `SERVER_URL` | `--server-url`, `-s` | External URL of this service | `http://<hostname>:8000` |
|
||||
| `DEPLOYMENT_MODE` | `--deployment-mode` | Where this service runs: `on-device`, `private-network`, or `public-network`. Only changes behavior when `SERVER_URL` is *not* set: `on-device` defaults to `http://localhost:<port>` instead of guessing a hostname (the speaker's own Linux hostname is never resolvable — see issue #546); `public-network` refuses to start rather than guess a publicly reachable address; unset/`private-network` keeps the previous hostname-guessing behavior, now with a startup warning. The on-device install script sets this automatically. | unset (legacy hostname guess, with warning) |
|
||||
| `HTTPS_PORT` | `--https-port` | HTTPS port to bind the service to | `8443` |
|
||||
| `HTTPS_SERVER_URL` | `--https-server-url`, `-S` | External HTTPS URL. An override: when empty it is derived from `SERVER_URL` (same host, `https`, on `HTTPS_PORT`), and can also be viewed/overridden in Settings. | derived from `SERVER_URL` |
|
||||
| `PYTHON_BACKEND_URL`, `TARGET_URL` | `--target-url` | URL for Python-based service components (legacy) | `http://localhost:8001` |
|
||||
| `REDACT_PROXY_LOGS` | `--redact-logs` | Redact sensitive data in proxy logs | `true` |
|
||||
| `LOG_PROXY_BODY` | `--log-bodies` | Log full request/response bodies | `false` |
|
||||
| `RECORD_INTERACTIONS` | `--record-interactions` | Record HTTP interactions to disk | `true` |
|
||||
| `DISCOVERY_ENABLED` | `--discovery-enabled` | Enable periodic device discovery | `true` |
|
||||
| `DISCOVERY_INTERVAL` | `--discovery-interval` | Device discovery interval | `5m` |
|
||||
| `DEVICE_SEED_RETRY_INTERVAL` | `--device-seed-retry-interval` | Interval between embedded-player startup retries for persisted devices that failed their first probe (e.g. LAN not yet routable on a cold boot) | `30s` |
|
||||
| `DEVICE_SEED_RETRY_WINDOW` | `--device-seed-retry-window` | Bounded window during which the embedded player retries those unreachable persisted devices at startup | `10m` |
|
||||
| `ENABLE_DNS_DISCOVERY` | `--dns-discovery` | Enable DNS discovery server | `false` |
|
||||
| `DNS_UPSTREAM` | `--dns-upstream` | Upstream DNS server for non-Bose queries | `8.8.8.8` |
|
||||
| `DNS_BIND_ADDR` | `--dns-bind` | Bind address for the DNS discovery server (standard port `:53` is required for DNS/DHCP migration) | `:53` |
|
||||
| `INTERNAL_PATHS` | `--internal-paths` | Paths for internal requests to exclude from recording (e.g., `/setup/*`, `/web/*`) | `[]` |
|
||||
| `UPDATE_CHECK_ENABLED` | `--update-check-enabled` | Periodically check GitHub Releases for a newer version and show a dismissible notice in the admin UI and Player when one is found. **Opt-in**: this is the only network call AfterTouch makes beyond speaker/provider traffic when enabled, so it defaults off. One unauthenticated `GET` per interval to `api.github.com`, nothing else leaves the box. Also available as an "Update Check" toggle on the admin Settings page, which applies without a restart; the env var/flag is the seed value for a fresh install with no `settings.json` yet. | `false` |
|
||||
| `UPDATE_CHECK_INTERVAL` | `--update-check-interval` | Update check interval. Also editable on the admin Settings page (applies without a restart). | `24h` |
|
||||
| `MGMT_USERNAME` | `--mgmt-username` | Username for HTTP Basic Auth on the Management API (`/api/mgmt/*`, `/mgmt/*`) — Spotify/Amazon account linking, Local Accounts | `admin` |
|
||||
| `MGMT_PASSWORD` | `--mgmt-password` | Password for the same Management API Basic Auth. **Change this if AfterTouch is reachable beyond a trusted LAN** — the default is published in this doc. | `change_me!` |
|
||||
| `STOCKHOLM_DIR` | `--stockholm-dir` | Path to extracted Stockholm frontend directory — enables the Stockholm UI when set | *(disabled)* |
|
||||
| `MARGE_URL` | | Streaming/marge base URL used when rewriting `stockholm/json/config.json`. Defaults to `SERVER_URL`. Set to `SERVER_URL/marge` only when using a soundcork backend. | *(same as `SERVER_URL`)* |
|
||||
| `MARGE_AUTH_TOKEN` | | Pre-seeds the Stockholm `margeAuthToken` state (skips the login step for the first session) | *(empty)* |
|
||||
| `MARGE_ACCOUNT_ID` | | Pre-seeds the Stockholm `margeAccountID` state (used to filter device-discovery results by account) | *(empty)* |
|
||||
|
||||
### Configuration Examples
|
||||
|
||||
@@ -472,6 +477,24 @@ curl -X POST "http://localhost:8000/setup/migrate/192.0.2.100?method=telnet&targ
|
||||
curl -X POST "http://localhost:8000/setup/migrate/192.0.2.100?method=resolv&target_url=https://my-server.com:8443"
|
||||
```
|
||||
|
||||
#### `POST /setup/revert/{deviceID}`
|
||||
Reverts either an SSH-backed migration or the URL fields written by a telnet migration.
|
||||
|
||||
- No `method` query parameter, or `method=ssh`, preserves the existing behavior:
|
||||
restore the on-speaker `.original` files and related SSH-managed state.
|
||||
- `method=telnet` restores the four canonical Bose service URLs without SSH.
|
||||
The optional `marge_url`, `stats_url`, `sw_update_url`, and `bmx_url` query
|
||||
parameters override individual canonical values.
|
||||
- Supplying those URL parameters with the default SSH method returns `400`
|
||||
instead of silently ignoring them. Invalid or command-unsafe telnet URLs also
|
||||
return `400` before a speaker connection is attempted.
|
||||
|
||||
The telnet path changes URL configuration only and does not reboot the speaker.
|
||||
Its commands are sequential, so an error can mean partial runtime state or an
|
||||
uncertain persistence outcome. Read back and reconcile all four fields before
|
||||
retrying or rebooting. A successful response confirms the runtime readback;
|
||||
verify persistence after the subsequent reboot.
|
||||
|
||||
#### `POST /setup/telnet-probe/{deviceIP}`
|
||||
SSH-less reachability check. Temporarily flips the speaker's `swUpdateUrl` via the port-17000 diagnostic shell, triggers `:8090/swUpdateCheck` on the device, and observes whether the resulting outbound lands on this service's `/probe/{token}` handler within 6 s. Always attempts to restore the original `swUpdateUrl` even on failure.
|
||||
|
||||
|
||||
@@ -456,6 +456,63 @@ client.SelectAux()
|
||||
|
||||
---
|
||||
|
||||
## 🎛️ **Lifestyle / Console Device Behavior** {#lifestyle-console-devices}
|
||||
|
||||
### ❌ "Console-style device (Lifestyle, CineMate) plays the first test station but every later one reports INVALID_SOURCE"
|
||||
|
||||
On a Bose Lifestyle or CineMate console, the SoundTouch module is one input
|
||||
among several (TV, AUX, Bluetooth, ...). As already established in #160,
|
||||
the console's active input cannot be switched from the SoundTouch side —
|
||||
there is no API call that forces it back onto SoundTouch.
|
||||
|
||||
**Symptoms:**
|
||||
- `/now_playing` reports `source="LOCAL"` with an empty `ContentItem`:
|
||||
```xml
|
||||
<nowPlaying deviceID="..." source="LOCAL">
|
||||
<ContentItem source="LOCAL" isPresetable="true" />
|
||||
</nowPlaying>
|
||||
```
|
||||
- `LOCAL` does not appear in `/sources` at all.
|
||||
- `POST /select` and `POST /key` (e.g. `PRESET_1`) are accepted
|
||||
(`<status>/select</status>`) but have no observable effect.
|
||||
|
||||
This means the console is sitting on its own (non-SoundTouch) input, not
|
||||
that the content/station itself is invalid. The input has to be selected
|
||||
on the console's own remote or front panel; there is no way to do it via
|
||||
the SoundTouch API.
|
||||
|
||||
**The trap:** `POST /key POWER` does not behave like it does on a plain
|
||||
speaker. On a speaker, `POWER` is a harmless way to stop playback between
|
||||
test runs. On a console, it puts the whole unit into standby — and on
|
||||
waking, the console returns to **its own** input, not back to SoundTouch.
|
||||
A test loop that stops playback with `POWER` between trials silently
|
||||
switches the device off SoundTouch after the *first* trial, so every
|
||||
station from the second one onward reports `INVALID_SOURCE` — including
|
||||
stations that would otherwise play perfectly fine. This is easy to
|
||||
misread as a per-station problem (e.g. "this console can't handle TLS/
|
||||
https streams") when it is actually a test-methodology artifact: whichever
|
||||
station happens to run first in the loop is the only one actually tested
|
||||
against SoundTouch input.
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. Before testing anything, select the SoundTouch input on the console
|
||||
itself (remote or front panel), not via the API.
|
||||
2. Do not use `POST /key POWER` to stop playback between trials on these
|
||||
devices. If you need to interrupt playback, use a different key
|
||||
(e.g. `PAUSE`/`STOP`) or simply move directly to selecting the next
|
||||
station.
|
||||
3. If `/now_playing` shows `source="LOCAL"` with `LOCAL` absent from
|
||||
`/sources`, treat that as "console is on a different input" — re-select
|
||||
SoundTouch on the console and retest before concluding anything about
|
||||
the station or migration itself.
|
||||
|
||||
See #597 for the original report, including a packet capture confirming a
|
||||
station that appeared to fail actually completed a full TLS handshake and
|
||||
streamed normally once the console was back on the SoundTouch input.
|
||||
|
||||
---
|
||||
|
||||
## 🎶 **Music Service & Preset Issues**
|
||||
|
||||
### ❌ Spotify preset fails with "Current content cannot be saved as preset"
|
||||
@@ -537,6 +594,53 @@ Once the source plays once, it gets persisted to `/mnt/nv/BoseApp-Persistence/1/
|
||||
|
||||
If `soundtouch-cli source content --source TUNEIN ...` returns `1005` on a reset device that has never had TuneIn, the speaker is refusing because the source isn't registered yet — chicken-and-egg. The SoundTouch app is then the only practical path to register it; we can't write `Sources.xml` directly over telnet on most models.
|
||||
|
||||
### ❌ Presets get wiped after a reboot, on a speaker sharing its Marge account with other devices {#preset-wipe-shared-account}
|
||||
|
||||
**Symptoms:**
|
||||
|
||||
- Presets are programmed and confirmed correct (e.g. via the Admin UI or `soundtouch-cli`), but after a plain reboot of the speaker, its own preset list comes back empty (`<presets />`) — even though the service's own `Presets.xml` for that device is untouched and still shows the correct presets.
|
||||
- The affected speaker is one of several devices under the **same** Marge account — for example a separate on-device AfterTouch instance per speaker, or several physical speakers migrated to one shared account.
|
||||
- Clicking **Sync** in the Admin UI can also lose presets, but since v0.129.0 that path shows a confirmation warning before it overwrites anything destructively — that's a different, already-fixed issue (a stale-snapshot overwrite guard), not the reboot behavior described here.
|
||||
|
||||
**Cause:**
|
||||
|
||||
Not fully root-caused — this is firmware-internal. A byte-exact capture of the speaker's own `/full` request confirmed AfterTouch serves the correct preset data at the exact moment of the reboot-triggered resync; the wipe happens *after* that, entirely inside the speaker's own firmware callback chain, with no further network exchange to intercept from the service side. The trigger correlates with the **number of devices** listed under the account, not the account ID itself: removing the other devices from the account fixed it for one reporter, while changing only the account ID (with the other devices still present) did not. This isn't a universal shared-account problem either — a setup using a distinct account ID per speaker, with discovery left enabled, has not reproduced it — so treat this as an observed correlation, not a proven mechanism. See [issue #614](https://github.com/gesellix/Bose-SoundTouch/issues/614) for the full debugging history.
|
||||
|
||||
**Workaround (confirmed working, root cause still open):**
|
||||
|
||||
1. Admin UI → **Settings** → disable **"Enable Periodic Discovery"** first. Order matters — leaving it on lets a background sweep re-add a device you just removed, mid-cleanup.
|
||||
2. Admin UI → **Devices** tab → click **✕** to remove every other device from the account, leaving only the speaker you're troubleshooting.
|
||||
3. Reboot the speaker and confirm the presets survive.
|
||||
|
||||
This is fully reversible: re-enabling discovery brings the other devices back as harmless entries, and it doesn't touch their own presets/recents.
|
||||
|
||||
If you'd rather not change device-list membership, the Health tab's **"Restore presets to speaker"** QuickFix pushes the service's stored presets back onto the speaker without a reboot — a workaround for the symptom rather than the trigger, but useful if you hit this again before removing devices.
|
||||
|
||||
### ❌ Changing Target Domain in Settings doesn't change what a speaker actually uses {#settings-vs-migrate}
|
||||
|
||||
**Symptoms:**
|
||||
|
||||
- You update **Settings → Target Domain / Server URL** (via the Admin UI, `SERVER_URL`, or `--deployment-mode`), and the Admin UI confirms the new value with no warning.
|
||||
- An already-migrated speaker's own behavior is unchanged: playback/BMX requests still go to the *old* address, and `soundtouch-cli setup inspect --telnet` still shows the old `margeServerUrl`/`statsServerUrl`/`bmxRegistryUrl`/`swUpdateUrl`.
|
||||
|
||||
**Cause:** Settings only updates the *service's own* record of its address (`s.serverURL`, persisted to `settings.json`) — the save handler never contacts any device. A speaker only learns a new address at migrate time: the telnet method writes it via `sys configuration ...` plus a closing `envswitch boseurls set ...` for the reboot-persisted layer; the XML/SSH method uploads a fresh `SoundTouchSdkPrivateCfg.xml`. Both write **once**, with no mechanism for a speaker to later re-fetch its own config from the service — this is equally true for either migration method. A "Sync" or `sourcesUpdated` notification only refreshes the speaker's source *list*, not its server URL configuration.
|
||||
|
||||
**Fix:** Any Target Domain change that needs to reach an already-migrated speaker requires a fresh Migrate afterward — Settings alone is never enough for a speaker that's been migrated before:
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <speaker-ip> setup migrate --method telnet --service-url <new-target-domain>
|
||||
```
|
||||
|
||||
Confirm it took:
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <speaker-ip> setup inspect --telnet
|
||||
```
|
||||
|
||||
`margeServerUrl`/`statsServerUrl`/`bmxRegistryUrl`/`swUpdateUrl` should all match the new value. Repeat per speaker — Settings is one service-wide value, but each speaker keeps its own independently-migrated copy, so a multi-speaker household needs a re-migrate for each one.
|
||||
|
||||
This also applies to a freshly-fixed on-device default (see `DEPLOYMENT_MODE`, #546): the installer now gets the *default* right for new installs automatically, but an install that was already migrated before you updated still needs the explicit re-migrate above — the fix only stops a *new* bad value from being written, it doesn't retroactively correct an already-migrated speaker.
|
||||
|
||||
### ❌ Radio sources never activate after an in-place migration {#radio-sources-after-migration}
|
||||
|
||||
**Symptoms:**
|
||||
@@ -571,12 +675,92 @@ Notes:
|
||||
|
||||
If the telnet method isn't available for your model, factory reset the speaker, then re-migrate it:
|
||||
|
||||
1. Factory reset (on most models: hold `1` + `−` for ~10 seconds).
|
||||
1. Factory reset (on most models: hold `1` + `−` for ~10 seconds — confirmed
|
||||
identical on the SoundTouch 30 Series III, not just the original ST30).
|
||||
2. Reconnect the speaker to your network.
|
||||
3. Re-migrate it in AfterTouch.
|
||||
|
||||
After this the radio sources activate normally. Note the factory reset rewrites the speaker's `Sources.xml` to defaults, so any **account-bound** source (for example a music-streaming login) has to be re-added afterwards; your presets for it come back once the source is present again.
|
||||
|
||||
### ❌ `setup enable-ssh` (or a telnet command) fails right after a power-cycle, but works if you wait
|
||||
|
||||
**Symptoms:**
|
||||
|
||||
- You power-cycled the speaker — as our own retry guidance suggests after a `setup enable-ssh` timeout — and immediately re-ran the command (or a telnet migration/pairing step).
|
||||
- You get `telnet dial <ip>:17000: connection refused` or the command otherwise fails as if the port were closed.
|
||||
- Running the exact same command again a minute or two later works fine, on the same device.
|
||||
|
||||
**Cause:**
|
||||
|
||||
Confirmed on hardware across five device variants (2026-08-09): different ports on the same speaker become ready at very different times after a cold boot. HTTP `:8090` typically answers first, but the diagnostic telnet shell on `:17000` — and the config subsystem behind it that `getpdo` reads — takes longer: 55–92 seconds observed, median ~70s. "The box answers on one port" is a weaker signal than "the box can answer on the specific port you need." See [TELNET-COMMAND-REFERENCE.md](../analysis/TELNET-COMMAND-REFERENCE.md) for the underlying mechanism.
|
||||
|
||||
**Fix:** After a power-cycle, wait at least 90 seconds before retrying any telnet-based command. If it still fails after that, wait a full 2 minutes before assuming the port is genuinely closed on that firmware rather than just slow to come up.
|
||||
|
||||
### ❌ Speaker gets slower/less responsive over time after `setup enable-ssh` with no `--service-url`
|
||||
|
||||
**Symptoms:**
|
||||
|
||||
- You ran `soundtouch-cli setup enable-ssh` without `--service-url` (or via the Admin UI's equivalent) to bootstrap SSH, and never followed up with a real `setup migrate`.
|
||||
- Over time (hours to days), the speaker becomes progressively less responsive — slow to answer `:8090`, SSH connections time out, the Admin UI shows it as flaky or offline.
|
||||
|
||||
**Cause:**
|
||||
|
||||
`enable-ssh` without `--service-url` writes a deliberately-invalid placeholder (`https://aftertouch.invalid`) into `margeServerUrl`/`swUpdateUrl`/etc — by design, since the SSH-enable injection only needs *a* URL to round-trip through, not a working one. But unless you run `setup migrate` (or the Admin UI's Migrate step) afterward, that placeholder **stays persisted** — the command's own success message says so explicitly. The firmware then retries a failing DNS/curl lookup against it on a background loop (same class of failure as the `mojo`/`taigan` unresolvable-hostname case, #546) — an ongoing resource drain that isn't dramatic on its own, but confirmed on real hardware (2026-08-16) to compound badly if anything else (e.g. a burst of SSH connections — see the `setup revert` entry below) puts the speaker under load at the same time.
|
||||
|
||||
**Fix:** Always follow `enable-ssh` (when run without `--service-url`) with a real `setup migrate` before walking away. If you're recovering a speaker that's already stuck like this: power-cycle it, confirm it's reachable (`ping`, `curl :8090/info`, a single plain `ssh ... echo ok`) before doing anything else, then run `setup migrate` with the real URLs. If you want to point it back at the **original Bose cloud** URLs instead of AfterTouch (e.g. to fully decommission it), use the per-field overrides on `--method=telnet` — see the `setup migrate` section of [CLI-REFERENCE.md](CLI-REFERENCE.md) — which writes over a single telnet connection, no SSH required:
|
||||
|
||||
```bash
|
||||
soundtouch-cli --host <SPEAKER-IP> setup migrate --method telnet \
|
||||
--service-url https://streaming.bose.com \
|
||||
--marge-url https://streaming.bose.com \
|
||||
--stats-url https://events.api.bosecm.com \
|
||||
--sw-update-url https://worldwide.bose.com/updates/soundtouch \
|
||||
--bmx-url https://content.api.bose.io/bmx/registry/v1/services
|
||||
```
|
||||
|
||||
### ❌ `setup revert` (or the Admin UI's "Revert to Defaults") fails with "backup .original not found" even though the file exists
|
||||
|
||||
**Status: fixed** (branch `docs-ondevice-install-gaps`, not yet in a numbered release as of this writing) — kept below for anyone hitting this on an older build, and because the underlying "don't hammer a struggling speaker" advice is still good practice generally.
|
||||
|
||||
**Symptoms:**
|
||||
|
||||
- You confirm via a separate SSH session that `/opt/Bose/etc/SoundTouchSdkPrivateCfg.xml.original` genuinely exists.
|
||||
- `setup revert` (or clicking "Revert to Defaults") still reports `backup .../SoundTouchSdkPrivateCfg.xml.original not found, cannot revert`.
|
||||
- A follow-up plain SSH command to the same speaker fails with `Operation timed out` at the TCP level — not an auth or shell error.
|
||||
|
||||
**Cause:** `RevertMigration`'s full call graph opened **17 separate SSH connections** in rapid succession (`pkg/ssh.Client.Run()` dialed fresh every call, with no connection reuse across `revertXMLConfig`/`revertHosts`/`revertResolvConf`/`revertAftertouchHook`/`removeRcLocalHooks`/`revertCACert`). Hitting a resource-constrained embedded speaker with that many rapid reconnects could overwhelm it — confirmed on real hardware (2026-08-16), where the speaker became unreachable shortly after. On top of that, `revertXMLConfig`'s error handling collapses *any* non-nil error from its file-existence check into "not found," so a dial failure got misreported as a missing backup — the message didn't mean what it said.
|
||||
|
||||
**Fix:** `pkg/ssh.Client` now supports an opt-in persistent connection (`Connect()`/`Close()`) that `RevertMigration` uses to collapse those 17 connections into 1 — confirmed on the same real hardware (2026-08-16): a subsequent `setup revert` completed quickly, and the restored config file diffed byte-identical against `.original`. If you're on a build that predates this fix, don't retry `setup revert` back-to-back — if it fails, wait a minute and confirm the speaker is reachable again (`ping`, a single plain `ssh ... echo ok`) before retrying. If all you actually need is to point the speaker's URLs somewhere else (back to AfterTouch, or back to the original Bose cloud), the lighter-weight `setup migrate --method telnet` with explicit URL overrides (previous entry) uses one telnet connection instead of SSH entirely.
|
||||
|
||||
### ❌ On-device install: AfterTouch answers on the speaker but not from other machines on the LAN
|
||||
|
||||
**Symptoms:**
|
||||
|
||||
- On the speaker itself, `curl http://localhost:8000/health` works and `/etc/init.d/aftertouch status` is green.
|
||||
- From any other machine, `http://<speaker-ip>:8000` fails immediately (connection refused/reset, not a timeout).
|
||||
- SSH to the same speaker works fine, so it is clearly reachable in general.
|
||||
|
||||
**Cause:**
|
||||
|
||||
Some SoundTouch chassis carry a BCO ("SMSC") Wi-Fi/Bluetooth co-processor, and inbound LAN traffic reaches the main Linux SoC only for a fixed set of Bose's *own* service ports, a list that appears to be compiled into the co-processor's firmware. AfterTouch's `:8000` was never part of that original design, so the connection never arrives at the SoC at all. Confirmed on an ST20 (`spotty`, FW 27.0.6) in 2026-08: `tcpdump -i eth0` on the speaker saw **zero packets** for `:8000` while Bose's `:8090`/`:8091`/`:17000` answered normally from the same client. This is not a firewall (the speaker's `iptables` is empty) and not a binding problem (the service does listen on `0.0.0.0:8000`).
|
||||
|
||||
**Fix:**
|
||||
|
||||
The on-device installer handles this automatically: on an affected speaker it redirects a relayed Bose port to AfterTouch, so use:
|
||||
|
||||
```
|
||||
http://<speaker-ip>:17008
|
||||
```
|
||||
|
||||
To check or change it, on the speaker:
|
||||
|
||||
```bash
|
||||
/etc/init.d/aftertouch status # reports the LAN port when active
|
||||
iptables -t nat -S PREROUTING # shows the redirect rule
|
||||
```
|
||||
|
||||
Set `AFTERTOUCH_LAN_PORT` in `/opt/aftertouch/aftertouch.conf` to a different port, or to `none` to disable the redirect and use an SSH tunnel instead; then `/etc/init.d/aftertouch restart`. Note that **linking music-service accounts still works best through the tunnel** (`http://localhost:8000`), because Spotify only accepts `https://` or loopback OAuth redirect URIs. If you also run the `streborn` project on the same speaker, note it defaults to the same port, so change one of them. Which models are affected is tracked in [MODEL-SUPPORT-MATRIX.md](../reference/MODEL-SUPPORT-MATRIX.md).
|
||||
|
||||
## 🔊 **Volume & Audio Issues**
|
||||
|
||||
### ❌ "Volume control not working"
|
||||
|
||||
@@ -100,6 +100,20 @@ All subsequent messages (except `selectLastWiFiSource`, see below) use this enve
|
||||
|
||||
## Phase 2 — Pairing a New Speaker
|
||||
|
||||
> **Preflight (AfterTouch's `setup pair --mode=full`).** Before opening the
|
||||
> WebSocket, AfterTouch reads `GET /supportedURLs` (must list
|
||||
> `/setMargeAccount`) and `GET /soundTouchConfigurationStatus`, and only
|
||||
> runs the state machine below when the status is exactly
|
||||
> `SOUNDTOUCH_NOT_CONFIGURED`. This matters because a speaker can be
|
||||
> reachable, named, and already have a `margeAccountUUID` set, yet still
|
||||
> report `SOUNDTOUCH_NOT_CONFIGURED` — the firmware keeps prompting to
|
||||
> install the Bose app until a full acknowledged pass through this state
|
||||
> machine runs, not just `setMargeAccount` on its own. Already-configured
|
||||
> devices are a no-op; an unsupported route or an unrecognised status value
|
||||
> aborts without writing anything. See
|
||||
> [#615](https://github.com/gesellix/Bose-SoundTouch/issues/615) and
|
||||
> `Manager.PreflightInitPlan` (`pkg/service/setup/marge_pairing.go`).
|
||||
|
||||
### 2.1 Setup State Machine
|
||||
|
||||
The pairing flow uses a setup state machine on the device. States must be sent in order.
|
||||
@@ -122,7 +136,7 @@ The pairing flow uses a setup state machine on the device. States must be sent i
|
||||
</soundTouchConfigurationUpdated>
|
||||
</updates>
|
||||
|
||||
<!-- 3. Set language (3 = German; adjust as needed) -->
|
||||
<!-- 3. Set language (3 = English; adjust as needed) -->
|
||||
<msg><header deviceID="{device_id}" url="language" method="POST">
|
||||
<request requestID="23"></request>
|
||||
</header><body><sysLanguage>3</sysLanguage></body></msg>
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
---
|
||||
title: "Model Support Matrix"
|
||||
---
|
||||
A living record of how individual SoundTouch models behave with AfterTouch,
|
||||
built up from things actually observed on hardware.
|
||||
|
||||
**This table only claims what someone has verified.** Anything not tested is
|
||||
marked `?` rather than inferred from a similar-looking model. Bose used
|
||||
several different chassis designs across the SoundTouch line, and at least
|
||||
one behaviour (LAN reachability, below) differs between them in a way that is
|
||||
invisible from the outside. If you have a model that isn't filled in yet,
|
||||
[the commands below](#how-to-fill-in-a-row) produce everything a row needs.
|
||||
|
||||
## What the columns mean
|
||||
|
||||
- **variant / moduleType**: the speaker's own identifiers, straight out of
|
||||
`/info`. `variant` is Bose's internal codename for the product; `moduleType`
|
||||
distinguishes chassis generations (`scm` and `sm2` are the two seen so far).
|
||||
- **BCO**: whether the board carries a BCO co-processor (Bose's internal name
|
||||
for the SMSC Wi-Fi/Bluetooth combo chip that also handles AirPlay). Bose's
|
||||
own `has-bco` helper on the device is simply
|
||||
`[ "$(cat /proc/module_type)" = scm ]`.
|
||||
- **`:8000` from LAN**: whether AfterTouch's own port is reachable from
|
||||
another machine on the network *without* any workaround.
|
||||
- **Entry port**: when `:8000` isn't reachable, the port AfterTouch redirects
|
||||
to itself so the admin UI still works. See
|
||||
[LAN access on co-processor chassis](#lan-access-on-co-processor-chassis).
|
||||
|
||||
## Matrix
|
||||
|
||||
| Model | variant | moduleType | BCO | On-device install | `:8000` from LAN | Entry port | Evidence |
|
||||
|---------------------|----------|------------|-----|-------------------|------------------|------------|-----------------------------------------------------------------------|
|
||||
| SoundTouch 20 | `spotty` | `scm` | yes | works | ✗ blocked | `17008` | verified on hardware 2026-08-16 (FW 27.0.6), redirect survives reboot |
|
||||
| SoundTouch 10 | ? | ? | ? | reported working | ? | ? | not tested for LAN reachability |
|
||||
| SoundTouch 30 | ? | ? | ? | reported working | ? | ? | not tested for LAN reachability |
|
||||
| SoundTouch Portable | ? | ? | ? | ? | ? | ? | not tested |
|
||||
| Wave / SA-4 | ? | ? | ? | ? | ? | ? | not tested |
|
||||
|
||||
Not every SoundTouch shares one firmware image, so treat a `?` as genuinely
|
||||
unknown. In particular, do not assume a model is unaffected just because it is
|
||||
newer or older than a model that is.
|
||||
|
||||
## LAN access on co-processor chassis
|
||||
|
||||
On chassis with a BCO co-processor, inbound LAN traffic reaches the speaker's
|
||||
main Linux SoC only for a fixed set of Bose's *own* service ports. That list
|
||||
appears to be compiled into the co-processor's firmware, and AfterTouch's
|
||||
`:8000` is not on it, so a connection attempt never arrives at the SoC at
|
||||
all. On a verified ST20, `tcpdump -i eth0` on the speaker recorded **zero
|
||||
packets** for `:8000` while Bose's `:8090`, `:8091`, `:8200`, `:82`, `:8080`
|
||||
and `:17000` all answered normally from the same client.
|
||||
|
||||
This is not a firewall, and not something AfterTouch can fix by binding
|
||||
differently: the service already listens on `0.0.0.0:8000`, and the speaker's
|
||||
`iptables` is empty (there is no `nft` or `ebtables` at all).
|
||||
|
||||
The on-device installer works around it by redirecting one of the relayed
|
||||
ports to AfterTouch. **Credit for this technique goes to the
|
||||
[STR / SoundTouch Reborn](https://github.com/JRpersonal/streborn) project**,
|
||||
which documented and shipped it first (their agent uses the same entry port
|
||||
for the same reason); finding their prior art is what turned this from an
|
||||
apparent hardware dead end into a one-line fix:
|
||||
|
||||
```
|
||||
iptables -t nat -I PREROUTING 1 ! -i lo -p tcp --dport 17008 -j REDIRECT --to-ports 8000
|
||||
```
|
||||
|
||||
`17008` is Bose's `SoftwareUpdate` listener. Its cloud service no longer
|
||||
exists, so taking over its inbound traffic costs nothing in practice. Only
|
||||
external traffic is matched (`! -i lo`), so anything running on the speaker
|
||||
still reaches AfterTouch on `:8000` exactly as before.
|
||||
|
||||
The rule is re-applied by the init script on every start, so it survives
|
||||
reboots (confirmed on the ST20) without any background watchdog. It is
|
||||
removed again on `stop` and on uninstall.
|
||||
|
||||
The redirect is applied automatically on chassis that need it, and configured
|
||||
via `AFTERTOUCH_LAN_PORT` in `/opt/aftertouch/aftertouch.conf`:
|
||||
|
||||
| Value | Effect |
|
||||
|------------|-----------------------------------------------------------------|
|
||||
| `auto` | *(default)* redirect only where the co-processor blocks `:8000` |
|
||||
| `none` | never redirect; use an SSH tunnel instead |
|
||||
| *(a port)* | always redirect that inbound port to AfterTouch |
|
||||
|
||||
Two caveats worth knowing:
|
||||
|
||||
- **Account linking still prefers the SSH tunnel.** Spotify only accepts
|
||||
`https://` or *loopback* OAuth redirect URIs, so `http://localhost:8000`
|
||||
through a tunnel works for linking where a plain LAN address does not.
|
||||
- **The `streborn` project defaults to the same port** for the same reason. If
|
||||
you run both on one speaker, change `AFTERTOUCH_LAN_PORT`.
|
||||
|
||||
## How to fill in a row
|
||||
|
||||
Run these from a machine on the same network (replace the address), then open
|
||||
an issue or PR with the output:
|
||||
|
||||
```bash
|
||||
# variant, moduleType, and whether an SCM/SMSC component is listed
|
||||
curl -s http://<speaker-ip>:8090/info
|
||||
|
||||
# is AfterTouch's own port reachable directly? (only meaningful once
|
||||
# AfterTouch is installed on the device)
|
||||
curl -v --max-time 5 http://<speaker-ip>:8000/health
|
||||
|
||||
# which Bose ports the chassis relays at all
|
||||
for p in 82 8080 8090 8091 8200 17000 17008; do
|
||||
printf '%s: ' "$p"
|
||||
curl -s -o /dev/null -w '%{http_code}\n' --max-time 3 "http://<speaker-ip>:$p/" || echo unreachable
|
||||
done
|
||||
```
|
||||
|
||||
And on the speaker itself, if you have SSH access:
|
||||
|
||||
```bash
|
||||
has-bco; echo "has-bco exit status: $?" # 0 = BCO co-processor present
|
||||
cat /proc/module_type /proc/variant
|
||||
```
|
||||
@@ -0,0 +1,179 @@
|
||||
---
|
||||
title: "Player: Sources and Selection State"
|
||||
---
|
||||
How the embedded web player (`soundtouch-player`, and the same UI served by
|
||||
`soundtouch-service`) decides what a source button does, and how it decides
|
||||
whether a selection worked.
|
||||
|
||||
Both questions have non-obvious answers, learned from real hardware. This page
|
||||
records what the speaker actually does, so the behaviour is not re-derived or
|
||||
accidentally undone.
|
||||
|
||||
## Not every advertised source can be selected
|
||||
|
||||
A speaker's `/sources` lists what it knows about, each with a `status`. The
|
||||
player renders every `status="READY"` entry as a button. That set is not
|
||||
uniform: some entries are **inputs**, some are **providers**.
|
||||
|
||||
An **input** can be selected on its own. `AUX`, `BLUETOOTH`, a `SPOTIFY`
|
||||
entry with a real `sourceAccount`: `POST /select` with just the source and
|
||||
account is meaningful, and the speaker resumes that input.
|
||||
|
||||
A **provider** cannot. `RADIO_BROWSER`, `TUNEIN` and `LOCAL_INTERNET_RADIO`
|
||||
need a station **ContentItem carrying a `Location`** (see
|
||||
`stations.ResolveContentItem`, which sets `type="stationurl"`). There is
|
||||
nothing for the speaker to resume from the source name alone.
|
||||
|
||||
All three are confirmed on hardware: `RADIO_BROWSER` and
|
||||
`LOCAL_INTERNET_RADIO` by the stub described below, `TUNEIN` by its resume
|
||||
path playing the station as intended.
|
||||
|
||||
`STORED_MUSIC` is a third case: one entry per media server, its
|
||||
`sourceAccount` being a server UDN. Selecting it identifies no track or
|
||||
container.
|
||||
|
||||
## What a bare select does to a provider
|
||||
|
||||
The speaker does not refuse. It answers `200`, and parks on a stub
|
||||
now-playing, while whatever was playing before **carries on**:
|
||||
|
||||
```xml
|
||||
<nowPlaying deviceID="..." source="RADIO_BROWSER" sourceAccount="">
|
||||
<ContentItem source="RADIO_BROWSER" type="" location="" isPresetable="false">
|
||||
<itemName>RADIO_BROWSER</itemName>
|
||||
</ContentItem>
|
||||
</nowPlaying>
|
||||
```
|
||||
|
||||
Four things identify the stub: no `playStatus`, empty `type`, empty
|
||||
`location`, and an `itemName` that just echoes the source name.
|
||||
|
||||
The speaker then reports that stub indefinitely. Observed on hardware: the
|
||||
player showed RadioBrowser while Spotify was audible, and a naive readback
|
||||
"confirmed" the selection because the reported source did match the one
|
||||
requested. `LOCAL_INTERNET_RADIO` produces a byte-identical stub.
|
||||
|
||||
This is speaker behaviour, not something the player or the service can fix
|
||||
after the fact. The only remedy is not to issue such a select.
|
||||
|
||||
## What the player does instead
|
||||
|
||||
| Source | Click behaviour | Resumes from Recents |
|
||||
|------------------------|-----------------------------------------------|----------------------|
|
||||
| `RADIO_BROWSER` | resume newest station, else open RadioBrowser | yes |
|
||||
| `TUNEIN` | resume newest station, else open TuneIn | yes |
|
||||
| `LOCAL_INTERNET_RADIO` | open Play URL | no |
|
||||
| `STORED_MUSIC` | open Library | no |
|
||||
| anything else | `POST /select` as before | n/a |
|
||||
|
||||
Resuming replays the newest Recents entry for that source, using that entry's
|
||||
own ContentItem: the real item the speaker was given, `Location` included.
|
||||
|
||||
**`LOCAL_INTERNET_RADIO` deliberately does not resume.** AfterTouch plays its
|
||||
own one-shot audio through that source: TTS and the notification ding both go
|
||||
out over `/custom/v1/playback/`. Its Recents therefore mix notifications with
|
||||
stations, and on a test speaker the *only* entry was "AfterTouch ding", so
|
||||
resuming played the ding. The announcement path is distinguishable from Play
|
||||
URL's `bmx.BuildOrionLocation`, but it also carries CLI URL playback, and any
|
||||
future audio-injecting feature would have to remember to stay clear of it.
|
||||
Opening Play URL does not depend on classifying what is in Recents.
|
||||
|
||||
`ALEXA` is advertised `READY` too and is deliberately left alone: it cannot be
|
||||
tested on the hardware available, and guessing at its behaviour risks breaking
|
||||
a source that works today. The backstop below covers it instead.
|
||||
|
||||
### The backstop
|
||||
|
||||
The table above only covers sources known to need it, and a source list is
|
||||
whatever the speaker chooses to advertise. So the readback additionally
|
||||
refuses to *confirm* the stub itself, wherever it comes from: a now-playing
|
||||
naming the requested source but with no `Location`, no `PlayStatus`, and an
|
||||
`ItemName` equal to the source is reported as a failure.
|
||||
|
||||
All three conditions are required together. A physical input reports no
|
||||
location and no item name of its own yet is genuinely playing, so any single
|
||||
condition alone would reject real selections.
|
||||
|
||||
## How a selection is confirmed
|
||||
|
||||
`POST /select` returning `200` proves nothing: the speaker can reject a source
|
||||
seconds later, surfacing as a transition to an error source
|
||||
(`INVALID_SOURCE`, `*_ERROR`). So the player posts once, then watches.
|
||||
|
||||
- The **event stream** is the primary watcher. A `nowPlayingUpdated` event
|
||||
reports a late rejection as it happens, and the player turns it into a
|
||||
failure.
|
||||
- **Bounded readbacks** at 2s, 5s and 10s are the fallback for a speaker whose
|
||||
events are not arriving. They stop as soon as a confirmation arrives *and*
|
||||
the readback reports a live event stream, so a confirmed selection normally
|
||||
costs one request rather than three. That signal is `webSocketConnected`,
|
||||
which reports the service's own socket to the speaker; it is opened lazily
|
||||
on first fetch or control of a device, so the very first click after
|
||||
loading one can still take all three.
|
||||
- Readbacks use `GET /devices/{id}/now-playing`, which refreshes only
|
||||
`/now_playing`. The full device fetch runs a complete status poll: six
|
||||
sequential speaker calls plus `/getGroup` on a stereo-capable model, to
|
||||
answer one question, against a device that may be slow precisely because
|
||||
something is wrong.
|
||||
|
||||
Outcomes are `pending`, `provisional-confirmed`, `final-confirmed`,
|
||||
`unverified` and `failed`, shown in a live region under the source list. A
|
||||
confirmation from a push event is never retracted by a later failed readback.
|
||||
|
||||
### Definitive versus uncertain failures
|
||||
|
||||
A rejected write is not always proof the command never landed:
|
||||
|
||||
- **4xx** is produced before the service contacts the speaker (unknown device,
|
||||
unparseable body, empty source). The command provably never went out, so the
|
||||
failure is reported immediately.
|
||||
- **5xx and transport errors** are ambiguous. `handleSourceControl` reports a
|
||||
failed `Client.SelectSource` through `sendControlResponse`, which maps any
|
||||
speaker-call error to 500, and a request that timed out *after* the speaker
|
||||
already switched looks identical to one it never received. The readbacks
|
||||
keep running and the reason is carried into whatever outcome they reach.
|
||||
|
||||
## Ordering: revisions and epochs
|
||||
|
||||
Status reaches the browser three ways — a full `devices` snapshot, a
|
||||
`status_update` delta, and REST refreshes — with no inherent ordering. Two
|
||||
fields fix that:
|
||||
|
||||
- `revision` advances on every projection, so a frame no newer than what the
|
||||
browser holds is dropped.
|
||||
- `nowPlayingRevision` is the now-playing field's own generation. `revision`
|
||||
alone cannot answer "did now-playing actually change?", because any other
|
||||
field's merge advances it; a selection waiting for confirmation needs
|
||||
exactly that distinction.
|
||||
|
||||
Revisions are per-connection and restart at 0, so they are only comparable
|
||||
within one **`epoch`**, which identifies the connection that produced the
|
||||
status. Without it, a device backed by a fresh connection would publish
|
||||
revisions the browser rejects forever, freezing that device's display until
|
||||
reload. Epochs are seeded from the wall clock and forced strictly increasing,
|
||||
so they keep rising across a service restart, and are in milliseconds because
|
||||
the browser compares them as JSON numbers.
|
||||
|
||||
## Source inventory staleness
|
||||
|
||||
`sourcesStale` marks an inventory the speaker has stopped confirming; the
|
||||
player keeps showing it but disables the buttons.
|
||||
|
||||
It is set after **two consecutive** failed `/sources` reads, not one. A single
|
||||
dropped read is not evidence the list is wrong, and marking it stale
|
||||
immediately disabled every source button on a transient hiccup. This mirrors
|
||||
`offlineFailureThreshold`, which debounces connectivity the same way. A
|
||||
successful read clears the marker and resets the count.
|
||||
|
||||
Successful reads remain ordered by generation, so an older one cannot
|
||||
overwrite a newer one. Failures are not ordered: a failure carries no
|
||||
inventory, so spending the generation on it would let a failed read discard a
|
||||
concurrent successful one.
|
||||
|
||||
## Related
|
||||
|
||||
- [Source Selection Guide](SOURCE-SELECTION.md) — the `/select` endpoint and
|
||||
the client library
|
||||
- [WebSocket Events](WEBSOCKET-EVENTS.md) — the event stream the confirmation
|
||||
relies on
|
||||
- [Radio Browser](radio-browser.md) — the RadioBrowser provider
|
||||
@@ -29,17 +29,34 @@ The Bose SoundTouch Go client provides comprehensive source selection functional
|
||||
|
||||
**Response**: HTTP 200 OK (no body) on success
|
||||
|
||||
**Supported Sources:**
|
||||
- `SPOTIFY` - Spotify streaming service
|
||||
**Sources selectable this way:**
|
||||
- `SPOTIFY` - Spotify streaming service (with a real `sourceAccount`)
|
||||
- `BLUETOOTH` - Bluetooth audio input
|
||||
- `AUX` - Auxiliary input (3.5mm jack)
|
||||
- `TUNEIN` - TuneIn internet radio
|
||||
- `PANDORA` - Pandora streaming service
|
||||
- `AMAZON` - Amazon Music
|
||||
- `IHEARTRADIO` - iHeartRadio streaming
|
||||
- `STORED_MUSIC` - Local/network stored music
|
||||
- `AIRPLAY` - Apple AirPlay (device dependent)
|
||||
- `PANDORA`, `AMAZON`, `IHEARTRADIO` - streaming services (with an account)
|
||||
|
||||
### Sources that need a ContentItem instead
|
||||
|
||||
A bare `/select` carrying only a source and account is **not** enough for
|
||||
every source a speaker advertises. These need a full ContentItem with a
|
||||
`Location`, built by `stations.ResolveContentItem` with `type="stationurl"`:
|
||||
|
||||
- `TUNEIN` - TuneIn internet radio
|
||||
- `RADIO_BROWSER` - [RadioBrowser](radio-browser.md) internet radio directory
|
||||
- `LOCAL_INTERNET_RADIO` - stream URLs, including Play URL and TTS output
|
||||
- `STORED_MUSIC` - one entry per media server; selecting it names no track
|
||||
|
||||
Given a bare select for one of these the speaker does **not** report an
|
||||
error. It answers `200`, parks on a stub now-playing with no `playStatus`,
|
||||
empty `type` and `location`, and an `itemName` echoing the source name, and
|
||||
carries on playing whatever it was playing. It then reports that stub
|
||||
indefinitely, so callers that check `/now_playing` see the source they asked
|
||||
for while the audio is something else.
|
||||
|
||||
Use `SelectContentItem` with a real `Location` for these, and see
|
||||
[Player: Sources and Selection State](PLAYER-SOURCE-BEHAVIOUR.md) for the
|
||||
stub's full signature and how the web player avoids it.
|
||||
|
||||
## Client Library Usage
|
||||
|
||||
@@ -158,20 +175,20 @@ soundtouch-cli -host 192.0.2.100 -aux
|
||||
|
||||
### CLI Flags
|
||||
|
||||
| Flag | Description | Example |
|
||||
|------|-------------|---------|
|
||||
| `-select-source <source>` | Select audio source | `-select-source SPOTIFY` |
|
||||
| `-source-account <account>` | Account for streaming services | `-source-account "user123"` |
|
||||
| `-spotify` | Select Spotify source | `-spotify -source-account "user"` |
|
||||
| `-bluetooth` | Select Bluetooth source | `-bluetooth` |
|
||||
| `-aux` | Select AUX input | `-aux` |
|
||||
| Flag | Description | Example |
|
||||
|-----------------------------|--------------------------------|-----------------------------------|
|
||||
| `-select-source <source>` | Select audio source | `-select-source SPOTIFY` |
|
||||
| `-source-account <account>` | Account for streaming services | `-source-account "user123"` |
|
||||
| `-spotify` | Select Spotify source | `-spotify -source-account "user"` |
|
||||
| `-bluetooth` | Select Bluetooth source | `-bluetooth` |
|
||||
| `-aux` | Select AUX input | `-aux` |
|
||||
|
||||
## Source Account Information
|
||||
|
||||
### When Source Accounts are Required
|
||||
|
||||
- **Spotify**: Required for multi-account setups
|
||||
- **Pandora**: Required for account-based access
|
||||
- **Pandora**: Required for account-based access
|
||||
- **TuneIn**: Optional, may improve personalization
|
||||
- **Amazon Music**: Required for account access
|
||||
- **Bluetooth/AUX**: Not required (leave empty)
|
||||
@@ -259,11 +276,11 @@ func selectWithConfig(client *client.Client, config SourceConfig) error {
|
||||
|
||||
### Common Error Codes
|
||||
|
||||
| Code | Name | Description | Solution |
|
||||
|------|------|-------------|----------|
|
||||
| 1005 | UNKNOWN_SOURCE_ERROR | Invalid or unavailable source | Check available sources first |
|
||||
| 1006 | SOURCE_UNAVAILABLE | Source temporarily unavailable | Try again later |
|
||||
| 1007 | ACCOUNT_ERROR | Invalid account for source | Check account name format |
|
||||
| Code | Name | Description | Solution |
|
||||
|------|----------------------|--------------------------------|-------------------------------|
|
||||
| 1005 | UNKNOWN_SOURCE_ERROR | Invalid or unavailable source | Check available sources first |
|
||||
| 1006 | SOURCE_UNAVAILABLE | Source temporarily unavailable | Try again later |
|
||||
| 1007 | ACCOUNT_ERROR | Invalid account for source | Check account name format |
|
||||
|
||||
### Troubleshooting Tips
|
||||
|
||||
@@ -347,13 +364,16 @@ The implementation follows the official SoundTouch API:
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [Player: Sources and Selection State](PLAYER-SOURCE-BEHAVIOUR.md) - which
|
||||
sources accept a bare select, and how a selection is confirmed
|
||||
|
||||
- **[API Endpoints Overview](API-ENDPOINTS.md)** - Complete API reference
|
||||
- **[Sources](https://github.com/gesellix/Bose-SoundTouch/blob/main/pkg/models/sources.go)** - Source model implementation
|
||||
- **[Sources](https://github.com/gesellix/Bose-SoundTouch/blob/main/pkg/models/sources.go)** - Source model implementation
|
||||
- **[Now Playing](https://github.com/gesellix/Bose-SoundTouch/blob/main/pkg/models/nowplaying.go)** - ContentItem model
|
||||
- **[Client Usage Examples](https://github.com/gesellix/Bose-SoundTouch/blob/main/cmd/soundtouch-cli/main.go)** - CLI implementation reference
|
||||
|
||||
---
|
||||
|
||||
**Implementation Date**: 2026-01-09
|
||||
**Status**: ✅ Complete and tested
|
||||
**Implementation Date**: 2026-01-09
|
||||
**Status**: ✅ Complete and tested
|
||||
**Real Device Validation**: SoundTouch 10, SoundTouch 20
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
module navigation-station-demo
|
||||
|
||||
go 1.26.5
|
||||
go 1.27.1
|
||||
|
||||
require github.com/gesellix/bose-soundtouch v0.118.0
|
||||
require github.com/gesellix/bose-soundtouch v0.128.0
|
||||
|
||||
require github.com/gorilla/websocket v1.5.3 // indirect
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
module preset-management-example
|
||||
|
||||
go 1.26.5
|
||||
go 1.27.1
|
||||
|
||||
require github.com/gesellix/bose-soundtouch v0.118.0
|
||||
require github.com/gesellix/bose-soundtouch v0.128.0
|
||||
|
||||
require github.com/gorilla/websocket v1.5.3 // indirect
|
||||
|
||||
|
||||
@@ -1,40 +1,38 @@
|
||||
module github.com/gesellix/bose-soundtouch
|
||||
|
||||
go 1.26.5
|
||||
go 1.27.1
|
||||
|
||||
require (
|
||||
filippo.io/age v1.3.1
|
||||
filippo.io/age v1.3.2
|
||||
github.com/chromedp/chromedp v0.16.0
|
||||
github.com/go-chi/chi/v5 v5.3.1
|
||||
github.com/go-chi/chi/v5 v5.3.2
|
||||
github.com/google/gopacket v1.1.19
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/hashicorp/mdns v1.0.7
|
||||
github.com/miekg/dns v1.1.72
|
||||
github.com/miekg/dns v1.1.73
|
||||
github.com/russross/blackfriday/v2 v2.1.0
|
||||
github.com/sergi/go-diff v1.4.0
|
||||
github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c
|
||||
github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef
|
||||
github.com/urfave/cli/v2 v2.27.7
|
||||
golang.org/x/crypto v0.54.0
|
||||
golang.org/x/net v0.57.0
|
||||
golang.org/x/crypto v0.56.0
|
||||
golang.org/x/mod v0.40.0
|
||||
golang.org/x/net v0.58.0
|
||||
golang.org/x/term v0.45.0
|
||||
)
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.2.0 // indirect
|
||||
filippo.io/hpke v0.4.0 // indirect
|
||||
github.com/chromedp/cdproto v0.0.0-20260714215040-dc233986426f // indirect
|
||||
github.com/chromedp/cdproto v0.0.0-20260804232424-e85f50dbfd32 // indirect
|
||||
github.com/chromedp/sysutil v1.1.0 // indirect
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect
|
||||
github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68 // indirect
|
||||
github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 // indirect
|
||||
github.com/gobwas/httphead v0.1.0 // indirect
|
||||
github.com/gobwas/pool v0.2.1 // indirect
|
||||
github.com/gobwas/ws v1.4.0 // indirect
|
||||
github.com/xrash/smetrics v0.0.0-20250705151800-55b8f293f342 // indirect
|
||||
golang.org/x/image v0.44.0 // indirect
|
||||
golang.org/x/mod v0.38.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/image v0.45.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
golang.org/x/tools v0.48.0 // indirect
|
||||
golang.org/x/text v0.41.0 // indirect
|
||||
)
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
c2sp.org/CCTV/age v0.0.0-20251208015420-e9274a7bdbfd h1:ZLsPO6WdZ5zatV4UfVpr7oAwLGRZ+sebTUruuM4Ra3M=
|
||||
c2sp.org/CCTV/age v0.0.0-20251208015420-e9274a7bdbfd/go.mod h1:SrHC2C7r5GkDk8R+NFVzYy/sdj0Ypg9htaPXQq5Cqeo=
|
||||
filippo.io/age v1.3.1 h1:hbzdQOJkuaMEpRCLSN1/C5DX74RPcNCk6oqhKMXmZi0=
|
||||
filippo.io/age v1.3.1/go.mod h1:EZorDTYUxt836i3zdori5IJX/v2Lj6kWFU0cfh6C0D4=
|
||||
c2sp.org/CCTV/age v0.0.0-20260829155415-4448f2097b2d h1:Blprhc2SbChNZtWcU+BLTM4YdoqYAS9V7cJgOwJKyAs=
|
||||
c2sp.org/CCTV/age v0.0.0-20260829155415-4448f2097b2d/go.mod h1:SrHC2C7r5GkDk8R+NFVzYy/sdj0Ypg9htaPXQq5Cqeo=
|
||||
filippo.io/age v1.3.2 h1:r6RSZLFSMm6rzKepZ7ZAYkKCu14f3/Me8c7uKYh7C8c=
|
||||
filippo.io/age v1.3.2/go.mod h1:TH/Yr2sSRhCKbaH4XPxpUV0Us8Gv6txYUpiZQWz8Evk=
|
||||
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
|
||||
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
|
||||
filippo.io/hpke v0.4.0 h1:p575VVQ6ted4pL+it6M00V/f2qTZITO0zgmdKCkd5+A=
|
||||
filippo.io/hpke v0.4.0/go.mod h1:EmAN849/P3qdeK+PCMkDpDm83vRHM5cDipBJ8xbQLVY=
|
||||
github.com/chromedp/cdproto v0.0.0-20260714215040-dc233986426f h1:0Z1zcSLEmnj2c2CmJYBqewtS6pxhB39bNWUSEUAWjgk=
|
||||
github.com/chromedp/cdproto v0.0.0-20260714215040-dc233986426f/go.mod h1:RwFsSODCtFExll+GhHM6R92SARHR3Z3oipaxLHj46C0=
|
||||
github.com/chromedp/cdproto v0.0.0-20260804232424-e85f50dbfd32 h1:6JI+JS7Zef+bMzZQ+OgzTHf79v3GqdvP6rD0FaP9CMk=
|
||||
github.com/chromedp/cdproto v0.0.0-20260804232424-e85f50dbfd32/go.mod h1:RwFsSODCtFExll+GhHM6R92SARHR3Z3oipaxLHj46C0=
|
||||
github.com/chromedp/chromedp v0.16.0 h1:rOO4deOm4CbZgBCa8mD9g2rDyIoNs0BkgvNrlbp5ouk=
|
||||
github.com/chromedp/chromedp v0.16.0/go.mod h1:rbuGKFT1vMcFcFqKfPIO1GpX/N+2s8onm2qMxZLbU5U=
|
||||
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
|
||||
@@ -17,18 +17,16 @@ github.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6N
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
|
||||
github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||
github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68 h1:KZaTBSyshWX3MP5jukJcNSuXDQTO+rNpt0J564dX/eg=
|
||||
github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg=
|
||||
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
|
||||
github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||
github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 h1:UADEEmDKgfXbtnGJZ97beY5XLo9ZechG1nlU4KnRrkE=
|
||||
github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg=
|
||||
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
|
||||
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
|
||||
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
|
||||
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
|
||||
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
|
||||
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8=
|
||||
github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
@@ -40,8 +38,8 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80 h1:6Yzfa6GP0rIo/kULo2bwGEkFvCePZ3qHDDTC3/J9Swo=
|
||||
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs=
|
||||
github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
|
||||
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
|
||||
github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE=
|
||||
github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ=
|
||||
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw=
|
||||
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
@@ -63,18 +61,18 @@ github.com/xrash/smetrics v0.0.0-20250705151800-55b8f293f342 h1:FnBeRrxr7OU4VvAz
|
||||
github.com/xrash/smetrics v0.0.0-20250705151800-55b8f293f342/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/image v0.44.0 h1:+tDekMZED9+LrtB3G5xzRggpVh9CARjZqROla3R3R+I=
|
||||
golang.org/x/image v0.44.0/go.mod h1:V8K3KE9KKKE+pLpQDOeN18w9oacNSvy1tDOirTu4xtY=
|
||||
golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y=
|
||||
golang.org/x/crypto v0.56.0/go.mod h1:OMW5y6CY9l38uPLmxU6l6pwcXp1obtLo3e6gT7gQR2I=
|
||||
golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0=
|
||||
golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4=
|
||||
golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
|
||||
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
|
||||
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
|
||||
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
|
||||
golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs=
|
||||
golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
@@ -86,11 +84,9 @@ golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
|
||||
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
|
||||
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
||||
Generated
+7
@@ -7,6 +7,7 @@
|
||||
"name": "@gesellix/bose-soundtouch",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-module-shims": "2.8.4",
|
||||
"htm": "3.1.1",
|
||||
"preact": "10.29.8"
|
||||
},
|
||||
@@ -14,6 +15,12 @@
|
||||
"node": ">=24.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/es-module-shims": {
|
||||
"version": "2.8.4",
|
||||
"resolved": "https://registry.npmjs.org/es-module-shims/-/es-module-shims-2.8.4.tgz",
|
||||
"integrity": "sha512-ea5srn5L89PWVad6Qle6r2kg+HvvLiL/GHqgNx06eFrkERHkrTFWaqo1w8Sd+XI3Xr0iAG5x3ZQ7mQ/hnQzNpA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/htm": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/htm/-/htm-3.1.1.tgz",
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
"node": ">=24.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"es-module-shims": "2.8.4",
|
||||
"htm": "3.1.1",
|
||||
"preact": "10.29.8"
|
||||
}
|
||||
|
||||
+334
-12
@@ -144,6 +144,7 @@ package client
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
@@ -169,6 +170,11 @@ type Client struct {
|
||||
avTransportURLOverride string
|
||||
}
|
||||
|
||||
// ErrMutationOutcomeUnknown reports that a state-changing GET may have reached
|
||||
// the speaker, but its authoritative response could not be verified. Callers
|
||||
// must read device state back rather than retrying the mutation blindly.
|
||||
var ErrMutationOutcomeUnknown = errors.New("state-changing GET outcome is unknown")
|
||||
|
||||
// Config holds configuration for the SoundTouch client
|
||||
type Config struct {
|
||||
Host string
|
||||
@@ -790,7 +796,14 @@ func (c *Client) DecreaseBalance(amount int) (*models.Balance, error) {
|
||||
return c.GetBalance()
|
||||
}
|
||||
|
||||
// SelectSource selects an audio source using the /select endpoint
|
||||
// SelectSource selects an audio source using the /select endpoint.
|
||||
//
|
||||
// Only sources that are inputs in their own right can be selected this way:
|
||||
// AUX, BLUETOOTH, or a streaming service with a real sourceAccount. Provider
|
||||
// sources (TUNEIN, RADIO_BROWSER, LOCAL_INTERNET_RADIO) and STORED_MUSIC need
|
||||
// SelectContentItem with a Location instead; a bare select leaves such a
|
||||
// speaker reporting a source it is not playing. See
|
||||
// docs/content/docs/reference/PLAYER-SOURCE-BEHAVIOUR.md.
|
||||
func (c *Client) SelectSource(source, sourceAccount string) error {
|
||||
// Validate source parameter
|
||||
if source == "" {
|
||||
@@ -855,7 +868,15 @@ func (c *Client) SelectAux() error {
|
||||
return c.SelectSource("AUX", "")
|
||||
}
|
||||
|
||||
// SelectTuneIn is a convenience method to select TuneIn source
|
||||
// SelectTuneIn is a convenience method to select TuneIn source.
|
||||
//
|
||||
// This sends a bare select, with no station. A speaker does not report an
|
||||
// error for that: it answers 200, parks on a stub now-playing (no playStatus,
|
||||
// empty type and location, itemName echoing the source name) and carries on
|
||||
// playing whatever it was playing, then reports that stub indefinitely. To
|
||||
// actually play something use SelectContentItem with a ContentItem carrying a
|
||||
// Location, as stations.ResolveContentItem builds. See
|
||||
// docs/content/docs/reference/PLAYER-SOURCE-BEHAVIOUR.md.
|
||||
func (c *Client) SelectTuneIn(sourceAccount string) error {
|
||||
return c.SelectSource("TUNEIN", sourceAccount)
|
||||
}
|
||||
@@ -1021,6 +1042,152 @@ func (c *Client) SetClockTimeNow() error {
|
||||
return c.SetClockTime(request)
|
||||
}
|
||||
|
||||
// GetSystemTimeout retrieves the power-saving setting from /systemtimeout.
|
||||
func (c *Client) GetSystemTimeout() (*models.SystemTimeout, error) {
|
||||
var setting models.SystemTimeout
|
||||
if err := c.get("/systemtimeout", &setting); err != nil {
|
||||
return nil, fmt.Errorf("failed to get system timeout: %w", err)
|
||||
}
|
||||
|
||||
return &setting, nil
|
||||
}
|
||||
|
||||
// SetSystemTimeout updates /systemtimeout. HTTP success only confirms that the
|
||||
// request was accepted; callers must read the setting back before reporting it.
|
||||
func (c *Client) SetSystemTimeout(setting *models.SystemTimeout) error {
|
||||
if err := setting.Validate(); err != nil {
|
||||
return fmt.Errorf("invalid system timeout request: %w", err)
|
||||
}
|
||||
|
||||
if err := c.post("/systemtimeout", setting); err != nil {
|
||||
return fmt.Errorf("failed to set system timeout: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetRebroadcastLatencyMode retrieves /rebroadcastlatencymode.
|
||||
func (c *Client) GetRebroadcastLatencyMode() (*models.RebroadcastLatencyMode, error) {
|
||||
var setting models.RebroadcastLatencyMode
|
||||
if err := c.get("/rebroadcastlatencymode", &setting); err != nil {
|
||||
return nil, fmt.Errorf("failed to get rebroadcast latency mode: %w", err)
|
||||
}
|
||||
|
||||
return &setting, nil
|
||||
}
|
||||
|
||||
// SetRebroadcastLatencyMode updates /rebroadcastlatencymode. HTTP success only
|
||||
// confirms request acceptance; callers must read the setting back.
|
||||
func (c *Client) SetRebroadcastLatencyMode(mode models.RebroadcastLatencyModeValue) error {
|
||||
request := &models.RebroadcastLatencyModeRequest{Mode: mode}
|
||||
if err := request.Validate(); err != nil {
|
||||
return fmt.Errorf("invalid rebroadcast latency mode request: %w", err)
|
||||
}
|
||||
|
||||
if err := c.post("/rebroadcastlatencymode", request); err != nil {
|
||||
return fmt.Errorf("failed to set rebroadcast latency mode: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetLanguage retrieves the current integer system language from /language.
|
||||
// Unknown codes are returned unchanged for compatibility with newer firmware.
|
||||
func (c *Client) GetLanguage() (*models.SystemLanguage, error) {
|
||||
var language models.SystemLanguage
|
||||
if err := c.get("/language", &language); err != nil {
|
||||
return nil, fmt.Errorf("failed to get system language: %w", err)
|
||||
}
|
||||
|
||||
return &language, nil
|
||||
}
|
||||
|
||||
// SetLanguage updates /language. HTTP success only confirms request acceptance;
|
||||
// callers must read the language back before reporting the change.
|
||||
func (c *Client) SetLanguage(code models.LanguageCode) error {
|
||||
request := &models.SystemLanguage{Code: code}
|
||||
if err := request.Validate(); err != nil {
|
||||
return fmt.Errorf("invalid system language request: %w", err)
|
||||
}
|
||||
|
||||
if err := c.post("/language", request); err != nil {
|
||||
return fmt.Errorf("failed to set system language: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetBluetoothInfo retrieves the speaker adapter information from /bluetoothInfo.
|
||||
func (c *Client) GetBluetoothInfo() (*models.BluetoothInfo, error) {
|
||||
var info models.BluetoothInfo
|
||||
if err := c.get("/bluetoothInfo", &info); err != nil {
|
||||
return nil, fmt.Errorf("failed to get Bluetooth info: %w", err)
|
||||
}
|
||||
|
||||
return &info, nil
|
||||
}
|
||||
|
||||
// RenameSource updates the source display name through /nameSource. HTTP
|
||||
// success only confirms request acceptance; callers must read sources back.
|
||||
func (c *Client) RenameSource(source, sourceAccount, itemName string) error {
|
||||
request := &models.SourceRenameRequest{
|
||||
Source: source,
|
||||
SourceAccount: sourceAccount,
|
||||
ItemName: itemName,
|
||||
}
|
||||
if err := request.Validate(); err != nil {
|
||||
return fmt.Errorf("invalid source rename request: %w", err)
|
||||
}
|
||||
|
||||
if err := c.post("/nameSource", request); err != nil {
|
||||
return fmt.Errorf("failed to rename source: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnterPairingMode requests the firmware's legacy general pairing mode through
|
||||
// its state-changing GET endpoint.
|
||||
func (c *Client) EnterPairingMode() error {
|
||||
if err := c.mutatingGetConfirmStatus("/enterPairingMode"); err != nil {
|
||||
return fmt.Errorf("failed to enter pairing mode: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnterBluetoothPairing requests Bluetooth discoverable mode through the
|
||||
// Bluetooth-specific state-changing GET endpoint. Callers must verify
|
||||
// discoverability through a subsequent now-playing read.
|
||||
func (c *Client) EnterBluetoothPairing() error {
|
||||
if err := c.mutatingGetConfirmStatus("/enterBluetoothPairing"); err != nil {
|
||||
return fmt.Errorf("failed to enter Bluetooth pairing mode: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearPairedList requests the firmware's legacy general paired-list clearing
|
||||
// through its state-changing GET endpoint.
|
||||
func (c *Client) ClearPairedList() error {
|
||||
if err := c.mutatingGetConfirmStatus("/clearPairedList"); err != nil {
|
||||
return fmt.Errorf("failed to clear paired list: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearBluetoothPaired requests removal of Bluetooth pairings through the
|
||||
// Bluetooth-specific state-changing GET endpoint. The firmware exposes no
|
||||
// paired-list readback, so HTTP success alone does not verify physical state.
|
||||
func (c *Client) ClearBluetoothPaired() error {
|
||||
if err := c.mutatingGetConfirmStatus("/clearBluetoothPaired"); err != nil {
|
||||
return fmt.Errorf("failed to clear Bluetooth paired devices: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetClockDisplay retrieves clock display settings from the /clockDisplay endpoint
|
||||
func (c *Client) GetClockDisplay() (*models.ClockDisplay, error) {
|
||||
var clockDisplay models.ClockDisplay
|
||||
@@ -1105,6 +1272,10 @@ func (c *Client) Host() string {
|
||||
|
||||
// get performs a GET request and unmarshals the XML response
|
||||
func (c *Client) get(endpoint string, result interface{}) error {
|
||||
return c.getWithHTTPClient(c.httpClient, endpoint, result)
|
||||
}
|
||||
|
||||
func (c *Client) getWithHTTPClient(httpClient *http.Client, endpoint string, result interface{}) error {
|
||||
url := c.baseURL + endpoint
|
||||
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
@@ -1115,7 +1286,7 @@ func (c *Client) get(endpoint string, result interface{}) error {
|
||||
req.Header.Set("User-Agent", c.userAgent)
|
||||
req.Header.Set("Accept", "application/xml")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to execute request: %w", err)
|
||||
}
|
||||
@@ -1151,6 +1322,148 @@ func (c *Client) get(endpoint string, result interface{}) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// newOneShotHTTPClient clones the client's transport with keep-alives
|
||||
// disabled, so a firmware-required state-changing GET runs exactly once at
|
||||
// the HTTP transport layer instead of risking an automatic replay by
|
||||
// net/http after an ambiguous failure on a reused connection. The caller
|
||||
// owns the returned transport's lifetime and must close its idle
|
||||
// connections once done (defer oneShotTransport.CloseIdleConnections()).
|
||||
func (c *Client) newOneShotHTTPClient() (client *http.Client, oneShotTransport *http.Transport, err error) {
|
||||
baseTransport := c.httpClient.Transport
|
||||
if baseTransport == nil {
|
||||
baseTransport = http.DefaultTransport
|
||||
}
|
||||
|
||||
transport, ok := baseTransport.(*http.Transport)
|
||||
if !ok {
|
||||
return nil, nil, errors.New("state-changing GET requires a cloneable HTTP transport")
|
||||
}
|
||||
|
||||
oneShotTransport = transport.Clone()
|
||||
oneShotTransport.DisableKeepAlives = true
|
||||
|
||||
return &http.Client{
|
||||
Transport: oneShotTransport,
|
||||
Timeout: c.httpClient.Timeout,
|
||||
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}, oneShotTransport, nil
|
||||
}
|
||||
|
||||
// mutatingGet performs a firmware-required state-changing GET exactly once at
|
||||
// the HTTP transport layer, unmarshaling the response into result. A fresh
|
||||
// connection prevents net/http from automatically replaying the request
|
||||
// after an ambiguous failure on a reused connection.
|
||||
func (c *Client) mutatingGet(endpoint string, result interface{}) error {
|
||||
oneShotClient, oneShotTransport, err := c.newOneShotHTTPClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer oneShotTransport.CloseIdleConnections()
|
||||
|
||||
return c.getWithHTTPClient(oneShotClient, endpoint, result)
|
||||
}
|
||||
|
||||
// mutatingGetConfirmStatus performs the same one-shot, firmware-required
|
||||
// state-changing GET as mutatingGet, for endpoints that return no meaningful
|
||||
// body to unmarshal -- confirmation instead comes from the device echoing
|
||||
// back <status>{endpoint}</status>.
|
||||
func (c *Client) mutatingGetConfirmStatus(endpoint string) error {
|
||||
oneShotClient, oneShotTransport, err := c.newOneShotHTTPClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer oneShotTransport.CloseIdleConnections()
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, c.baseURL+endpoint, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("User-Agent", c.userAgent)
|
||||
req.Header.Set("Accept", "application/xml")
|
||||
|
||||
resp, err := oneShotClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: failed to execute request: %w", ErrMutationOutcomeUnknown, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: failed to read response: %w", ErrMutationOutcomeUnknown, err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
if apiErr := mutationAPIError(body); apiErr != nil {
|
||||
return apiErr
|
||||
}
|
||||
|
||||
return fmt.Errorf(
|
||||
"%w: API request failed with status %d: %s",
|
||||
ErrMutationOutcomeUnknown,
|
||||
resp.StatusCode,
|
||||
string(body),
|
||||
)
|
||||
}
|
||||
|
||||
if apiErr := mutationAPIError(body); apiErr != nil {
|
||||
return apiErr
|
||||
}
|
||||
|
||||
return validateMutationStatus(body, endpoint)
|
||||
}
|
||||
|
||||
func mutationAPIError(body []byte) error {
|
||||
switch mutationResponseRoot(body) {
|
||||
case "errors":
|
||||
var errs models.ErrorsResponse
|
||||
if err := xml.Unmarshal(body, &errs); err == nil && len(errs.Errors) > 0 {
|
||||
return &errs
|
||||
}
|
||||
case "error":
|
||||
var apiError models.APIError
|
||||
if err := xml.Unmarshal(body, &apiError); err == nil && apiError.Message != "" {
|
||||
return &apiError
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func mutationResponseRoot(body []byte) string {
|
||||
var root struct {
|
||||
XMLName xml.Name
|
||||
}
|
||||
if xml.Unmarshal(body, &root) != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return root.XMLName.Local
|
||||
}
|
||||
|
||||
func validateMutationStatus(body []byte, endpoint string) error {
|
||||
var status struct {
|
||||
XMLName xml.Name `xml:"status"`
|
||||
Value string `xml:",chardata"`
|
||||
}
|
||||
if err := xml.Unmarshal(body, &status); err != nil {
|
||||
return fmt.Errorf("%w: malformed XML response: %w", ErrMutationOutcomeUnknown, err)
|
||||
}
|
||||
|
||||
if strings.TrimSpace(status.Value) != endpoint {
|
||||
return fmt.Errorf(
|
||||
"%w: expected <status>%s</status>, got %s",
|
||||
ErrMutationOutcomeUnknown,
|
||||
endpoint,
|
||||
strings.TrimSpace(string(body)),
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// post performs a POST request with XML body
|
||||
func (c *Client) post(endpoint string, payload interface{}) error {
|
||||
url := c.baseURL + endpoint
|
||||
@@ -1428,10 +1741,18 @@ func (c *Client) GetZoneMembers() ([]string, error) {
|
||||
// An empty <group/> response is reported as a zero-value Group; callers can
|
||||
// distinguish with (*Group).IsEmpty().
|
||||
//
|
||||
// ST-10 is the only product that supports stereo pairs; on other devices
|
||||
// the call is harmless but will always return an empty group. The endpoint
|
||||
// is named /getGroup on the device (mirroring /getZone), even though some
|
||||
// third-party wikis document it as plain /group.
|
||||
// ST-10 is the only product that supports stereo pairs. Verified against
|
||||
// real hardware: a SoundTouch 20 does not reply to /getGroup promptly. The
|
||||
// device's own firmware ("AllegroWebserver") eventually answers with a
|
||||
// plain-text "AllegroWebserver timeout: /getGroup" error body after an
|
||||
// internal delay exceeding several seconds, but well within the client's
|
||||
// own timeout (30s by default, see DefaultConfig) the request just looks
|
||||
// like it never replied at all. Callers on a poll cycle must gate this call
|
||||
// behind a stereo-pair-capable model check (see stereoPairCapable in
|
||||
// pkg/service/soundtouchweb) instead of relying on a fast, harmless
|
||||
// response on unsupported models. The endpoint is named /getGroup on the
|
||||
// device (mirroring /getZone), even though some third-party wikis document
|
||||
// it as plain /group.
|
||||
func (c *Client) GetGroup() (*models.Group, error) {
|
||||
var g models.Group
|
||||
|
||||
@@ -1440,10 +1761,11 @@ func (c *Client) GetGroup() (*models.Group, error) {
|
||||
return &g, err
|
||||
}
|
||||
|
||||
// AddGroup creates a new stereo pair on the device addressed by this client,
|
||||
// which becomes the master. The supplied group must contain both LEFT and
|
||||
// RIGHT roles; the device assigns the group ID and echoes the full state
|
||||
// in the response.
|
||||
// AddGroup applies one side of stereo-pair creation to the addressed device.
|
||||
// The supplied group must contain both LEFT and RIGHT roles. A master-bound
|
||||
// request omits SenderIPAddress; a slave-bound request sets it to the master's
|
||||
// IP address. Firmware may acknowledge the request without returning the
|
||||
// assigned group ID, so callers must verify the resulting state with GetGroup.
|
||||
func (c *Client) AddGroup(group *models.Group) (*models.Group, error) {
|
||||
var result models.Group
|
||||
if err := c.postWithResponse("/addGroup", group, &result); err != nil {
|
||||
@@ -1473,7 +1795,7 @@ func (c *Client) UpdateGroup(group *models.Group) (*models.Group, error) {
|
||||
func (c *Client) RemoveGroup() error {
|
||||
var g models.Group
|
||||
|
||||
return c.get("/removeGroup", &g)
|
||||
return c.mutatingGet("/removeGroup", &g)
|
||||
}
|
||||
|
||||
// SetName sets the device name
|
||||
|
||||
@@ -59,8 +59,9 @@ func TestClient_Post_ErrorsResponse(t *testing.T) {
|
||||
t.Errorf("expected message '%s', got '%s'", expectedMsg, errs.Errors[0].Message)
|
||||
}
|
||||
|
||||
if err.Error() != expectedMsg {
|
||||
t.Errorf("expected Error() to return '%s', got '%s'", expectedMsg, err.Error())
|
||||
expectedErr := "UNKNOWN_ACTION_ERROR: " + expectedMsg
|
||||
if err.Error() != expectedErr {
|
||||
t.Errorf("expected Error() to return '%s', got '%s'", expectedErr, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
@@ -232,3 +233,74 @@ func TestClient_RemoveGroup(t *testing.T) {
|
||||
t.Fatalf("RemoveGroup: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRemoveGroupDoesNotReplayDroppedResponse(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/getGroup" {
|
||||
_, _ = w.Write([]byte(`<group />`))
|
||||
return
|
||||
}
|
||||
|
||||
if r.URL.Path != "/removeGroup" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
calls.Add(1)
|
||||
connection, _, err := w.(http.Hijacker).Hijack()
|
||||
if err != nil {
|
||||
t.Errorf("hijack response: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
_ = connection.Close()
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client := createTestClient(server.URL)
|
||||
if _, err := client.GetGroup(); err != nil {
|
||||
t.Fatalf("prime ordinary client connection: %v", err)
|
||||
}
|
||||
|
||||
err := client.RemoveGroup()
|
||||
if err == nil {
|
||||
t.Fatal("RemoveGroup succeeded after the response was dropped")
|
||||
}
|
||||
if got := calls.Load(); got != 1 {
|
||||
t.Fatalf("/removeGroup requests = %d, want exactly 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRemoveGroupDoesNotFollowRedirect(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
var redirectedCalls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
|
||||
switch r.URL.Path {
|
||||
case "/removeGroup":
|
||||
http.Redirect(w, r, "/redirected", http.StatusTemporaryRedirect)
|
||||
case "/redirected":
|
||||
redirectedCalls.Add(1)
|
||||
_, _ = w.Write([]byte(`<group />`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
err := createTestClient(server.URL).RemoveGroup()
|
||||
if err == nil {
|
||||
t.Fatal("RemoveGroup followed a redirect")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "status 307") {
|
||||
t.Fatalf("RemoveGroup error = %q, want redirect status", err)
|
||||
}
|
||||
if got := calls.Load(); got != 1 {
|
||||
t.Fatalf("HTTP requests = %d, want exactly 1", got)
|
||||
}
|
||||
if got := redirectedCalls.Load(); got != 0 {
|
||||
t.Fatalf("redirect target requests = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
)
|
||||
|
||||
func TestClientSystemSettingsGETs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
path string
|
||||
response string
|
||||
call func(*Client) error
|
||||
}{
|
||||
{
|
||||
name: "system timeout",
|
||||
path: "/systemtimeout",
|
||||
response: `<systemtimeout><powersaving_enabled>true</powersaving_enabled></systemtimeout>`,
|
||||
call: func(client *Client) error {
|
||||
setting, err := client.GetSystemTimeout()
|
||||
if err == nil && !setting.PowerSavingEnabled {
|
||||
t.Error("PowerSavingEnabled = false, want true")
|
||||
}
|
||||
return err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "rebroadcast latency",
|
||||
path: "/rebroadcastlatencymode",
|
||||
response: `<rebroadcastlatencymode mode="SYNC_TO_ZONE" controllable="true"/>`,
|
||||
call: func(client *Client) error {
|
||||
setting, err := client.GetRebroadcastLatencyMode()
|
||||
if err == nil && (setting.Mode != models.RebroadcastLatencySyncToZone || !setting.Controllable) {
|
||||
t.Errorf("setting = %#v", setting)
|
||||
}
|
||||
return err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "known language",
|
||||
path: "/language",
|
||||
response: `<sysLanguage>15</sysLanguage>`,
|
||||
call: func(client *Client) error {
|
||||
language, err := client.GetLanguage()
|
||||
if err == nil && language.Code != models.LanguageCzech {
|
||||
t.Errorf("Code = %d, want %d", language.Code, models.LanguageCzech)
|
||||
}
|
||||
return err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unknown language remains readable",
|
||||
path: "/language",
|
||||
response: `<sysLanguage>99</sysLanguage>`,
|
||||
call: func(client *Client) error {
|
||||
language, err := client.GetLanguage()
|
||||
if err == nil && language.Code != 99 {
|
||||
t.Errorf("Code = %d, want 99", language.Code)
|
||||
}
|
||||
return err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Bluetooth info",
|
||||
path: "/bluetoothInfo",
|
||||
response: `<BluetoothInfo BluetoothMACAddress="AABBCCDDEEFF"/>`,
|
||||
call: func(client *Client) error {
|
||||
info, err := client.GetBluetoothInfo()
|
||||
if err == nil && info.BluetoothMACAddress != "AABBCCDDEEFF" {
|
||||
t.Errorf("BluetoothMACAddress = %q", info.BluetoothMACAddress)
|
||||
}
|
||||
return err
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
t.Errorf("method = %s, want GET", r.Method)
|
||||
}
|
||||
if r.URL.Path != test.path {
|
||||
t.Errorf("path = %s, want %s", r.URL.Path, test.path)
|
||||
}
|
||||
if got := r.Header.Get("Accept"); got != "application/xml" {
|
||||
t.Errorf("Accept = %q", got)
|
||||
}
|
||||
if got := r.Header.Get("User-Agent"); got != "Bose-SoundTouch-Go-Client/1.0" {
|
||||
t.Errorf("User-Agent = %q", got)
|
||||
}
|
||||
_, _ = io.WriteString(w, test.response)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
if err := test.call(createTestClient(server.URL)); err != nil {
|
||||
t.Fatalf("call(): %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientSystemSettingsGETErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
call func(*Client) error
|
||||
}{
|
||||
{
|
||||
name: "malformed system timeout XML",
|
||||
body: `<systemtimeout><powersaving_enabled>`,
|
||||
call: func(client *Client) error { _, err := client.GetSystemTimeout(); return err },
|
||||
},
|
||||
{
|
||||
name: "incomplete Bluetooth XML",
|
||||
body: `<BluetoothInfo/>`,
|
||||
call: func(client *Client) error { _, err := client.GetBluetoothInfo(); return err },
|
||||
},
|
||||
{
|
||||
name: "language non-200",
|
||||
status: http.StatusNotFound,
|
||||
body: `unsupported`,
|
||||
call: func(client *Client) error { _, err := client.GetLanguage(); return err },
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
status := test.status
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
_, _ = io.WriteString(w, test.body)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
if err := test.call(createTestClient(server.URL)); err == nil {
|
||||
t.Fatal("call() unexpectedly succeeded")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientSystemSettingsPOSTs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
path string
|
||||
body string
|
||||
call func(*Client) error
|
||||
}{
|
||||
{
|
||||
name: "system timeout",
|
||||
path: "/systemtimeout",
|
||||
body: `<systemtimeout><powersaving_enabled>false</powersaving_enabled></systemtimeout>`,
|
||||
call: func(client *Client) error {
|
||||
return client.SetSystemTimeout(&models.SystemTimeout{PowerSavingEnabled: false})
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "rebroadcast latency",
|
||||
path: "/rebroadcastlatencymode",
|
||||
body: `<rebroadcastlatencymode mode="SYNC_TO_ROOM"></rebroadcastlatencymode>`,
|
||||
call: func(client *Client) error {
|
||||
return client.SetRebroadcastLatencyMode(models.RebroadcastLatencySyncToRoom)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "language",
|
||||
path: "/language",
|
||||
body: `<sysLanguage>3</sysLanguage>`,
|
||||
call: func(client *Client) error { return client.SetLanguage(models.LanguageEnglish) },
|
||||
},
|
||||
{
|
||||
name: "source rename with account",
|
||||
path: "/nameSource",
|
||||
body: `<ContentItem source="AUX" sourceAccount="AUX1"><itemName>Turntable</itemName></ContentItem>`,
|
||||
call: func(client *Client) error { return client.RenameSource("AUX", "AUX1", "Turntable") },
|
||||
},
|
||||
{
|
||||
name: "source rename without account",
|
||||
path: "/nameSource",
|
||||
body: `<ContentItem source="BLUETOOTH"><itemName>Phone</itemName></ContentItem>`,
|
||||
call: func(client *Client) error { return client.RenameSource("BLUETOOTH", "", "Phone") },
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
t.Errorf("method = %s, want POST", r.Method)
|
||||
}
|
||||
if r.URL.Path != test.path {
|
||||
t.Errorf("path = %s, want %s", r.URL.Path, test.path)
|
||||
}
|
||||
if got := r.Header.Get("Content-Type"); got != "application/xml" {
|
||||
t.Errorf("Content-Type = %q", got)
|
||||
}
|
||||
if got := r.Header.Get("Accept"); got != "application/xml" {
|
||||
t.Errorf("Accept = %q", got)
|
||||
}
|
||||
if got := r.Header.Get("User-Agent"); got != "Bose-SoundTouch-Go-Client/1.0" {
|
||||
t.Errorf("User-Agent = %q", got)
|
||||
}
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
t.Errorf("ReadAll(): %v", err)
|
||||
}
|
||||
if string(body) != test.body {
|
||||
t.Errorf("body = %q, want %q", body, test.body)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
if err := test.call(createTestClient(server.URL)); err != nil {
|
||||
t.Fatalf("call(): %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientSystemSettingsPOSTValidation(t *testing.T) {
|
||||
client := createTestClient("http://127.0.0.1:1")
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
call func() error
|
||||
}{
|
||||
{"nil timeout", func() error { return client.SetSystemTimeout(nil) }},
|
||||
{"unknown latency", func() error { return client.SetRebroadcastLatencyMode("OTHER") }},
|
||||
{"unknown language", func() error { return client.SetLanguage(99) }},
|
||||
{"missing source", func() error { return client.RenameSource("", "", "Name") }},
|
||||
{"missing item name", func() error { return client.RenameSource("AUX", "AUX1", "") }},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if err := test.call(); err == nil {
|
||||
t.Fatal("call() unexpectedly succeeded")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientSystemSettingsPOSTNon200(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
http.Error(w, "rejected", http.StatusBadRequest)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
err := createTestClient(server.URL).SetLanguage(models.LanguageEnglish)
|
||||
if err == nil || !strings.Contains(err.Error(), "400") {
|
||||
t.Fatalf("SetLanguage() error = %v, want status 400", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientBluetoothMutatingGETs(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
path string
|
||||
call func(*Client) error
|
||||
}{
|
||||
{"enter pairing mode", "/enterPairingMode", func(client *Client) error { return client.EnterPairingMode() }},
|
||||
{"clear paired list", "/clearPairedList", func(client *Client) error { return client.ClearPairedList() }},
|
||||
{"enter Bluetooth pairing", "/enterBluetoothPairing", func(client *Client) error { return client.EnterBluetoothPairing() }},
|
||||
{"clear Bluetooth paired", "/clearBluetoothPaired", func(client *Client) error { return client.ClearBluetoothPaired() }},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
requests := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests++
|
||||
if r.Method != http.MethodGet {
|
||||
t.Errorf("method = %s, want GET", r.Method)
|
||||
}
|
||||
if r.URL.Path != test.path {
|
||||
t.Errorf("path = %s, want %s", r.URL.Path, test.path)
|
||||
}
|
||||
if got := r.Header.Get("Accept"); got != "application/xml" {
|
||||
t.Errorf("Accept = %q", got)
|
||||
}
|
||||
if got := r.Header.Get("User-Agent"); got != "Bose-SoundTouch-Go-Client/1.0" {
|
||||
t.Errorf("User-Agent = %q", got)
|
||||
}
|
||||
_, _ = io.WriteString(w, `<status>`+test.path+`</status>`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
if err := test.call(createTestClient(server.URL)); err != nil {
|
||||
t.Fatalf("call(): %v", err)
|
||||
}
|
||||
if requests != 1 {
|
||||
t.Fatalf("requests = %d, want 1", requests)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientMutatingGETDoesNotFollowRedirect(t *testing.T) {
|
||||
requests := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests++
|
||||
if r.URL.Path == "/enterBluetoothPairing" {
|
||||
http.Redirect(w, r, "/replayed", http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(w, `<status>replayed</status>`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
err := createTestClient(server.URL).EnterBluetoothPairing()
|
||||
if err == nil || !strings.Contains(err.Error(), "307") {
|
||||
t.Fatalf("EnterBluetoothPairing() error = %v, want status 307", err)
|
||||
}
|
||||
if requests != 1 {
|
||||
t.Fatalf("requests = %d, want 1", requests)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientMutatingGETRejectsErrorEnvelopeWithHTTP200(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = io.WriteString(w, `<errors deviceID="AABBCCDDEEFF"><error value="1029" name="UNKNOWN_ACTION_ERROR">rejected</error></errors>`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
err := createTestClient(server.URL).EnterBluetoothPairing()
|
||||
var errs *models.ErrorsResponse
|
||||
if !errors.As(err, &errs) {
|
||||
t.Fatalf("EnterBluetoothPairing() error = %T %v, want ErrorsResponse", err, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientMutatingGETMarksUnstructuredHTTPFailureUnknown(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
http.Error(w, "internal failure", http.StatusInternalServerError)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
err := createTestClient(server.URL).EnterBluetoothPairing()
|
||||
if !errors.Is(err, ErrMutationOutcomeUnknown) {
|
||||
t.Fatalf("EnterBluetoothPairing() error = %v, want ErrMutationOutcomeUnknown", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "status 500") {
|
||||
t.Fatalf("EnterBluetoothPairing() error = %v, want status 500", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientMutatingGETMarksLostResponseUnknown(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
connection, _, err := w.(http.Hijacker).Hijack()
|
||||
if err != nil {
|
||||
t.Errorf("Hijack(): %v", err)
|
||||
return
|
||||
}
|
||||
_ = connection.Close()
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
err := createTestClient(server.URL).EnterBluetoothPairing()
|
||||
if !errors.Is(err, ErrMutationOutcomeUnknown) {
|
||||
t.Fatalf("EnterBluetoothPairing() error = %v, want ErrMutationOutcomeUnknown", err)
|
||||
}
|
||||
}
|
||||
+257
-71
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -16,17 +17,33 @@ import (
|
||||
|
||||
// WebSocketClient handles WebSocket connections to SoundTouch devices
|
||||
type WebSocketClient struct {
|
||||
client *Client
|
||||
conn *websocket.Conn
|
||||
handlers *models.WebSocketEventHandlers
|
||||
mu sync.RWMutex
|
||||
writeMu sync.Mutex // serializes all writes; gorilla/websocket allows one concurrent writer
|
||||
connected bool
|
||||
reconnect bool
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
logger Logger
|
||||
bufferSize int
|
||||
client *Client
|
||||
conn *websocket.Conn
|
||||
connection *webSocketConnection
|
||||
handlers *models.WebSocketEventHandlers
|
||||
mu sync.RWMutex
|
||||
connectMu sync.Mutex // serializes dial attempts without blocking shutdown
|
||||
writeMu sync.Mutex // serializes all writes; gorilla/websocket allows one concurrent writer
|
||||
connected bool
|
||||
reconnect bool
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
logger Logger
|
||||
bufferSize int
|
||||
dialContext webSocketDialContext
|
||||
|
||||
transportHandler func(connected bool, generation uint64)
|
||||
transportGeneration uint64
|
||||
}
|
||||
|
||||
type webSocketDialContext func(context.Context, string, http.Header) (*websocket.Conn, *http.Response, error)
|
||||
|
||||
// webSocketConnection gives each transport generation its own lifecycle so an
|
||||
// old read or ping loop cannot start using a replacement connection.
|
||||
type webSocketConnection struct {
|
||||
conn *websocket.Conn
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// Logger interface for WebSocket logging
|
||||
@@ -159,6 +176,23 @@ func (ws *WebSocketClient) OnBassUpdated(handler models.TypedEventHandler[*model
|
||||
ws.handlers.OnBassUpdated = handler
|
||||
}
|
||||
|
||||
// OnNameUpdated sets a handler for device name update events.
|
||||
func (ws *WebSocketClient) OnNameUpdated(handler models.TypedEventHandler[*models.NameUpdatedEvent]) {
|
||||
ws.mu.Lock()
|
||||
defer ws.mu.Unlock()
|
||||
|
||||
ws.handlers.OnNameUpdated = handler
|
||||
}
|
||||
|
||||
// OnTransportState observes authoritative connection transitions. Generation
|
||||
// numbers let consumers reject callbacks that arrive out of order.
|
||||
func (ws *WebSocketClient) OnTransportState(handler func(connected bool, generation uint64)) {
|
||||
ws.mu.Lock()
|
||||
defer ws.mu.Unlock()
|
||||
|
||||
ws.transportHandler = handler
|
||||
}
|
||||
|
||||
// OnUnknownEvent sets a handler for unknown events
|
||||
func (ws *WebSocketClient) OnUnknownEvent(handler models.EventHandler) {
|
||||
ws.mu.Lock()
|
||||
@@ -198,13 +232,24 @@ func (ws *WebSocketClient) ConnectWithConfig(config *WebSocketConfig) error {
|
||||
}
|
||||
|
||||
func (ws *WebSocketClient) connectWithConfig(config *WebSocketConfig) error {
|
||||
ws.mu.Lock()
|
||||
defer ws.mu.Unlock()
|
||||
ws.connectMu.Lock()
|
||||
defer ws.connectMu.Unlock()
|
||||
|
||||
ws.mu.RLock()
|
||||
|
||||
if ws.connected {
|
||||
ws.mu.RUnlock()
|
||||
return fmt.Errorf("already connected")
|
||||
}
|
||||
|
||||
ctx := ws.ctx
|
||||
dialContext := ws.dialContext
|
||||
ws.mu.RUnlock()
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return fmt.Errorf("WebSocket client is closed: %w", err)
|
||||
}
|
||||
|
||||
// Build WebSocket URL
|
||||
// Parse the base URL to extract just the hostname
|
||||
baseURL, err := url.Parse(ws.client.BaseURL())
|
||||
@@ -220,16 +265,20 @@ func (ws *WebSocketClient) connectWithConfig(config *WebSocketConfig) error {
|
||||
|
||||
ws.logger.Printf("Connecting to %s", sanitizeLog(wsURL.String()))
|
||||
|
||||
// Create dialer with custom buffer sizes and "gabbo" protocol
|
||||
dialer := websocket.Dialer{
|
||||
HandshakeTimeout: 10 * time.Second,
|
||||
ReadBufferSize: config.ReadBufferSize,
|
||||
WriteBufferSize: config.WriteBufferSize,
|
||||
Subprotocols: []string{"gabbo"}, // Required by SoundTouch API
|
||||
if dialContext == nil {
|
||||
// Create dialer with custom buffer sizes and "gabbo" protocol.
|
||||
dialer := websocket.Dialer{
|
||||
HandshakeTimeout: 10 * time.Second,
|
||||
ReadBufferSize: config.ReadBufferSize,
|
||||
WriteBufferSize: config.WriteBufferSize,
|
||||
Subprotocols: []string{"gabbo"}, // Required by SoundTouch API
|
||||
}
|
||||
dialContext = dialer.DialContext
|
||||
}
|
||||
|
||||
// Establish connection
|
||||
conn, resp, err := dialer.DialContext(ws.ctx, wsURL.String(), nil)
|
||||
// Dial without holding the state mutex so shutdown can cancel the context
|
||||
// immediately instead of waiting for the handshake timeout.
|
||||
conn, resp, err := dialContext(ctx, wsURL.String(), nil)
|
||||
if resp != nil && resp.Body != nil {
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
}
|
||||
@@ -238,8 +287,55 @@ func (ws *WebSocketClient) connectWithConfig(config *WebSocketConfig) error {
|
||||
return fmt.Errorf("failed to connect to WebSocket: %w", err)
|
||||
}
|
||||
|
||||
ws.mu.Lock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
ws.mu.Unlock()
|
||||
|
||||
_ = conn.Close()
|
||||
|
||||
return fmt.Errorf("WebSocket client closed during connect: %w", err)
|
||||
}
|
||||
|
||||
if ws.connected {
|
||||
ws.mu.Unlock()
|
||||
|
||||
_ = conn.Close()
|
||||
|
||||
return fmt.Errorf("already connected")
|
||||
}
|
||||
|
||||
connection, transportHandler, transportGeneration := ws.activateConnectionLocked(conn)
|
||||
ws.mu.Unlock()
|
||||
|
||||
notifyTransportState(transportHandler, true, transportGeneration)
|
||||
|
||||
go ws.readLoop(config, connection)
|
||||
go ws.pingLoop(config, connection)
|
||||
|
||||
ws.logger.Printf("Connected to %s", sanitizeLog(wsURL.String()))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ws *WebSocketClient) activateConnectionLocked(
|
||||
conn *websocket.Conn,
|
||||
) (*webSocketConnection, func(bool, uint64), uint64) {
|
||||
if ws.connection != nil {
|
||||
ws.connection.cancel()
|
||||
_ = ws.connection.conn.Close()
|
||||
}
|
||||
|
||||
connectionCtx, connectionCancel := context.WithCancel(ws.ctx)
|
||||
connection := &webSocketConnection{
|
||||
conn: conn,
|
||||
ctx: connectionCtx,
|
||||
cancel: connectionCancel,
|
||||
}
|
||||
|
||||
ws.conn = conn
|
||||
ws.connection = connection
|
||||
ws.connected = true
|
||||
ws.transportGeneration++
|
||||
|
||||
// Extend the read deadline on every pong so the connection survives
|
||||
// quiet periods between speaker events. Without this, the 60-second
|
||||
@@ -250,41 +346,100 @@ func (ws *WebSocketClient) connectWithConfig(config *WebSocketConfig) error {
|
||||
return nil
|
||||
})
|
||||
|
||||
// Start background goroutines for connection management
|
||||
go ws.readLoop(config)
|
||||
go ws.pingLoop(config)
|
||||
|
||||
ws.logger.Printf("Connected to %s", sanitizeLog(wsURL.String()))
|
||||
|
||||
return nil
|
||||
return connection, ws.transportHandler, ws.transportGeneration
|
||||
}
|
||||
|
||||
// Disconnect closes the WebSocket connection
|
||||
func (ws *WebSocketClient) Disconnect() error {
|
||||
ws.mu.Lock()
|
||||
defer ws.mu.Unlock()
|
||||
// Cancel first so an in-progress DialContext wakes without waiting for mu.
|
||||
ws.cancel()
|
||||
|
||||
if !ws.connected {
|
||||
return fmt.Errorf("not connected")
|
||||
}
|
||||
ws.mu.Lock()
|
||||
wasConnected := ws.connected
|
||||
|
||||
ws.reconnect = false
|
||||
ws.cancel() // Cancel context to stop goroutines
|
||||
if ws.connection != nil {
|
||||
ws.connection.cancel()
|
||||
ws.connection = nil
|
||||
}
|
||||
|
||||
conn := ws.conn
|
||||
ws.conn = nil
|
||||
ws.connected = false
|
||||
|
||||
var (
|
||||
transportHandler func(bool, uint64)
|
||||
transportGeneration uint64
|
||||
)
|
||||
if wasConnected {
|
||||
ws.transportGeneration++
|
||||
transportHandler = ws.transportHandler
|
||||
transportGeneration = ws.transportGeneration
|
||||
}
|
||||
ws.mu.Unlock()
|
||||
|
||||
if conn != nil {
|
||||
err := conn.Close()
|
||||
|
||||
if ws.conn != nil {
|
||||
err := ws.conn.Close()
|
||||
ws.conn = nil
|
||||
ws.connected = false
|
||||
ws.logger.Printf("Disconnected")
|
||||
|
||||
notifyTransportState(transportHandler, false, transportGeneration)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
ws.connected = false
|
||||
notifyTransportState(transportHandler, false, transportGeneration)
|
||||
|
||||
if !wasConnected {
|
||||
return fmt.Errorf("not connected")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close permanently stops this client and is idempotent. Device registries use
|
||||
// it when removal races an initial dial or an automatic reconnect.
|
||||
func (ws *WebSocketClient) Close() error {
|
||||
ws.cancel()
|
||||
|
||||
ws.mu.Lock()
|
||||
wasConnected := ws.connected
|
||||
|
||||
ws.reconnect = false
|
||||
if ws.connection != nil {
|
||||
ws.connection.cancel()
|
||||
ws.connection = nil
|
||||
}
|
||||
|
||||
conn := ws.conn
|
||||
ws.conn = nil
|
||||
ws.connected = false
|
||||
|
||||
var (
|
||||
transportHandler func(bool, uint64)
|
||||
transportGeneration uint64
|
||||
)
|
||||
if wasConnected {
|
||||
ws.transportGeneration++
|
||||
transportHandler = ws.transportHandler
|
||||
transportGeneration = ws.transportGeneration
|
||||
}
|
||||
ws.mu.Unlock()
|
||||
|
||||
if conn == nil {
|
||||
notifyTransportState(transportHandler, false, transportGeneration)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
err := conn.Close()
|
||||
|
||||
ws.logger.Printf("Disconnected")
|
||||
notifyTransportState(transportHandler, false, transportGeneration)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// IsConnected returns true if the WebSocket is connected
|
||||
func (ws *WebSocketClient) IsConnected() bool {
|
||||
ws.mu.RLock()
|
||||
@@ -293,45 +448,63 @@ func (ws *WebSocketClient) IsConnected() bool {
|
||||
return ws.connected
|
||||
}
|
||||
|
||||
func (ws *WebSocketClient) shouldReconnect() bool {
|
||||
ws.mu.RLock()
|
||||
defer ws.mu.RUnlock()
|
||||
|
||||
return ws.reconnect
|
||||
}
|
||||
|
||||
func notifyTransportState(handler func(bool, uint64), connected bool, generation uint64) {
|
||||
if handler != nil {
|
||||
handler(connected, generation)
|
||||
}
|
||||
}
|
||||
|
||||
// readLoop continuously reads messages from the WebSocket connection
|
||||
func (ws *WebSocketClient) readLoop(config *WebSocketConfig) {
|
||||
func (ws *WebSocketClient) readLoop(config *WebSocketConfig, connection *webSocketConnection) {
|
||||
defer func() {
|
||||
ws.mu.Lock()
|
||||
if ws.connection != connection {
|
||||
ws.mu.Unlock()
|
||||
connection.cancel()
|
||||
_ = connection.conn.Close()
|
||||
|
||||
ws.connected = false
|
||||
if ws.conn != nil {
|
||||
_ = ws.conn.Close()
|
||||
ws.conn = nil
|
||||
return
|
||||
}
|
||||
|
||||
connection.cancel()
|
||||
ws.connection = nil
|
||||
ws.conn = nil
|
||||
ws.connected = false
|
||||
ws.transportGeneration++
|
||||
transportHandler := ws.transportHandler
|
||||
transportGeneration := ws.transportGeneration
|
||||
reconnect := ws.reconnect
|
||||
ws.mu.Unlock()
|
||||
|
||||
_ = connection.conn.Close()
|
||||
|
||||
notifyTransportState(transportHandler, false, transportGeneration)
|
||||
|
||||
// Attempt reconnection if enabled
|
||||
if ws.reconnect {
|
||||
if reconnect {
|
||||
go ws.attemptReconnect(config)
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ws.ctx.Done():
|
||||
case <-connection.ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
ws.mu.RLock()
|
||||
conn := ws.conn
|
||||
ws.mu.RUnlock()
|
||||
|
||||
if conn == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Set read deadline
|
||||
_ = conn.SetReadDeadline(time.Now().Add(60 * time.Second))
|
||||
_ = connection.conn.SetReadDeadline(time.Now().Add(60 * time.Second))
|
||||
|
||||
// Read message
|
||||
messageType, data, err := conn.ReadMessage()
|
||||
messageType, data, err := connection.conn.ReadMessage()
|
||||
if err != nil {
|
||||
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
|
||||
ws.logger.Printf("WebSocket read error: %v", err)
|
||||
@@ -351,30 +524,20 @@ func (ws *WebSocketClient) readLoop(config *WebSocketConfig) {
|
||||
}
|
||||
|
||||
// pingLoop sends periodic ping messages to keep the connection alive
|
||||
func (ws *WebSocketClient) pingLoop(config *WebSocketConfig) {
|
||||
func (ws *WebSocketClient) pingLoop(config *WebSocketConfig, connection *webSocketConnection) {
|
||||
ticker := time.NewTicker(config.PingInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ws.ctx.Done():
|
||||
case <-connection.ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
ws.mu.RLock()
|
||||
conn := ws.conn
|
||||
connected := ws.connected
|
||||
ws.mu.RUnlock()
|
||||
|
||||
if !connected || conn == nil {
|
||||
active, err := ws.writePing(connection)
|
||||
if !active {
|
||||
return
|
||||
}
|
||||
|
||||
// Set write deadline for ping
|
||||
ws.writeMu.Lock()
|
||||
_ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
||||
err := conn.WriteMessage(websocket.PingMessage, nil)
|
||||
ws.writeMu.Unlock()
|
||||
|
||||
if err != nil {
|
||||
ws.logger.Printf("Failed to send ping: %v", err)
|
||||
return
|
||||
@@ -383,10 +546,26 @@ func (ws *WebSocketClient) pingLoop(config *WebSocketConfig) {
|
||||
}
|
||||
}
|
||||
|
||||
func (ws *WebSocketClient) writePing(connection *webSocketConnection) (bool, error) {
|
||||
ws.writeMu.Lock()
|
||||
defer ws.writeMu.Unlock()
|
||||
|
||||
ws.mu.RLock()
|
||||
defer ws.mu.RUnlock()
|
||||
|
||||
if connection.ctx.Err() != nil || ws.connection != connection || !ws.connected {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
_ = connection.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
||||
|
||||
return true, connection.conn.WriteMessage(websocket.PingMessage, nil)
|
||||
}
|
||||
|
||||
// attemptReconnect attempts to reconnect to the WebSocket
|
||||
func (ws *WebSocketClient) attemptReconnect(config *WebSocketConfig) {
|
||||
attempt := 0
|
||||
for ws.reconnect && (config.MaxReconnectAttempts == 0 || attempt < config.MaxReconnectAttempts) {
|
||||
for ws.shouldReconnect() && (config.MaxReconnectAttempts == 0 || attempt < config.MaxReconnectAttempts) {
|
||||
select {
|
||||
case <-ws.ctx.Done():
|
||||
return
|
||||
@@ -533,6 +712,13 @@ func (ws *WebSocketClient) dispatchTypedEventContinued(handlers *models.WebSocke
|
||||
|
||||
return true
|
||||
|
||||
case models.EventTypeNameUpdated:
|
||||
if handlers.OnNameUpdated != nil && event.NameUpdated != nil {
|
||||
handlers.OnNameUpdated(event.NameUpdated)
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
case models.EventTypeRecentsUpdated:
|
||||
return true
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
@@ -269,6 +270,139 @@ func TestWebSocketClient_Disconnect(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebSocketClient_DisconnectWhileDisconnectedStopsReconnect(t *testing.T) {
|
||||
client := NewClientFromHost("192.0.2.10")
|
||||
wsClient := client.NewWebSocketClient(nil)
|
||||
|
||||
if err := wsClient.Disconnect(); err == nil {
|
||||
t.Fatal("Disconnect() while disconnected should retain its compatibility error")
|
||||
}
|
||||
|
||||
wsClient.mu.RLock()
|
||||
reconnect := wsClient.reconnect
|
||||
wsClient.mu.RUnlock()
|
||||
if reconnect {
|
||||
t.Fatal("Disconnect() left reconnect enabled")
|
||||
}
|
||||
|
||||
select {
|
||||
case <-wsClient.ctx.Done():
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
t.Fatal("Disconnect() did not cancel the WebSocket context")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebSocketClient_CloseCancelsInProgressDial(t *testing.T) {
|
||||
client := NewClientFromHost("192.0.2.10")
|
||||
wsClient := client.NewWebSocketClient(nil)
|
||||
dialStarted := make(chan struct{})
|
||||
|
||||
wsClient.dialContext = func(ctx context.Context, _ string, _ http.Header) (*websocket.Conn, *http.Response, error) {
|
||||
close(dialStarted)
|
||||
<-ctx.Done()
|
||||
|
||||
return nil, nil, ctx.Err()
|
||||
}
|
||||
|
||||
connectDone := make(chan error, 1)
|
||||
go func() {
|
||||
connectDone <- wsClient.Connect()
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-dialStarted:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("WebSocket dial did not start")
|
||||
}
|
||||
|
||||
if err := wsClient.Close(); err != nil {
|
||||
t.Fatalf("Close() failed: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case err := <-connectDone:
|
||||
if err == nil {
|
||||
t.Fatal("Connect() succeeded after Close() canceled its dial")
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("canceled WebSocket dial did not return")
|
||||
}
|
||||
|
||||
if err := wsClient.Close(); err != nil {
|
||||
t.Fatalf("second Close() was not idempotent: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebSocketClient_StaleGenerationCannotOwnPing(t *testing.T) {
|
||||
client := NewClientFromHost("192.0.2.10")
|
||||
wsClient := client.NewWebSocketClient(nil)
|
||||
oldCtx, oldCancel := context.WithCancel(context.Background())
|
||||
currentCtx, currentCancel := context.WithCancel(context.Background())
|
||||
defer oldCancel()
|
||||
defer currentCancel()
|
||||
|
||||
oldConnection := &webSocketConnection{ctx: oldCtx, cancel: oldCancel}
|
||||
currentConnection := &webSocketConnection{ctx: currentCtx, cancel: currentCancel}
|
||||
wsClient.mu.Lock()
|
||||
wsClient.connection = currentConnection
|
||||
wsClient.connected = true
|
||||
wsClient.mu.Unlock()
|
||||
|
||||
active, err := wsClient.writePing(oldConnection)
|
||||
if err != nil {
|
||||
t.Fatalf("writePing() for stale generation returned error: %v", err)
|
||||
}
|
||||
if active {
|
||||
t.Fatal("replaced connection generation retained ping ownership")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebSocketClient_TransportCallbacksCarryMonotonicGenerations(t *testing.T) {
|
||||
server, messagesChan := setupMockWebSocketServer(t)
|
||||
defer server.Close()
|
||||
defer close(messagesChan)
|
||||
|
||||
client := NewClientFromHost("192.0.2.10")
|
||||
wsClient := client.NewWebSocketClient(nil)
|
||||
serverWebSocketURL := strings.Replace(server.URL, "http://", "ws://", 1)
|
||||
wsClient.dialContext = func(ctx context.Context, _ string, header http.Header) (*websocket.Conn, *http.Response, error) {
|
||||
return websocket.DefaultDialer.DialContext(ctx, serverWebSocketURL, header)
|
||||
}
|
||||
|
||||
type transportState struct {
|
||||
connected bool
|
||||
generation uint64
|
||||
}
|
||||
states := make(chan transportState, 2)
|
||||
wsClient.OnTransportState(func(connected bool, generation uint64) {
|
||||
states <- transportState{connected: connected, generation: generation}
|
||||
})
|
||||
nextState := func() transportState {
|
||||
t.Helper()
|
||||
select {
|
||||
case state := <-states:
|
||||
return state
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("timed out waiting for transport callback")
|
||||
return transportState{}
|
||||
}
|
||||
}
|
||||
|
||||
if err := wsClient.Connect(); err != nil {
|
||||
t.Fatalf("Connect() failed: %v", err)
|
||||
}
|
||||
if state := nextState(); !state.connected || state.generation != 1 {
|
||||
t.Fatalf("connected state = %+v, want connected generation 1", state)
|
||||
}
|
||||
|
||||
if err := wsClient.Close(); err != nil {
|
||||
t.Fatalf("Close() failed: %v", err)
|
||||
}
|
||||
if state := nextState(); state.connected || state.generation != 2 {
|
||||
t.Fatalf("disconnected state = %+v, want disconnected generation 2", state)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebSocketClient_HandleMessage(t *testing.T) {
|
||||
client := NewClientFromHost("192.0.2.10")
|
||||
wsClient := client.NewWebSocketClient(&WebSocketConfig{
|
||||
@@ -278,6 +412,7 @@ func TestWebSocketClient_HandleMessage(t *testing.T) {
|
||||
var (
|
||||
nowPlayingEvent *models.NowPlayingUpdatedEvent
|
||||
volumeEvent *models.VolumeUpdatedEvent
|
||||
nameEvent *models.NameUpdatedEvent
|
||||
)
|
||||
|
||||
wsClient.OnNowPlaying(func(event *models.NowPlayingUpdatedEvent) {
|
||||
@@ -288,6 +423,10 @@ func TestWebSocketClient_HandleMessage(t *testing.T) {
|
||||
volumeEvent = event
|
||||
})
|
||||
|
||||
wsClient.OnNameUpdated(func(event *models.NameUpdatedEvent) {
|
||||
nameEvent = event
|
||||
})
|
||||
|
||||
t.Run("HandleNowPlayingEvent", func(t *testing.T) {
|
||||
xmlData := []byte(`<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<updates deviceID="689E19B8BB8A">
|
||||
@@ -343,6 +482,20 @@ func TestWebSocketClient_HandleMessage(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("HandleNameEvent", func(t *testing.T) {
|
||||
xmlData := []byte(`<updates deviceID="689E19B8BB8A"><nameUpdated deviceID="689E19B8BB8A"><name>Living Room Left</name></nameUpdated></updates>`)
|
||||
|
||||
wsClient.handleMessage(xmlData)
|
||||
|
||||
if nameEvent == nil {
|
||||
t.Fatal("Name event handler was not called")
|
||||
}
|
||||
|
||||
if nameEvent.DeviceID != "689E19B8BB8A" || nameEvent.Name.Value != "Living Room Left" {
|
||||
t.Errorf("Unexpected name event: %+v", nameEvent)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("HandleInvalidXML", func(t *testing.T) {
|
||||
logger := &mockLogger{}
|
||||
wsClient.logger = logger
|
||||
|
||||
@@ -31,6 +31,7 @@ type ClockDisplay struct {
|
||||
XMLName xml.Name `xml:"clockDisplay"`
|
||||
DeviceID string
|
||||
Enabled bool
|
||||
enabledSet bool
|
||||
Format string // public-facing values: "12", "24", "auto"
|
||||
Brightness int
|
||||
AutoDim bool // not on the device's wire format; preserved for API compat
|
||||
@@ -76,6 +77,7 @@ func mapFromWireFormat(wire string) string {
|
||||
// either because it appears in legacy captures or for forward-compat with
|
||||
// firmwares that may revert.
|
||||
func (c *ClockDisplay) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
||||
c.enabledSet = false
|
||||
applyClockDisplayOuterAttrs(c, start.Attr)
|
||||
|
||||
for {
|
||||
@@ -121,6 +123,7 @@ func applyClockDisplayOuterAttrs(c *ClockDisplay, attrs []xml.Attr) {
|
||||
c.DeviceID = attr.Value
|
||||
case "enabled":
|
||||
c.Enabled = attr.Value == "true"
|
||||
c.enabledSet = true
|
||||
case "format":
|
||||
c.Format = attr.Value
|
||||
case "brightness":
|
||||
@@ -143,6 +146,7 @@ func applyClockConfigAttrs(c *ClockDisplay, attrs []xml.Attr) {
|
||||
c.TimeZone = attr.Value
|
||||
case "userEnable":
|
||||
c.Enabled = attr.Value == "true"
|
||||
c.enabledSet = true
|
||||
case "timeFormat":
|
||||
if mapped := mapFromWireFormat(attr.Value); mapped != "" {
|
||||
c.Format = mapped
|
||||
@@ -170,6 +174,11 @@ func (c *ClockDisplay) IsEnabled() bool {
|
||||
return c.Enabled
|
||||
}
|
||||
|
||||
// HasEnabled reports whether the enabled value was present in the XML response.
|
||||
func (c *ClockDisplay) HasEnabled() bool {
|
||||
return c.enabledSet
|
||||
}
|
||||
|
||||
// GetFormat returns the clock display format (12/24 hour)
|
||||
func (c *ClockDisplay) GetFormat() string {
|
||||
if c.Format == "" {
|
||||
|
||||
@@ -98,6 +98,57 @@ func TestClockDisplay_UnmarshalXML(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClockDisplay_UnmarshalXML_EnabledPresence(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
xmlData string
|
||||
wantEnabled bool
|
||||
wantPresent bool
|
||||
}{
|
||||
{
|
||||
name: "nested present true",
|
||||
xmlData: `<clockDisplay><clockConfig userEnable="true"/></clockDisplay>`,
|
||||
wantEnabled: true,
|
||||
wantPresent: true,
|
||||
},
|
||||
{
|
||||
name: "nested present false",
|
||||
xmlData: `<clockDisplay><clockConfig userEnable="false"/></clockDisplay>`,
|
||||
wantEnabled: false,
|
||||
wantPresent: true,
|
||||
},
|
||||
{
|
||||
name: "legacy present",
|
||||
xmlData: `<clockDisplay enabled="true"></clockDisplay>`,
|
||||
wantEnabled: true,
|
||||
wantPresent: true,
|
||||
},
|
||||
{
|
||||
name: "omitted",
|
||||
xmlData: `<clockDisplay><clockConfig brightnessLevel="70"/></clockDisplay>`,
|
||||
wantEnabled: false,
|
||||
wantPresent: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var got ClockDisplay
|
||||
if err := xml.Unmarshal([]byte(tt.xmlData), &got); err != nil {
|
||||
t.Fatalf("Failed to unmarshal XML: %v", err)
|
||||
}
|
||||
|
||||
if got.Enabled != tt.wantEnabled {
|
||||
t.Errorf("Enabled = %v, want %v", got.Enabled, tt.wantEnabled)
|
||||
}
|
||||
|
||||
if got.HasEnabled() != tt.wantPresent {
|
||||
t.Errorf("HasEnabled() = %v, want %v", got.HasEnabled(), tt.wantPresent)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClockDisplay_IsEnabled(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
+24
-1
@@ -2,6 +2,8 @@ package models
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -80,7 +82,7 @@ type ErrorsResponse struct {
|
||||
// Error implements the error interface for ErrorsResponse
|
||||
func (e *ErrorsResponse) Error() string {
|
||||
if len(e.Errors) > 0 {
|
||||
return e.Errors[0].Message
|
||||
return e.Errors[0].Error()
|
||||
}
|
||||
|
||||
return "unknown API error"
|
||||
@@ -93,6 +95,27 @@ type DeviceError struct {
|
||||
Message string `xml:",chardata"`
|
||||
}
|
||||
|
||||
// Error implements the error interface for DeviceError. Some speakers
|
||||
// return a Message that just restates Value as text (e.g. a bare "1047"
|
||||
// for an error the firmware has no localized string for) — Name is the
|
||||
// only informative part in that case, so it's always included unless
|
||||
// Message already carries it.
|
||||
func (e DeviceError) Error() string {
|
||||
if e.Name == "" {
|
||||
if e.Message == "" {
|
||||
return fmt.Sprintf("device error %d", e.Value)
|
||||
}
|
||||
|
||||
return e.Message
|
||||
}
|
||||
|
||||
if e.Message == "" || e.Message == e.Name || e.Message == strconv.Itoa(e.Value) {
|
||||
return fmt.Sprintf("%s (%d)", e.Name, e.Value)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s: %s", e.Name, e.Message)
|
||||
}
|
||||
|
||||
// DiscoveredDevice represents a device found through network discovery
|
||||
type DiscoveredDevice struct {
|
||||
Name string `json:"name"`
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package models
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestDeviceError_Error(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err DeviceError
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "message repeats the numeric value (real speaker case)",
|
||||
err: DeviceError{Value: 1047, Name: "SOURCE_ALREADY_REMOVED", Message: "1047"},
|
||||
expected: "SOURCE_ALREADY_REMOVED (1047)",
|
||||
},
|
||||
{
|
||||
name: "message is empty",
|
||||
err: DeviceError{Value: 1047, Name: "SOURCE_ALREADY_REMOVED", Message: ""},
|
||||
expected: "SOURCE_ALREADY_REMOVED (1047)",
|
||||
},
|
||||
{
|
||||
name: "message is meaningful and distinct from name",
|
||||
err: DeviceError{Value: 1029, Name: "UNKNOWN_ACTION_ERROR", Message: "This version of SCM does not support spotify create account functionality."},
|
||||
expected: "UNKNOWN_ACTION_ERROR: This version of SCM does not support spotify create account functionality.",
|
||||
},
|
||||
{
|
||||
name: "name is empty, message carries the detail",
|
||||
err: DeviceError{Value: 500, Name: "", Message: "internal error"},
|
||||
expected: "internal error",
|
||||
},
|
||||
{
|
||||
name: "both name and message are empty",
|
||||
err: DeviceError{Value: 500, Name: "", Message: ""},
|
||||
expected: "device error 500",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := tt.err.Error(); got != tt.expected {
|
||||
t.Errorf("expected %q, got %q", tt.expected, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorsResponse_Error(t *testing.T) {
|
||||
t.Run("delegates to the first DeviceError", func(t *testing.T) {
|
||||
errs := &ErrorsResponse{
|
||||
Errors: []DeviceError{
|
||||
{Value: 1047, Name: "SOURCE_ALREADY_REMOVED", Message: "1047"},
|
||||
},
|
||||
}
|
||||
|
||||
expected := "SOURCE_ALREADY_REMOVED (1047)"
|
||||
if got := errs.Error(); got != expected {
|
||||
t.Errorf("expected %q, got %q", expected, got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("no errors", func(t *testing.T) {
|
||||
errs := &ErrorsResponse{}
|
||||
|
||||
expected := "unknown API error"
|
||||
if got := errs.Error(); got != expected {
|
||||
t.Errorf("expected %q, got %q", expected, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
+102
-1
@@ -1,6 +1,10 @@
|
||||
package models
|
||||
|
||||
import "encoding/xml"
|
||||
import (
|
||||
"encoding/xml"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Group represents a stereo pair of two ST10 SoundTouch speakers.
|
||||
type Group struct {
|
||||
@@ -32,3 +36,100 @@ type GroupRole struct {
|
||||
Role string `xml:"role"`
|
||||
IPAddress string `xml:"ipAddress,omitempty"`
|
||||
}
|
||||
|
||||
// SameGroupRoles reports whether two role slices describe the same stereo
|
||||
// pair topology: matching length, no duplicate Role value on either side, and
|
||||
// every role paired by Role with equal DeviceID and IPAddress. It tolerates
|
||||
// any role count rather than assuming exactly LEFT/RIGHT.
|
||||
//
|
||||
// This is the shared core behind both pkg/stereopair's and
|
||||
// pkg/service/datastore's topology-equality checks -- they used to compare
|
||||
// IPAddress independently (one via net.ParseIP, one via plain string
|
||||
// equality), which could disagree about whether two differently-formatted
|
||||
// but equal addresses matched. See i655 code-review finding #10.
|
||||
func SameGroupRoles(a, b []GroupRole) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
|
||||
byRole := make(map[string]GroupRole, len(a))
|
||||
for _, role := range a {
|
||||
if _, duplicate := byRole[role.Role]; duplicate {
|
||||
return false
|
||||
}
|
||||
|
||||
byRole[role.Role] = role
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, len(b))
|
||||
for _, role := range b {
|
||||
if _, duplicate := seen[role.Role]; duplicate {
|
||||
return false
|
||||
}
|
||||
|
||||
seen[role.Role] = struct{}{}
|
||||
|
||||
other, ok := byRole[role.Role]
|
||||
if !ok || other.DeviceID != role.DeviceID || !sameRoleIPAddress(other.IPAddress, role.IPAddress) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// sameRoleIPAddress treats identical strings (including two empty/unset
|
||||
// addresses) as equal, and otherwise falls back to parsed-IP equality so two
|
||||
// differently-formatted representations of the same address still match. It
|
||||
// never treats one populated and one empty/unparsable address as a match.
|
||||
func sameRoleIPAddress(a, b string) bool {
|
||||
if a == b {
|
||||
return true
|
||||
}
|
||||
|
||||
parsedA, parsedB := net.ParseIP(a), net.ParseIP(b)
|
||||
|
||||
return parsedA != nil && parsedB != nil && parsedA.Equal(parsedB)
|
||||
}
|
||||
|
||||
// SameGroup reports whether left and right describe the same stereo-pair
|
||||
// configuration, comparing role assignments by device ID rather than by
|
||||
// slice order. The device's own /getGroup response and its groupUpdated
|
||||
// WebSocket event both populate Roles.Roles directly from XML unmarshaling
|
||||
// in wire order, so a polled read and a pushed event for the identical pair
|
||||
// are not guaranteed to list roles in the same order -- comparing with
|
||||
// reflect.DeepEqual (order-sensitive) would then report a spurious change
|
||||
// even though nothing about the pair actually changed. Two nil Groups are
|
||||
// equal; exactly one nil is not.
|
||||
//
|
||||
// SameGroup stays a distinct, IP-agnostic implementation from
|
||||
// SameGroupRoles: its callers (event/status projection) need
|
||||
// order-independence without caring about IP, and adding an IP check here
|
||||
// would change that contract.
|
||||
func SameGroup(left, right *Group) bool {
|
||||
if left == nil && right == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
if left == nil || right == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if left.ID != right.ID || left.MasterDeviceID != right.MasterDeviceID ||
|
||||
len(left.Roles.Roles) != len(right.Roles.Roles) {
|
||||
return false
|
||||
}
|
||||
|
||||
rightRoles := make(map[string]string, len(right.Roles.Roles))
|
||||
for _, role := range right.Roles.Roles {
|
||||
rightRoles[strings.TrimSpace(role.DeviceID)] = strings.ToUpper(strings.TrimSpace(role.Role))
|
||||
}
|
||||
|
||||
for _, role := range left.Roles.Roles {
|
||||
if rightRoles[strings.TrimSpace(role.DeviceID)] != strings.ToUpper(strings.TrimSpace(role.Role)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package models
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSameGroupRoles(t *testing.T) {
|
||||
base := []GroupRole{
|
||||
{DeviceID: "LEFT-ID", Role: "LEFT", IPAddress: "192.0.2.10"},
|
||||
{DeviceID: "RIGHT-ID", Role: "RIGHT", IPAddress: "192.0.2.11"},
|
||||
}
|
||||
|
||||
t.Run("identical roles match", func(t *testing.T) {
|
||||
if !SameGroupRoles(base, append([]GroupRole(nil), base...)) {
|
||||
t.Fatal("identical roles reported as different")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("role order does not matter", func(t *testing.T) {
|
||||
reordered := []GroupRole{base[1], base[0]}
|
||||
if !SameGroupRoles(base, reordered) {
|
||||
t.Fatal("reordered roles reported as different")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("differently formatted equal IP matches", func(t *testing.T) {
|
||||
other := append([]GroupRole(nil), base...)
|
||||
other[0].IPAddress = "::ffff:192.0.2.10" // IPv4-mapped IPv6 form of the same address
|
||||
if !SameGroupRoles(base, other) {
|
||||
t.Fatal("differently-formatted equal IP addresses reported as different")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("both empty IP addresses match", func(t *testing.T) {
|
||||
noIP := []GroupRole{
|
||||
{DeviceID: "LEFT-ID", Role: "LEFT"},
|
||||
{DeviceID: "RIGHT-ID", Role: "RIGHT"},
|
||||
}
|
||||
if !SameGroupRoles(noIP, append([]GroupRole(nil), noIP...)) {
|
||||
t.Fatal("two roles with unset IP addresses reported as different")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("different IP does not match", func(t *testing.T) {
|
||||
other := append([]GroupRole(nil), base...)
|
||||
other[0].IPAddress = "198.51.100.10"
|
||||
if SameGroupRoles(base, other) {
|
||||
t.Fatal("different IP addresses reported as same")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("populated vs empty IP does not match", func(t *testing.T) {
|
||||
other := append([]GroupRole(nil), base...)
|
||||
other[0].IPAddress = ""
|
||||
if SameGroupRoles(base, other) {
|
||||
t.Fatal("populated vs empty IP address reported as same")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("different DeviceID does not match", func(t *testing.T) {
|
||||
other := append([]GroupRole(nil), base...)
|
||||
other[0].DeviceID = "OTHER-ID"
|
||||
if SameGroupRoles(base, other) {
|
||||
t.Fatal("different DeviceID reported as same")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("different Role does not match", func(t *testing.T) {
|
||||
other := append([]GroupRole(nil), base...)
|
||||
other[0].Role = "RIGHT"
|
||||
if SameGroupRoles(base, other) {
|
||||
t.Fatal("mismatched Role reported as same")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("different length does not match", func(t *testing.T) {
|
||||
if SameGroupRoles(base, base[:1]) {
|
||||
t.Fatal("different-length role slices reported as same")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("duplicate role on either side does not match", func(t *testing.T) {
|
||||
duplicateA := []GroupRole{base[0], base[0]}
|
||||
duplicateB := []GroupRole{base[1], base[1]}
|
||||
if SameGroupRoles(duplicateA, base) {
|
||||
t.Fatal("duplicate role in first argument reported as same")
|
||||
}
|
||||
if SameGroupRoles(base, duplicateB) {
|
||||
t.Fatal("duplicate role in second argument reported as same")
|
||||
}
|
||||
})
|
||||
}
|
||||
+35
-23
@@ -8,29 +8,30 @@ import (
|
||||
|
||||
// NowPlaying represents the current playback information from /now_playing endpoint
|
||||
type NowPlaying struct {
|
||||
XMLName xml.Name `xml:"nowPlaying"`
|
||||
DeviceID string `xml:"deviceID,attr"`
|
||||
Source string `xml:"source,attr"`
|
||||
SourceAccount string `xml:"sourceAccount,attr,omitempty"`
|
||||
ContentItem *ContentItem `xml:"ContentItem,omitempty"`
|
||||
Track string `xml:"track,omitempty"`
|
||||
Artist string `xml:"artist,omitempty"`
|
||||
Album string `xml:"album,omitempty"`
|
||||
StationName string `xml:"stationName,omitempty"`
|
||||
Art *Art `xml:"art,omitempty"`
|
||||
Time *Time `xml:"time,omitempty"`
|
||||
SkipEnabled *SkipEnabled `xml:"skipEnabled,omitempty"`
|
||||
FavoriteEnabled *FavoriteEnabled `xml:"favoriteEnabled,omitempty"`
|
||||
PlayStatus PlayStatus `xml:"playStatus,omitempty"`
|
||||
ShuffleSetting ShuffleSetting `xml:"shuffleSetting,omitempty"`
|
||||
RepeatSetting RepeatSetting `xml:"repeatSetting,omitempty"`
|
||||
SkipPreviousEnabled *SkipPreviousEnabled `xml:"skipPreviousEnabled,omitempty"`
|
||||
SeekSupported *SeekSupported `xml:"seekSupported,omitempty"`
|
||||
StreamType string `xml:"streamType,omitempty"`
|
||||
TrackID string `xml:"trackID,omitempty"`
|
||||
Position *Position `xml:"position,omitempty"`
|
||||
Description string `xml:"description,omitempty"`
|
||||
StationLocation string `xml:"stationLocation,omitempty"`
|
||||
XMLName xml.Name `xml:"nowPlaying"`
|
||||
DeviceID string `xml:"deviceID,attr"`
|
||||
Source string `xml:"source,attr"`
|
||||
SourceAccount string `xml:"sourceAccount,attr,omitempty"`
|
||||
ContentItem *ContentItem `xml:"ContentItem,omitempty"`
|
||||
Track string `xml:"track,omitempty"`
|
||||
Artist string `xml:"artist,omitempty"`
|
||||
Album string `xml:"album,omitempty"`
|
||||
StationName string `xml:"stationName,omitempty"`
|
||||
Art *Art `xml:"art,omitempty"`
|
||||
Time *Time `xml:"time,omitempty"`
|
||||
SkipEnabled *SkipEnabled `xml:"skipEnabled,omitempty"`
|
||||
FavoriteEnabled *FavoriteEnabled `xml:"favoriteEnabled,omitempty"`
|
||||
PlayStatus PlayStatus `xml:"playStatus,omitempty"`
|
||||
ShuffleSetting ShuffleSetting `xml:"shuffleSetting,omitempty"`
|
||||
RepeatSetting RepeatSetting `xml:"repeatSetting,omitempty"`
|
||||
SkipPreviousEnabled *SkipPreviousEnabled `xml:"skipPreviousEnabled,omitempty"`
|
||||
SeekSupported *SeekSupported `xml:"seekSupported,omitempty"`
|
||||
StreamType string `xml:"streamType,omitempty"`
|
||||
TrackID string `xml:"trackID,omitempty"`
|
||||
Position *Position `xml:"position,omitempty"`
|
||||
Description string `xml:"description,omitempty"`
|
||||
StationLocation string `xml:"stationLocation,omitempty"`
|
||||
ConnectionStatusInfo *ConnectionStatusInfo `xml:"connectionStatusInfo,omitempty"`
|
||||
}
|
||||
|
||||
// ContentItem represents metadata about the currently playing content
|
||||
@@ -44,6 +45,17 @@ type ContentItem struct {
|
||||
ContainerArt string `xml:"containerArt,omitempty"`
|
||||
}
|
||||
|
||||
// ConnectionStatusInfo describes the active Bluetooth connection state.
|
||||
type ConnectionStatusInfo struct {
|
||||
DeviceName string `xml:"deviceName,attr"`
|
||||
Status string `xml:"status,attr"`
|
||||
}
|
||||
|
||||
// IsDiscoverable reports whether the speaker is advertising for pairing.
|
||||
func (c *ConnectionStatusInfo) IsDiscoverable() bool {
|
||||
return c != nil && c.Status == "DISCOVERABLE"
|
||||
}
|
||||
|
||||
// Art represents album artwork information
|
||||
type Art struct {
|
||||
ArtImageStatus string `xml:"artImageStatus,attr"`
|
||||
|
||||
@@ -307,6 +307,35 @@ func TestNowPlaying_UnmarshalXML(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNowPlaying_BluetoothConnectionStatusInfo(t *testing.T) {
|
||||
input := `<nowPlaying source="BLUETOOTH"><connectionStatusInfo deviceName="Phone" status="DISCOVERABLE"></connectionStatusInfo></nowPlaying>`
|
||||
var nowPlaying NowPlaying
|
||||
if err := xml.Unmarshal([]byte(input), &nowPlaying); err != nil {
|
||||
t.Fatalf("xml.Unmarshal(): %v", err)
|
||||
}
|
||||
if nowPlaying.ConnectionStatusInfo == nil {
|
||||
t.Fatal("ConnectionStatusInfo is nil")
|
||||
}
|
||||
if nowPlaying.ConnectionStatusInfo.DeviceName != "Phone" {
|
||||
t.Fatalf("DeviceName = %q, want Phone", nowPlaying.ConnectionStatusInfo.DeviceName)
|
||||
}
|
||||
if nowPlaying.ConnectionStatusInfo.Status != "DISCOVERABLE" {
|
||||
t.Fatalf("Status = %q, want DISCOVERABLE", nowPlaying.ConnectionStatusInfo.Status)
|
||||
}
|
||||
if !nowPlaying.ConnectionStatusInfo.IsDiscoverable() {
|
||||
t.Fatal("IsDiscoverable() = false, want true")
|
||||
}
|
||||
|
||||
nowPlaying.ConnectionStatusInfo.Status = "CONNECTED"
|
||||
if nowPlaying.ConnectionStatusInfo.IsDiscoverable() {
|
||||
t.Fatal("IsDiscoverable() = true for CONNECTED")
|
||||
}
|
||||
var absent *ConnectionStatusInfo
|
||||
if absent.IsDiscoverable() {
|
||||
t.Fatal("nil IsDiscoverable() = true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNowPlaying_RadioStation(t *testing.T) {
|
||||
xmlData := `<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<nowPlaying deviceID="AABBCCDDEEFF" source="TUNEIN">
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SystemTimeout is the power-saving setting returned by /systemtimeout.
|
||||
type SystemTimeout struct {
|
||||
XMLName xml.Name `xml:"systemtimeout"`
|
||||
PowerSavingEnabled bool `xml:"powersaving_enabled"`
|
||||
}
|
||||
|
||||
// Validate checks whether the update model is present.
|
||||
func (s *SystemTimeout) Validate() error {
|
||||
if s == nil {
|
||||
return fmt.Errorf("system timeout is nil")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UnmarshalXML rejects responses that omit the required power-saving value.
|
||||
func (s *SystemTimeout) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
||||
if start.Name.Local != "systemtimeout" {
|
||||
return fmt.Errorf("expected systemtimeout element, got %s", start.Name.Local)
|
||||
}
|
||||
|
||||
var wire struct {
|
||||
PowerSavingEnabled *bool `xml:"powersaving_enabled"`
|
||||
}
|
||||
if err := d.DecodeElement(&wire, &start); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if wire.PowerSavingEnabled == nil {
|
||||
return fmt.Errorf("systemtimeout is missing powersaving_enabled")
|
||||
}
|
||||
|
||||
s.XMLName = start.Name
|
||||
s.PowerSavingEnabled = *wire.PowerSavingEnabled
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RebroadcastLatencyModeValue is a firmware-supported rebroadcast timing mode.
|
||||
type RebroadcastLatencyModeValue string
|
||||
|
||||
const (
|
||||
// RebroadcastLatencySyncToRoom prioritizes the selected room for video sync.
|
||||
RebroadcastLatencySyncToRoom RebroadcastLatencyModeValue = "SYNC_TO_ROOM"
|
||||
// RebroadcastLatencySyncToZone prioritizes synchronization across the zone.
|
||||
RebroadcastLatencySyncToZone RebroadcastLatencyModeValue = "SYNC_TO_ZONE"
|
||||
)
|
||||
|
||||
// Validate rejects values that the SoundTouch firmware does not understand.
|
||||
func (m RebroadcastLatencyModeValue) Validate() error {
|
||||
switch m {
|
||||
case RebroadcastLatencySyncToRoom, RebroadcastLatencySyncToZone:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unknown rebroadcast latency mode %q", m)
|
||||
}
|
||||
}
|
||||
|
||||
// RebroadcastLatencyMode is the setting returned by /rebroadcastlatencymode.
|
||||
// Controllable is response metadata and is not included in update requests.
|
||||
type RebroadcastLatencyMode struct {
|
||||
XMLName xml.Name `xml:"rebroadcastlatencymode"`
|
||||
Mode RebroadcastLatencyModeValue `xml:"mode,attr"`
|
||||
Controllable bool `xml:"controllable,attr"`
|
||||
}
|
||||
|
||||
// Validate checks whether the reported mode is supported.
|
||||
func (r *RebroadcastLatencyMode) Validate() error {
|
||||
if r == nil {
|
||||
return fmt.Errorf("rebroadcast latency mode is nil")
|
||||
}
|
||||
|
||||
return r.Mode.Validate()
|
||||
}
|
||||
|
||||
// UnmarshalXML rejects responses that omit either required attribute.
|
||||
func (r *RebroadcastLatencyMode) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
||||
if start.Name.Local != "rebroadcastlatencymode" {
|
||||
return fmt.Errorf("expected rebroadcastlatencymode element, got %s", start.Name.Local)
|
||||
}
|
||||
|
||||
var wire struct {
|
||||
Mode *RebroadcastLatencyModeValue `xml:"mode,attr"`
|
||||
Controllable *bool `xml:"controllable,attr"`
|
||||
}
|
||||
if err := d.DecodeElement(&wire, &start); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if wire.Mode == nil {
|
||||
return fmt.Errorf("rebroadcastlatencymode is missing mode")
|
||||
}
|
||||
|
||||
if wire.Controllable == nil {
|
||||
return fmt.Errorf("rebroadcastlatencymode is missing controllable")
|
||||
}
|
||||
|
||||
if err := wire.Mode.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r.XMLName = start.Name
|
||||
r.Mode = *wire.Mode
|
||||
r.Controllable = *wire.Controllable
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RebroadcastLatencyModeRequest is the update body accepted by the firmware.
|
||||
type RebroadcastLatencyModeRequest struct {
|
||||
XMLName xml.Name `xml:"rebroadcastlatencymode"`
|
||||
Mode RebroadcastLatencyModeValue `xml:"mode,attr"`
|
||||
}
|
||||
|
||||
// Validate checks whether the requested latency mode is known.
|
||||
func (r *RebroadcastLatencyModeRequest) Validate() error {
|
||||
if r == nil {
|
||||
return fmt.Errorf("rebroadcast latency mode request is nil")
|
||||
}
|
||||
|
||||
return r.Mode.Validate()
|
||||
}
|
||||
|
||||
// LanguageCode is a SoundTouch system-language identifier.
|
||||
type LanguageCode int
|
||||
|
||||
// Supported system language codes match the set exposed by Stockholm.
|
||||
const (
|
||||
LanguageDanish LanguageCode = 1
|
||||
LanguageGerman LanguageCode = 2
|
||||
LanguageEnglish LanguageCode = 3
|
||||
LanguageSpanish LanguageCode = 4
|
||||
LanguageFrench LanguageCode = 5
|
||||
LanguageItalian LanguageCode = 6
|
||||
LanguageDutch LanguageCode = 7
|
||||
LanguageSwedish LanguageCode = 8
|
||||
LanguageJapanese LanguageCode = 9
|
||||
LanguageSimplifiedChinese LanguageCode = 10
|
||||
LanguageTraditionalChinese LanguageCode = 11
|
||||
LanguageKorean LanguageCode = 12
|
||||
LanguageThai LanguageCode = 13
|
||||
LanguageCzech LanguageCode = 15
|
||||
LanguageFinnish LanguageCode = 16
|
||||
LanguageGreek LanguageCode = 17
|
||||
LanguageNorwegian LanguageCode = 18
|
||||
LanguagePolish LanguageCode = 19
|
||||
LanguagePortuguese LanguageCode = 20
|
||||
LanguageRomanian LanguageCode = 21
|
||||
LanguageRussian LanguageCode = 22
|
||||
LanguageSlovenian LanguageCode = 23
|
||||
LanguageTurkish LanguageCode = 24
|
||||
LanguageHungarian LanguageCode = 25
|
||||
)
|
||||
|
||||
var knownSystemLanguageNames = map[LanguageCode]string{
|
||||
LanguageDanish: "Dansk",
|
||||
LanguageGerman: "Deutsch",
|
||||
LanguageEnglish: "English",
|
||||
LanguageSpanish: "Español",
|
||||
LanguageFrench: "Français",
|
||||
LanguageItalian: "Italiano",
|
||||
LanguageDutch: "Nederlands",
|
||||
LanguageSwedish: "Svenska",
|
||||
LanguageJapanese: "日本語",
|
||||
LanguageSimplifiedChinese: "简体中文",
|
||||
LanguageTraditionalChinese: "繁體中文",
|
||||
LanguageKorean: "한국어",
|
||||
LanguageThai: "ไทย",
|
||||
LanguageCzech: "Čeština",
|
||||
LanguageFinnish: "Suomi",
|
||||
LanguageGreek: "Ελληνικά",
|
||||
LanguageNorwegian: "Norsk",
|
||||
LanguagePolish: "Polski",
|
||||
LanguagePortuguese: "Português",
|
||||
LanguageRomanian: "Română",
|
||||
LanguageRussian: "Русский",
|
||||
LanguageSlovenian: "Slovenščina",
|
||||
LanguageTurkish: "Türkçe",
|
||||
LanguageHungarian: "Magyar",
|
||||
}
|
||||
|
||||
// SystemLanguageNames returns the language labels and codes used by Stockholm.
|
||||
// Each call returns a copy so callers cannot mutate shared validation state.
|
||||
func SystemLanguageNames() map[LanguageCode]string {
|
||||
names := make(map[LanguageCode]string, len(knownSystemLanguageNames))
|
||||
for code, name := range knownSystemLanguageNames {
|
||||
names[code] = name
|
||||
}
|
||||
|
||||
return names
|
||||
}
|
||||
|
||||
// Validate rejects language codes that Stockholm does not offer for writes.
|
||||
func (l LanguageCode) Validate() error {
|
||||
if _, ok := knownSystemLanguageNames[l]; !ok {
|
||||
return fmt.Errorf("unknown system language code %d", l)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SystemLanguage is the integer value read from or written to /language.
|
||||
// Unknown values are retained when reading so newer firmware remains usable.
|
||||
type SystemLanguage struct {
|
||||
XMLName xml.Name `xml:"sysLanguage"`
|
||||
Code LanguageCode `xml:",chardata"`
|
||||
}
|
||||
|
||||
// UnmarshalXML retains unknown integer codes for forward compatibility while
|
||||
// rejecting a response that omits the language value entirely.
|
||||
func (l *SystemLanguage) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
||||
if start.Name.Local != "sysLanguage" {
|
||||
return fmt.Errorf("expected sysLanguage element, got %s", start.Name.Local)
|
||||
}
|
||||
|
||||
var raw string
|
||||
if err := d.DecodeElement(&raw, &start); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return fmt.Errorf("sysLanguage is missing its language code")
|
||||
}
|
||||
|
||||
code, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid sysLanguage code %q: %w", raw, err)
|
||||
}
|
||||
|
||||
l.XMLName = start.Name
|
||||
l.Code = LanguageCode(code)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Validate checks whether this language can be sent to the speaker.
|
||||
func (l *SystemLanguage) Validate() error {
|
||||
if l == nil {
|
||||
return fmt.Errorf("system language is nil")
|
||||
}
|
||||
|
||||
return l.Code.Validate()
|
||||
}
|
||||
|
||||
// BluetoothInfo is the speaker Bluetooth adapter information.
|
||||
type BluetoothInfo struct {
|
||||
XMLName xml.Name `xml:"BluetoothInfo"`
|
||||
BluetoothMACAddress string `xml:"BluetoothMACAddress,attr"`
|
||||
}
|
||||
|
||||
// Validate requires the adapter address returned by the firmware.
|
||||
func (b *BluetoothInfo) Validate() error {
|
||||
if b == nil {
|
||||
return fmt.Errorf("bluetooth info is nil")
|
||||
}
|
||||
|
||||
if b.BluetoothMACAddress == "" {
|
||||
return fmt.Errorf("bluetooth info is missing BluetoothMACAddress")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UnmarshalXML rejects responses without the adapter address.
|
||||
func (b *BluetoothInfo) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
||||
if start.Name.Local != "BluetoothInfo" {
|
||||
return fmt.Errorf("expected BluetoothInfo element, got %s", start.Name.Local)
|
||||
}
|
||||
|
||||
var wire struct {
|
||||
BluetoothMACAddress string `xml:"BluetoothMACAddress,attr"`
|
||||
}
|
||||
if err := d.DecodeElement(&wire, &start); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b.XMLName = start.Name
|
||||
b.BluetoothMACAddress = wire.BluetoothMACAddress
|
||||
|
||||
return b.Validate()
|
||||
}
|
||||
|
||||
// SourceRenameRequest is the exact update body accepted by /nameSource.
|
||||
type SourceRenameRequest struct {
|
||||
XMLName xml.Name `xml:"ContentItem"`
|
||||
Source string `xml:"source,attr"`
|
||||
SourceAccount string `xml:"sourceAccount,attr,omitempty"`
|
||||
ItemName string `xml:"itemName"`
|
||||
}
|
||||
|
||||
// Validate requires the source identity and replacement display name.
|
||||
func (r *SourceRenameRequest) Validate() error {
|
||||
if r == nil {
|
||||
return fmt.Errorf("source rename request is nil")
|
||||
}
|
||||
|
||||
if r.Source == "" {
|
||||
return fmt.Errorf("source is required")
|
||||
}
|
||||
|
||||
if r.ItemName == "" {
|
||||
return fmt.Errorf("item name is required")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSystemTimeoutXML(t *testing.T) {
|
||||
for _, enabled := range []bool{true, false} {
|
||||
input := `<systemtimeout><powersaving_enabled>` + map[bool]string{true: "true", false: "false"}[enabled] + `</powersaving_enabled></systemtimeout>`
|
||||
var setting SystemTimeout
|
||||
if err := xml.Unmarshal([]byte(input), &setting); err != nil {
|
||||
t.Fatalf("xml.Unmarshal(%q): %v", input, err)
|
||||
}
|
||||
if setting.PowerSavingEnabled != enabled {
|
||||
t.Fatalf("PowerSavingEnabled = %t, want %t", setting.PowerSavingEnabled, enabled)
|
||||
}
|
||||
|
||||
got, err := xml.Marshal(setting)
|
||||
if err != nil {
|
||||
t.Fatalf("xml.Marshal(): %v", err)
|
||||
}
|
||||
if string(got) != input {
|
||||
t.Fatalf("xml.Marshal() = %q, want %q", got, input)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemTimeoutRejectsInvalidXML(t *testing.T) {
|
||||
for _, input := range []string{
|
||||
`<systemtimeout/>`,
|
||||
`<systemtimeout><powersaving_enabled>maybe</powersaving_enabled></systemtimeout>`,
|
||||
`<wrong><powersaving_enabled>true</powersaving_enabled></wrong>`,
|
||||
} {
|
||||
var setting SystemTimeout
|
||||
if err := xml.Unmarshal([]byte(input), &setting); err == nil {
|
||||
t.Errorf("xml.Unmarshal(%q) unexpectedly succeeded", input)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRebroadcastLatencyModeXML(t *testing.T) {
|
||||
input := `<rebroadcastlatencymode mode="SYNC_TO_ZONE" controllable="true"></rebroadcastlatencymode>`
|
||||
var setting RebroadcastLatencyMode
|
||||
if err := xml.Unmarshal([]byte(input), &setting); err != nil {
|
||||
t.Fatalf("xml.Unmarshal(): %v", err)
|
||||
}
|
||||
if setting.Mode != RebroadcastLatencySyncToZone || !setting.Controllable {
|
||||
t.Fatalf("setting = %#v", setting)
|
||||
}
|
||||
if err := setting.Validate(); err != nil {
|
||||
t.Fatalf("Validate(): %v", err)
|
||||
}
|
||||
|
||||
request := RebroadcastLatencyModeRequest{Mode: RebroadcastLatencySyncToRoom}
|
||||
if err := request.Validate(); err != nil {
|
||||
t.Fatalf("Validate(): %v", err)
|
||||
}
|
||||
got, err := xml.Marshal(request)
|
||||
if err != nil {
|
||||
t.Fatalf("xml.Marshal(): %v", err)
|
||||
}
|
||||
if want := `<rebroadcastlatencymode mode="SYNC_TO_ROOM"></rebroadcastlatencymode>`; string(got) != want {
|
||||
t.Fatalf("xml.Marshal() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRebroadcastLatencyModeValidation(t *testing.T) {
|
||||
for _, input := range []string{
|
||||
`<rebroadcastlatencymode controllable="true"/>`,
|
||||
`<rebroadcastlatencymode mode="SYNC_TO_ROOM"/>`,
|
||||
`<rebroadcastlatencymode mode="OTHER" controllable="true"/>`,
|
||||
`<rebroadcastlatencymode mode="SYNC_TO_ROOM" controllable="maybe"/>`,
|
||||
} {
|
||||
var setting RebroadcastLatencyMode
|
||||
if err := xml.Unmarshal([]byte(input), &setting); err == nil {
|
||||
t.Errorf("xml.Unmarshal(%q) unexpectedly succeeded", input)
|
||||
}
|
||||
}
|
||||
|
||||
request := RebroadcastLatencyModeRequest{Mode: "OTHER"}
|
||||
if err := request.Validate(); err == nil {
|
||||
t.Error("Validate() unexpectedly accepted an unknown mode")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemLanguageCodesMatchStockholm(t *testing.T) {
|
||||
want := map[LanguageCode]string{
|
||||
1: "Dansk", 2: "Deutsch", 3: "English", 4: "Español", 5: "Français",
|
||||
6: "Italiano", 7: "Nederlands", 8: "Svenska", 9: "日本語", 10: "简体中文",
|
||||
11: "繁體中文", 12: "한국어", 13: "ไทย", 15: "Čeština", 16: "Suomi",
|
||||
17: "Ελληνικά", 18: "Norsk", 19: "Polski", 20: "Português", 21: "Română",
|
||||
22: "Русский", 23: "Slovenščina", 24: "Türkçe", 25: "Magyar",
|
||||
}
|
||||
if !reflect.DeepEqual(SystemLanguageNames(), want) {
|
||||
t.Fatalf("SystemLanguageNames() = %#v, want %#v", SystemLanguageNames(), want)
|
||||
}
|
||||
if LanguageEnglish != 3 || LanguageCzech != 15 {
|
||||
t.Fatalf("English/Czech codes = %d/%d, want 3/15", LanguageEnglish, LanguageCzech)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemLanguageReadAndWriteValidation(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
input string
|
||||
code LanguageCode
|
||||
}{
|
||||
{`<sysLanguage>15</sysLanguage>`, LanguageCzech},
|
||||
{`<sysLanguage>99</sysLanguage>`, 99},
|
||||
} {
|
||||
var language SystemLanguage
|
||||
if err := xml.Unmarshal([]byte(test.input), &language); err != nil {
|
||||
t.Fatalf("xml.Unmarshal(%q): %v", test.input, err)
|
||||
}
|
||||
if language.Code != test.code {
|
||||
t.Fatalf("Code = %d, want %d", language.Code, test.code)
|
||||
}
|
||||
}
|
||||
|
||||
known := SystemLanguage{Code: LanguageEnglish}
|
||||
if err := known.Validate(); err != nil {
|
||||
t.Fatalf("Validate(English): %v", err)
|
||||
}
|
||||
got, err := xml.Marshal(known)
|
||||
if err != nil {
|
||||
t.Fatalf("xml.Marshal(): %v", err)
|
||||
}
|
||||
if want := `<sysLanguage>3</sysLanguage>`; string(got) != want {
|
||||
t.Fatalf("xml.Marshal() = %q, want %q", got, want)
|
||||
}
|
||||
|
||||
unknown := SystemLanguage{Code: 99}
|
||||
if err := unknown.Validate(); err == nil {
|
||||
t.Error("Validate() unexpectedly accepted unknown code 99")
|
||||
}
|
||||
names := SystemLanguageNames()
|
||||
names[99] = "Future language"
|
||||
if err := unknown.Validate(); err == nil {
|
||||
t.Error("Validate() was widened by a caller-modified display map")
|
||||
}
|
||||
if _, ok := SystemLanguageNames()[99]; ok {
|
||||
t.Error("SystemLanguageNames() returned shared mutable state")
|
||||
}
|
||||
var missing SystemLanguage
|
||||
if err := xml.Unmarshal([]byte(`<sysLanguage/>`), &missing); err == nil {
|
||||
t.Error("xml.Unmarshal() unexpectedly accepted a missing language code")
|
||||
}
|
||||
var malformed SystemLanguage
|
||||
if err := xml.Unmarshal([]byte(`<sysLanguage>English</sysLanguage>`), &malformed); err == nil {
|
||||
t.Error("xml.Unmarshal() unexpectedly accepted a non-integer language")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBluetoothInfoXML(t *testing.T) {
|
||||
input := `<BluetoothInfo BluetoothMACAddress="AABBCCDDEEFF"></BluetoothInfo>`
|
||||
var info BluetoothInfo
|
||||
if err := xml.Unmarshal([]byte(input), &info); err != nil {
|
||||
t.Fatalf("xml.Unmarshal(): %v", err)
|
||||
}
|
||||
if info.BluetoothMACAddress != "AABBCCDDEEFF" {
|
||||
t.Fatalf("BluetoothMACAddress = %q", info.BluetoothMACAddress)
|
||||
}
|
||||
if err := info.Validate(); err != nil {
|
||||
t.Fatalf("Validate(): %v", err)
|
||||
}
|
||||
if err := (*BluetoothInfo)(nil).Validate(); err == nil {
|
||||
t.Fatal("nil Validate() unexpectedly succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceRenameRequestXMLAndValidation(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
request SourceRenameRequest
|
||||
want string
|
||||
}{
|
||||
{
|
||||
request: SourceRenameRequest{Source: "AUX", SourceAccount: "AUX1", ItemName: "Turntable"},
|
||||
want: `<ContentItem source="AUX" sourceAccount="AUX1"><itemName>Turntable</itemName></ContentItem>`,
|
||||
},
|
||||
{
|
||||
request: SourceRenameRequest{Source: "BLUETOOTH", ItemName: "Phone"},
|
||||
want: `<ContentItem source="BLUETOOTH"><itemName>Phone</itemName></ContentItem>`,
|
||||
},
|
||||
} {
|
||||
if err := test.request.Validate(); err != nil {
|
||||
t.Fatalf("Validate(): %v", err)
|
||||
}
|
||||
got, err := xml.Marshal(test.request)
|
||||
if err != nil {
|
||||
t.Fatalf("xml.Marshal(): %v", err)
|
||||
}
|
||||
if string(got) != test.want {
|
||||
t.Fatalf("xml.Marshal() = %q, want %q", got, test.want)
|
||||
}
|
||||
}
|
||||
|
||||
for _, request := range []*SourceRenameRequest{
|
||||
nil,
|
||||
{ItemName: "Name"},
|
||||
{Source: "AUX"},
|
||||
} {
|
||||
if err := request.Validate(); err == nil {
|
||||
t.Errorf("Validate(%#v) unexpectedly succeeded", request)
|
||||
}
|
||||
}
|
||||
}
|
||||
+221
-84
@@ -99,6 +99,18 @@ func isTuneInOpmlURI(rawURL string) bool {
|
||||
return strings.EqualFold(u.Hostname(), "opml.radiotime.com")
|
||||
}
|
||||
|
||||
// tuneInRawItems extracts a response's item list, trying "Items" (the
|
||||
// v1.3 search/profiles API shape) first, then falling back to "body"
|
||||
// (the legacy/OPML shape).
|
||||
func tuneInRawItems(data map[string]interface{}) []interface{} {
|
||||
items, ok := data["Items"].([]interface{})
|
||||
if !ok {
|
||||
items, _ = data["body"].([]interface{})
|
||||
}
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
// tuneInRenderJSONURI returns the URL with render=json set as a query parameter,
|
||||
// replacing any existing render value instead of appending a duplicate.
|
||||
func tuneInRenderJSONURI(rawURL string) string {
|
||||
@@ -211,37 +223,41 @@ func tuneInSectionsAshx(tuneInURI string, subsection *int) ([]models.BmxNavSecti
|
||||
}
|
||||
|
||||
itemType, _ := m["type"].(string)
|
||||
|
||||
if children, ok := m["children"].([]interface{}); ok && len(children) > 0 {
|
||||
name, _ := m["text"].(string)
|
||||
|
||||
section := models.BmxNavSection{
|
||||
Name: name,
|
||||
Items: make([]models.BmxNavItem, 0, len(children)),
|
||||
}
|
||||
|
||||
for _, child := range children {
|
||||
cm, ok := child.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
childType, _ := cm["type"].(string)
|
||||
if childType == "audio" {
|
||||
section.Items = append(section.Items, tuneInNavigatePlayItem(cm))
|
||||
} else {
|
||||
section.Items = append(section.Items, tuneInNavigateLink(cm))
|
||||
}
|
||||
}
|
||||
|
||||
sections = append(sections, section)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
switch itemType {
|
||||
case "link":
|
||||
if children, ok := m["children"].([]interface{}); ok && len(children) > 0 {
|
||||
name, _ := m["text"].(string)
|
||||
|
||||
section := models.BmxNavSection{
|
||||
Name: name,
|
||||
Items: make([]models.BmxNavItem, 0, len(children)),
|
||||
}
|
||||
for _, child := range children {
|
||||
cm, ok := child.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
childType, _ := cm["type"].(string)
|
||||
if childType == "audio" {
|
||||
section.Items = append(section.Items, tuneInNavigatePlayItem(cm))
|
||||
} else {
|
||||
section.Items = append(section.Items, tuneInNavigateLink(cm))
|
||||
}
|
||||
}
|
||||
|
||||
sections = append(sections, section)
|
||||
} else {
|
||||
topItems = append(topItems, tuneInNavigateLink(m))
|
||||
}
|
||||
topItems = append(topItems, tuneInNavigateLink(m))
|
||||
case "audio":
|
||||
topItems = append(topItems, tuneInNavigatePlayItem(m))
|
||||
case "text":
|
||||
// Ignore info text
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
@@ -346,11 +362,7 @@ func TuneInSearch(query string) (*models.BmxNavResponse, error) {
|
||||
Layout: "classic",
|
||||
}
|
||||
|
||||
// Try "Items" (v1.3) first, then "body" (legacy)
|
||||
items, ok := data["Items"].([]interface{})
|
||||
if !ok {
|
||||
items, _ = data["body"].([]interface{})
|
||||
}
|
||||
items := tuneInRawItems(data)
|
||||
|
||||
for idx, item := range items {
|
||||
m, ok := item.(map[string]interface{})
|
||||
@@ -389,20 +401,12 @@ func tuneInSearchSection(item map[string]interface{}, idx int, query, layout str
|
||||
|
||||
// Pivots.More.Url is the "load more" cursor from the TuneIn profiles API.
|
||||
// It is only present when there are more results beyond the first page.
|
||||
if pivots, ok := item["Pivots"].(map[string]interface{}); ok {
|
||||
if more, ok := pivots["More"].(map[string]interface{}); ok {
|
||||
if containerURL, _ := more["Url"].(string); strings.Contains(containerURL, "itemToken") {
|
||||
if u, err := url.Parse(containerURL); err == nil && allowedTuneInHosts[u.Hostname()] {
|
||||
encoded := base64.RawURLEncoding.EncodeToString([]byte(containerURL))
|
||||
|
||||
if section.Links == nil {
|
||||
section.Links = &models.Links{}
|
||||
}
|
||||
|
||||
section.Links.BmxNext = &models.Link{Href: "/v1/search/next?cursor=" + encoded}
|
||||
}
|
||||
}
|
||||
if next := tuneInMoreCursorLink(item); next != nil {
|
||||
if section.Links == nil {
|
||||
section.Links = &models.Links{}
|
||||
}
|
||||
|
||||
section.Links.BmxNext = next
|
||||
}
|
||||
|
||||
for _, child := range children {
|
||||
@@ -411,25 +415,42 @@ func tuneInSearchSection(item map[string]interface{}, idx int, query, layout str
|
||||
continue
|
||||
}
|
||||
|
||||
typeStr, _ := cm["Type"].(string)
|
||||
if typeStr == "" {
|
||||
typeStr, _ = cm["className"].(string)
|
||||
}
|
||||
|
||||
switch typeStr {
|
||||
case "Station", "PlayItem", "Topic":
|
||||
// Topics are single podcast episodes (t<N>) — Tune.ashx
|
||||
// accepts them just like station IDs, so the same play-link
|
||||
// shape works.
|
||||
section.Items = append(section.Items, tuneInSearchPlayItem(cm))
|
||||
case "Program", "Profile":
|
||||
section.Items = append(section.Items, tuneInSearchProfile(cm, name))
|
||||
}
|
||||
section.Items = append(section.Items, tuneInClassifyItem(cm))
|
||||
}
|
||||
|
||||
return section
|
||||
}
|
||||
|
||||
// tuneInMoreCursorLink builds a BmxNext pagination link from item's
|
||||
// Pivots.More.Url, the "load more" cursor the TuneIn search/profiles API
|
||||
// attaches once there are more results than fit on the first page. Returns
|
||||
// nil if there's nothing more to load.
|
||||
func tuneInMoreCursorLink(item map[string]interface{}) *models.Link {
|
||||
pivots, ok := item["Pivots"].(map[string]interface{})
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
more, ok := pivots["More"].(map[string]interface{})
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
containerURL, _ := more["Url"].(string)
|
||||
if !strings.Contains(containerURL, "itemToken") {
|
||||
return nil
|
||||
}
|
||||
|
||||
u, err := url.Parse(containerURL)
|
||||
if err != nil || !allowedTuneInHosts[u.Hostname()] {
|
||||
return nil
|
||||
}
|
||||
|
||||
encoded := base64.RawURLEncoding.EncodeToString([]byte(containerURL))
|
||||
|
||||
return &models.Link{Href: "/v1/search/next?cursor=" + encoded}
|
||||
}
|
||||
|
||||
// TuneInSearchNext fetches the remaining results for a section using the opaque
|
||||
// cursor produced by TuneInSearch. The cursor URL returns a flat Items[] list
|
||||
// (not nested containers), so we parse items directly rather than via
|
||||
@@ -453,10 +474,7 @@ func TuneInSearchNext(encodedCursor string) (*models.BmxNavResponse, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rawItems, ok := data["Items"].([]interface{})
|
||||
if !ok {
|
||||
rawItems, _ = data["body"].([]interface{})
|
||||
}
|
||||
rawItems := tuneInRawItems(data)
|
||||
|
||||
navItems := make([]models.BmxNavItem, 0, len(rawItems))
|
||||
for _, raw := range rawItems {
|
||||
@@ -465,13 +483,7 @@ func TuneInSearchNext(encodedCursor string) (*models.BmxNavResponse, error) {
|
||||
continue
|
||||
}
|
||||
|
||||
typeStr, _ := m["Type"].(string)
|
||||
switch typeStr {
|
||||
case "Station", "PlayItem", "Topic":
|
||||
navItems = append(navItems, tuneInSearchPlayItem(m))
|
||||
case "Program", "Profile":
|
||||
navItems = append(navItems, tuneInSearchProfile(m, ""))
|
||||
}
|
||||
navItems = append(navItems, tuneInClassifyItem(m))
|
||||
}
|
||||
|
||||
return &models.BmxNavResponse{
|
||||
@@ -548,7 +560,7 @@ func tuneInSearchProfile(item map[string]interface{}, _ string) models.BmxNavIte
|
||||
// Artists/Stations/etc are typically navigated first.
|
||||
if typeStr, _ := item["Type"].(string); typeStr == "Program" {
|
||||
if guideID, _ := item["GuideId"].(string); guideID != "" {
|
||||
encodedName := base64.URLEncoding.EncodeToString([]byte(profileName))
|
||||
encodedName := base64.RawURLEncoding.EncodeToString([]byte(profileName))
|
||||
playbackHref := fmt.Sprintf("/v1/playback/episodes/%s?encoded_name=%s", guideID, encodedName)
|
||||
|
||||
return models.BmxNavItem{
|
||||
@@ -561,7 +573,7 @@ func tuneInSearchProfile(item map[string]interface{}, _ string) models.BmxNavIte
|
||||
Type: "tracklisturl",
|
||||
},
|
||||
BmxNavigate: &models.Link{
|
||||
Href: "/v1/navigate/profiles/" + base64.URLEncoding.EncodeToString([]byte(href)),
|
||||
Href: "/v1/navigate/profiles/" + base64.RawURLEncoding.EncodeToString([]byte(href)),
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -596,46 +608,171 @@ func TuneInNavigateProfile(encodedURI string) (*models.BmxNavResponse, error) {
|
||||
|
||||
navResp := &models.BmxNavResponse{
|
||||
Links: &models.Links{
|
||||
Self: &models.Link{Href: "/v1/navigate/profile/" + encodedURI},
|
||||
Self: &models.Link{Href: "/v1/navigate/profiles/" + encodedURI},
|
||||
},
|
||||
Layout: "classic",
|
||||
}
|
||||
|
||||
// Profiles contain "pivots" (sections like "Programs", "Related", etc.)
|
||||
pivots, _ := data["pivots"].([]interface{})
|
||||
for _, p := range pivots {
|
||||
// The profiles API (api.radiotime.com/profiles/...) nests everything under
|
||||
// "Item", and its pivots ("Contents", "Related", etc.) are an *object*
|
||||
// keyed by pivot name, e.g.:
|
||||
// {"Item": {..., "Pivots": {"Contents": {"DisplayName": "Broadcasts", "Url": "..."}}}}
|
||||
// (Earlier code assumed a top-level "pivots" array with "text"/"URL"
|
||||
// fields, which never matched this response and left bmx_sections empty.)
|
||||
item, _ := data["Item"].(map[string]interface{})
|
||||
pivots, _ := item["Pivots"].(map[string]interface{})
|
||||
|
||||
for pivotName, p := range pivots {
|
||||
// We only care about the "Contents" pivot for now (the main list).
|
||||
if !strings.EqualFold(pivotName, "contents") {
|
||||
continue
|
||||
}
|
||||
|
||||
pivot, ok := p.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
pivotName, _ := pivot["text"].(string)
|
||||
pivotURL, _ := pivot["URL"].(string)
|
||||
|
||||
// We only care about the "Contents" pivot for now (the main list)
|
||||
if !strings.EqualFold(pivotName, "contents") {
|
||||
pivotURL, _ := pivot["Url"].(string)
|
||||
if pivotURL == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
displayName, _ := pivot["DisplayName"].(string)
|
||||
if displayName == "" {
|
||||
displayName = pivotName
|
||||
}
|
||||
|
||||
contents, err := fetchJSON(tuneInRenderJSONURI(pivotURL))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
body, _ := contents["body"].([]interface{})
|
||||
for idx, item := range body {
|
||||
m, ok := item.(map[string]interface{})
|
||||
rawItems := tuneInRawItems(contents)
|
||||
|
||||
// The Contents pivot doesn't return playable items directly: each
|
||||
// top-level entry is a "Container" (identified by a "ContainerType"
|
||||
// field, e.g. GuideId "v5", Title "Episodes") whose real payload is
|
||||
// its own "Children" (or legacy lowercase "children") array. A
|
||||
// Container also carries a "Pivots.More" cursor once there are more
|
||||
// children than fit on this page. Build one BmxNavSection per
|
||||
// container (falling back to treating the entry itself as a leaf
|
||||
// item only when it isn't a Container at all, in case some profile
|
||||
// types ever return a flat list here).
|
||||
for _, raw := range rawItems {
|
||||
m, ok := raw.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
navResp.BmxSections = append(navResp.BmxSections, tuneInSearchSection(m, idx, "", "list"))
|
||||
children, hasChildren := m["Children"].([]interface{})
|
||||
if !hasChildren {
|
||||
children, hasChildren = m["children"].([]interface{})
|
||||
}
|
||||
|
||||
if !hasChildren || len(children) == 0 {
|
||||
if _, isContainer := m["ContainerType"].(string); isContainer {
|
||||
// An empty container (e.g. no episodes published yet)
|
||||
// has nothing playable to show; skip it rather than
|
||||
// mistakenly treating its own GuideId (which identifies
|
||||
// the container, not a track) as a playback link.
|
||||
continue
|
||||
}
|
||||
|
||||
navResp.BmxSections = append(navResp.BmxSections, models.BmxNavSection{
|
||||
Name: displayName,
|
||||
Layout: "list",
|
||||
Items: []models.BmxNavItem{tuneInClassifyItem(m)},
|
||||
})
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
sectionName, _ := m["Title"].(string)
|
||||
if sectionName == "" {
|
||||
sectionName = displayName
|
||||
}
|
||||
|
||||
navItems := make([]models.BmxNavItem, 0, len(children))
|
||||
|
||||
for _, child := range children {
|
||||
cm, ok := child.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
navItems = append(navItems, tuneInClassifyItem(cm))
|
||||
}
|
||||
|
||||
section := models.BmxNavSection{
|
||||
Name: sectionName,
|
||||
Layout: "list",
|
||||
Items: navItems,
|
||||
}
|
||||
|
||||
if next := tuneInMoreCursorLink(m); next != nil {
|
||||
section.Links = &models.Links{BmxNext: next}
|
||||
}
|
||||
|
||||
navResp.BmxSections = append(navResp.BmxSections, section)
|
||||
}
|
||||
}
|
||||
|
||||
return navResp, nil
|
||||
}
|
||||
|
||||
// tuneInClassifyItem maps a single TuneIn item (a search/search-next
|
||||
// result, a section child, or a profile Contents/Container child) to a
|
||||
// BmxNavItem based on its "Type". Program/Profile items navigate to
|
||||
// another profile page; Station/PlayItem/Topic are played directly by
|
||||
// their own GuideId via Tune.ashx (Topics are single on-demand episodes/
|
||||
// broadcasts (t<N>) — Tune.ashx accepts them just like station IDs, so the
|
||||
// same play-link shape works).
|
||||
//
|
||||
// This intentionally does NOT use /v1/playback/episodes/{GuideId}
|
||||
// (tracklisturl) for any of these: that route is backed by
|
||||
// TuneInPodcastInfo, which is a stub that always returns an empty track
|
||||
// list (see its doc comment) - a speaker given that location has nothing
|
||||
// to play. /v1/playback/station/{GuideId} (bmx.TuneInPlayback) is the one
|
||||
// path in this codebase proven to resolve a raw TuneIn GuideId - including
|
||||
// a "t"-prefixed topic id - to an actual stream, via Tune.ashx;
|
||||
// resolveTuneInProgramLatestEpisode+TuneInPlayback uses the exact same
|
||||
// call for a program's latest topic.
|
||||
//
|
||||
// A type this code doesn't otherwise recognize is *also* given a playback
|
||||
// link rather than silently dropped: TuneIn's type list isn't guaranteed
|
||||
// stable, and dropping the item entirely (as this code used to for search
|
||||
// and search-next results) hides real content with no trace it existed.
|
||||
// Its Subtitle is marked instead, so a playback attempt that doesn't pan
|
||||
// out reads as "this content type isn't fully supported yet" rather than
|
||||
// a mystery broken link.
|
||||
func tuneInClassifyItem(m map[string]interface{}) models.BmxNavItem {
|
||||
typeStr, _ := m["Type"].(string)
|
||||
if typeStr == "" {
|
||||
typeStr, _ = m["className"].(string)
|
||||
}
|
||||
|
||||
switch typeStr {
|
||||
case "Program", "Profile":
|
||||
name, _ := m["Title"].(string)
|
||||
|
||||
return tuneInSearchProfile(m, name)
|
||||
case "Station", "PlayItem", "Topic":
|
||||
return tuneInSearchPlayItem(m)
|
||||
default:
|
||||
item := tuneInSearchPlayItem(m)
|
||||
|
||||
const uncertainNote = "Unrecognized type, may not play"
|
||||
if item.Subtitle == "" {
|
||||
item.Subtitle = uncertainNote
|
||||
} else {
|
||||
item.Subtitle = item.Subtitle + " (" + uncertainNote + ")"
|
||||
}
|
||||
|
||||
return item
|
||||
}
|
||||
}
|
||||
|
||||
func parseTuneInStreamBody(body []byte, guideID string) ([]string, error) {
|
||||
// TuneIn sometimes returns plain text with URLs or comments,
|
||||
// especially for .ashx or error responses.
|
||||
|
||||
@@ -2,10 +2,80 @@ package bmx
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
)
|
||||
|
||||
// TestTuneInSectionsAshx_UntypedContainerSurfacesStations is a regression
|
||||
// test for a real-world bug: TuneIn's Browse.ashx?render=json responses
|
||||
// often wrap the actual stations for a category in a container object that
|
||||
// has "children" but no "type" field at all (unlike navigable sub-categories,
|
||||
// which are always type:"link"). The original parser's switch only ever
|
||||
// extracted "children" when itemType == "link", so these untyped containers
|
||||
// -- and every station nested inside them -- were silently dropped: browse
|
||||
// showed only category links, never any actual stations. Reproduces the
|
||||
// shape of a real captured Jazz-genre browse response.
|
||||
func TestTuneInSectionsAshx_UntypedContainerSurfacesStations(t *testing.T) {
|
||||
const wantStationName = "SmoothJazz.com.pl (Poland)"
|
||||
|
||||
payload := `{
|
||||
"head": {"status": "200", "title": "Jazz"},
|
||||
"body": [
|
||||
{
|
||||
"text": "Stations",
|
||||
"key": "stations",
|
||||
"children": [
|
||||
{
|
||||
"type": "audio",
|
||||
"text": "` + wantStationName + `",
|
||||
"URL": "http://opml.radiotime.com/Tune.ashx?id=s106565",
|
||||
"guide_id": "s106565",
|
||||
"subtext": "Smooth Jazz"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}`
|
||||
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(payload))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
parsed, err := url.Parse(ts.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("could not parse test server URL: %v", err)
|
||||
}
|
||||
|
||||
allowedTuneInHosts[parsed.Hostname()] = true
|
||||
defer delete(allowedTuneInHosts, parsed.Hostname())
|
||||
|
||||
sections, err := tuneInSectionsAshx(ts.URL, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("tuneInSectionsAshx returned error: %v", err)
|
||||
}
|
||||
|
||||
for _, section := range sections {
|
||||
for _, item := range section.Items {
|
||||
if item.Name == wantStationName {
|
||||
if item.Links == nil || item.Links.BmxPlayback == nil {
|
||||
t.Errorf("station %q was surfaced but has no BmxPlayback link: %+v", wantStationName, item)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t.Fatalf("expected station %q to be surfaced from the untyped container, got sections: %+v", wantStationName, sections)
|
||||
}
|
||||
|
||||
func TestTuneInRenderJSONURI(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -452,3 +522,202 @@ func TestParseTuneInProgramContents(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTuneInNavigateProfileHandlesContainerShapes is a regression test for
|
||||
// four bugs found reviewing PR #677's profile-navigate fix:
|
||||
// - an empty Container (no children, identified by "ContainerType") was
|
||||
// misread as a leaf item and turned into a bogus playback link keyed by
|
||||
// the container's own non-playable GuideId (it checked "Type", which
|
||||
// only leaf items carry, instead of "ContainerType");
|
||||
// - the legacy lowercase "children" key (as opposed to "Children") was no
|
||||
// longer read at all, silently hiding any container using it;
|
||||
// - the Pivots.More.Url "load more" pagination cursor was dropped
|
||||
// entirely, so a container's BmxNext link was never built; and
|
||||
// - the response's own self link used "/v1/navigate/profile/" (singular),
|
||||
// which none of the route dispatchers that recognize "profiles"
|
||||
// (plural) actually match, breaking re-navigation via that link.
|
||||
func TestTuneInNavigateProfileHandlesContainerShapes(t *testing.T) {
|
||||
var contentsURL string
|
||||
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
switch r.URL.Path {
|
||||
case "/profile":
|
||||
_, _ = w.Write([]byte(`{
|
||||
"Item": {
|
||||
"Pivots": {
|
||||
"Contents": {"DisplayName": "Broadcasts", "Url": "` + contentsURL + `"}
|
||||
}
|
||||
}
|
||||
}`))
|
||||
case "/contents":
|
||||
_, _ = w.Write([]byte(`{
|
||||
"Items": [
|
||||
{
|
||||
"Title": "Episodes",
|
||||
"GuideId": "v5",
|
||||
"ContainerType": "Topics",
|
||||
"Children": [
|
||||
{"Type": "Topic", "Title": "Ep 1", "GuideId": "t100"}
|
||||
],
|
||||
"Pivots": {"More": {"Url": "` + contentsURL + `?itemToken=abc"}}
|
||||
},
|
||||
{
|
||||
"Title": "Empty Container",
|
||||
"GuideId": "v6",
|
||||
"ContainerType": "Topics",
|
||||
"Children": []
|
||||
},
|
||||
{
|
||||
"Title": "Legacy Children",
|
||||
"GuideId": "v7",
|
||||
"ContainerType": "Topics",
|
||||
"children": [
|
||||
{"Type": "Topic", "Title": "Ep 2", "GuideId": "t200"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"Type": "Station",
|
||||
"Title": "Flat Leaf",
|
||||
"GuideId": "s999"
|
||||
}
|
||||
]
|
||||
}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
contentsURL = ts.URL + "/contents"
|
||||
|
||||
parsed, err := url.Parse(ts.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("could not parse test server URL: %v", err)
|
||||
}
|
||||
|
||||
allowedTuneInHosts[parsed.Hostname()] = true
|
||||
defer delete(allowedTuneInHosts, parsed.Hostname())
|
||||
|
||||
encodedURI := base64.RawURLEncoding.EncodeToString([]byte(ts.URL + "/profile"))
|
||||
|
||||
navResp, err := TuneInNavigateProfile(encodedURI)
|
||||
if err != nil {
|
||||
t.Fatalf("TuneInNavigateProfile returned error: %v", err)
|
||||
}
|
||||
|
||||
if navResp.Links == nil || navResp.Links.Self == nil {
|
||||
t.Fatalf("response has no self link: %+v", navResp)
|
||||
}
|
||||
|
||||
if want := "/v1/navigate/profiles/" + encodedURI; navResp.Links.Self.Href != want {
|
||||
t.Errorf("self link = %q, want %q (must match the \"profiles\" prefix the dispatchers recognize)", navResp.Links.Self.Href, want)
|
||||
}
|
||||
|
||||
byName := make(map[string]models.BmxNavSection, len(navResp.BmxSections))
|
||||
for _, section := range navResp.BmxSections {
|
||||
byName[section.Name] = section
|
||||
}
|
||||
|
||||
if _, found := byName["Empty Container"]; found {
|
||||
t.Errorf("empty container was surfaced as a section, want it skipped: %+v", navResp.BmxSections)
|
||||
}
|
||||
|
||||
episodes, ok := byName["Episodes"]
|
||||
if !ok {
|
||||
t.Fatalf("no \"Episodes\" section found: %+v", navResp.BmxSections)
|
||||
}
|
||||
|
||||
if len(episodes.Items) != 1 || episodes.Items[0].Name != "Ep 1" {
|
||||
t.Errorf("Episodes items = %+v, want exactly [Ep 1]", episodes.Items)
|
||||
}
|
||||
|
||||
if episodes.Links == nil || episodes.Links.BmxNext == nil || !strings.Contains(episodes.Links.BmxNext.Href, "/v1/search/next?cursor=") {
|
||||
t.Errorf("Episodes section missing BmxNext pagination link: %+v", episodes.Links)
|
||||
}
|
||||
|
||||
legacy, ok := byName["Legacy Children"]
|
||||
if !ok {
|
||||
t.Fatalf("no \"Legacy Children\" section found (lowercase \"children\" fallback not applied): %+v", navResp.BmxSections)
|
||||
}
|
||||
|
||||
if len(legacy.Items) != 1 || legacy.Items[0].Name != "Ep 2" {
|
||||
t.Errorf("Legacy Children items = %+v, want exactly [Ep 2]", legacy.Items)
|
||||
}
|
||||
|
||||
broadcasts, ok := byName["Broadcasts"]
|
||||
if !ok {
|
||||
t.Fatalf("no \"Broadcasts\" (flat leaf, pivot display name) section found: %+v", navResp.BmxSections)
|
||||
}
|
||||
|
||||
if len(broadcasts.Items) != 1 || broadcasts.Items[0].Name != "Flat Leaf" {
|
||||
t.Errorf("Broadcasts items = %+v, want exactly [Flat Leaf]", broadcasts.Items)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTuneInClassifyItemMarksUnrecognizedTypesInsteadOfDroppingThem covers
|
||||
// the shared classifier used by tuneInSearchSection, TuneInSearchNext, and
|
||||
// TuneInNavigateProfile's container children. Previously, tuneInSearchSection
|
||||
// and TuneInSearchNext each had their own switch with no default case, so an
|
||||
// item whose "Type" wasn't one of the 5 known values was silently omitted --
|
||||
// TuneIn's type list isn't guaranteed stable, and this hid real content with
|
||||
// no trace it existed. An unrecognized type now still gets a playback link,
|
||||
// with its Subtitle marked so a playback attempt that doesn't pan out reads
|
||||
// as "this content type isn't fully supported yet" rather than a mystery
|
||||
// broken link.
|
||||
func TestTuneInClassifyItemMarksUnrecognizedTypesInsteadOfDroppingThem(t *testing.T) {
|
||||
t.Run("known playable type is unmarked", func(t *testing.T) {
|
||||
item := tuneInClassifyItem(map[string]interface{}{
|
||||
"Type": "Station", "Title": "Jazz FM", "GuideId": "s123", "Subtitle": "Smooth Jazz",
|
||||
})
|
||||
|
||||
if item.Subtitle != "Smooth Jazz" {
|
||||
t.Errorf("Subtitle = %q, want unmodified %q", item.Subtitle, "Smooth Jazz")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Program/Profile type navigates instead of playing", func(t *testing.T) {
|
||||
item := tuneInClassifyItem(map[string]interface{}{
|
||||
"Type": "Program", "Title": "Some Show", "GuideId": "p123",
|
||||
})
|
||||
|
||||
if item.Links == nil || item.Links.BmxNavigate == nil {
|
||||
t.Errorf("Program item has no BmxNavigate link: %+v", item)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unrecognized type without existing subtitle", func(t *testing.T) {
|
||||
item := tuneInClassifyItem(map[string]interface{}{
|
||||
"Type": "SomeFutureType", "Title": "Mystery Item", "GuideId": "x123",
|
||||
})
|
||||
|
||||
if item.Links == nil || item.Links.BmxPlayback == nil {
|
||||
t.Fatalf("unrecognized-type item has no playback link, want it still playable: %+v", item)
|
||||
}
|
||||
|
||||
if item.Subtitle != "Unrecognized type, may not play" {
|
||||
t.Errorf("Subtitle = %q, want the unrecognized-type marker", item.Subtitle)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unrecognized type with existing subtitle appends the marker", func(t *testing.T) {
|
||||
item := tuneInClassifyItem(map[string]interface{}{
|
||||
"Type": "SomeFutureType", "Title": "Mystery Item", "GuideId": "x123", "Subtitle": "From Mystery Network",
|
||||
})
|
||||
|
||||
if !strings.Contains(item.Subtitle, "From Mystery Network") || !strings.Contains(item.Subtitle, "Unrecognized type") {
|
||||
t.Errorf("Subtitle = %q, want both the original subtitle and the unrecognized-type marker", item.Subtitle)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty type falls back to className, still unrecognized if className is also unknown", func(t *testing.T) {
|
||||
item := tuneInClassifyItem(map[string]interface{}{
|
||||
"className": "weirdLegacyThing", "Title": "Legacy Item", "GuideId": "y123",
|
||||
})
|
||||
|
||||
if !strings.Contains(item.Subtitle, "Unrecognized type") {
|
||||
t.Errorf("Subtitle = %q, want the unrecognized-type marker", item.Subtitle)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -428,10 +428,12 @@ func TestSettingsPersistence(t *testing.T) {
|
||||
ds := NewDataStore(tempDir)
|
||||
|
||||
settings := Settings{
|
||||
ServerURL: "http://myserver:8000",
|
||||
LogBodies: true,
|
||||
DiscoveryInterval: "10m",
|
||||
DiscoveryEnabled: true,
|
||||
ServerURL: "http://myserver:8000",
|
||||
LogBodies: true,
|
||||
DiscoveryInterval: "10m",
|
||||
DiscoveryEnabled: true,
|
||||
UpdateCheckInterval: "12h",
|
||||
UpdateCheckEnabled: true,
|
||||
}
|
||||
|
||||
err = ds.SaveSettings(settings)
|
||||
@@ -456,6 +458,64 @@ func TestSettingsPersistence(t *testing.T) {
|
||||
if loaded.DiscoveryEnabled != settings.DiscoveryEnabled {
|
||||
t.Errorf("Expected DiscoveryEnabled %v, got %v", settings.DiscoveryEnabled, loaded.DiscoveryEnabled)
|
||||
}
|
||||
if loaded.UpdateCheckInterval != settings.UpdateCheckInterval {
|
||||
t.Errorf("Expected UpdateCheckInterval %s, got %s", settings.UpdateCheckInterval, loaded.UpdateCheckInterval)
|
||||
}
|
||||
if loaded.UpdateCheckEnabled != settings.UpdateCheckEnabled {
|
||||
t.Errorf("Expected UpdateCheckEnabled %v, got %v", settings.UpdateCheckEnabled, loaded.UpdateCheckEnabled)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCheckState_MissingFileReturnsZeroValue verifies a fresh install
|
||||
// (or one where the update check has never run) gets a zero-value state,
|
||||
// not an error — same shape as GetSettings on a missing settings.json.
|
||||
func TestUpdateCheckState_MissingFileReturnsZeroValue(t *testing.T) {
|
||||
tempDir, err := os.MkdirTemp("", "update-check-missing-test-*")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
ds := NewDataStore(tempDir)
|
||||
|
||||
state, err := ds.GetUpdateCheckState()
|
||||
if err != nil {
|
||||
t.Fatalf("GetUpdateCheckState on a fresh install should not error, got: %v", err)
|
||||
}
|
||||
if state != (UpdateCheckState{}) {
|
||||
t.Errorf("Expected zero-value state, got %+v", state)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCheckState_Persistence is the roundtrip test, mirroring
|
||||
// TestSettingsPersistence.
|
||||
func TestUpdateCheckState_Persistence(t *testing.T) {
|
||||
tempDir, err := os.MkdirTemp("", "update-check-persist-test-*")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
ds := NewDataStore(tempDir)
|
||||
|
||||
state := UpdateCheckState{
|
||||
LastCheckedAt: "2026-08-09T12:00:00Z",
|
||||
LastSeenVersion: "v0.122.0",
|
||||
LastReleaseURL: "https://github.com/gesellix/Bose-SoundTouch/releases/tag/v0.122.0",
|
||||
}
|
||||
|
||||
if err := ds.SaveUpdateCheckState(state); err != nil {
|
||||
t.Fatalf("SaveUpdateCheckState failed: %v", err)
|
||||
}
|
||||
|
||||
loaded, err := ds.GetUpdateCheckState()
|
||||
if err != nil {
|
||||
t.Fatalf("GetUpdateCheckState failed: %v", err)
|
||||
}
|
||||
|
||||
if loaded != state {
|
||||
t.Errorf("Expected %+v, got %+v", state, loaded)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordActivity_EmptyKindReturnsNilNotError verifies GetActivityRecords
|
||||
|
||||
@@ -0,0 +1,764 @@
|
||||
package datastore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
)
|
||||
|
||||
func lifecycleTestGroup(master, left, right, name string) models.Group {
|
||||
return models.Group{
|
||||
Name: name,
|
||||
MasterDeviceID: master,
|
||||
Roles: models.GroupRoles{Roles: []models.GroupRole{
|
||||
{DeviceID: left, Role: "LEFT"},
|
||||
{DeviceID: right, Role: "RIGHT"},
|
||||
}},
|
||||
}
|
||||
}
|
||||
|
||||
func countLifecycleGroupFiles(t *testing.T, ds *DataStore, account string) int {
|
||||
t.Helper()
|
||||
|
||||
entries, err := os.ReadDir(ds.AccountDevicesDir(account))
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return 0
|
||||
}
|
||||
|
||||
t.Fatalf("read account devices directory: %v", err)
|
||||
}
|
||||
|
||||
count := 0
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() && strings.HasPrefix(entry.Name(), "Group_") && strings.HasSuffix(entry.Name(), ".xml") {
|
||||
count++
|
||||
}
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
func writeLifecycleGroup(t *testing.T, ds *DataStore, account, groupID string, group models.Group) {
|
||||
t.Helper()
|
||||
|
||||
group.ID = groupID
|
||||
|
||||
data, err := xml.MarshalIndent(&group, "", " ")
|
||||
if err != nil {
|
||||
t.Fatalf("marshal group %s: %v", groupID, err)
|
||||
}
|
||||
|
||||
if err := ds.rootMkdirAll(ds.AccountDevicesDir(account), 0755); err != nil {
|
||||
t.Fatalf("create account %s devices directory: %v", account, err)
|
||||
}
|
||||
|
||||
if err := ds.atomicWriteFile(ds.groupFilePath(account, groupID), append([]byte(xml.Header), data...)); err != nil {
|
||||
t.Fatalf("write group %s: %v", groupID, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupGenerationReservationsAreGlobal(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
|
||||
writeLifecycleGroup(t, ds, "ACCOUNT1", "1234567",
|
||||
lifecycleTestGroup("MASTER1", "MASTER1", "SLAVE1", "Active pair"))
|
||||
|
||||
if err := ds.rootMkdirAll(ds.AccountDevicesDir("ACCOUNT2"), 0755); err != nil {
|
||||
t.Fatalf("create tombstone account: %v", err)
|
||||
}
|
||||
if err := ds.atomicWriteFile(ds.retiredGroupFilePath("ACCOUNT2", "7654321"), []byte("retired\n")); err != nil {
|
||||
t.Fatalf("write cross-account tombstone: %v", err)
|
||||
}
|
||||
|
||||
locations, err := ds.loadGroupGenerationLocationsNoLock()
|
||||
if err != nil {
|
||||
t.Fatalf("load generation reservations: %v", err)
|
||||
}
|
||||
|
||||
if got := locations["1234567"]; len(got.active) != 1 || got.active[0].account != "ACCOUNT1" {
|
||||
t.Fatalf("active reservation = %#v, want ACCOUNT1", got)
|
||||
}
|
||||
if got := locations["7654321"]; len(got.retired) != 1 || got.retired[0].account != "ACCOUNT2" {
|
||||
t.Fatalf("retired reservation = %#v, want ACCOUNT2", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddGroupReusesStoredStereoPair(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
const account = "ACCOUNT1"
|
||||
|
||||
original := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Original name")
|
||||
original.SenderIPAddress = "192.0.2.10"
|
||||
|
||||
firstID, err := ds.AddGroup(account, &original)
|
||||
if err != nil {
|
||||
t.Fatalf("add original group: %v", err)
|
||||
}
|
||||
|
||||
retry := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Retry name")
|
||||
retry.Roles.Roles[0].IPAddress = "198.51.100.10"
|
||||
|
||||
retryID, err := ds.AddGroup(account, &retry)
|
||||
if err != nil {
|
||||
t.Fatalf("retry group creation: %v", err)
|
||||
}
|
||||
|
||||
if retryID != firstID {
|
||||
t.Fatalf("retry ID = %q, want stored ID %q", retryID, firstID)
|
||||
}
|
||||
|
||||
if retry.ID != firstID || retry.Name != original.Name || retry.SenderIPAddress != original.SenderIPAddress {
|
||||
t.Fatalf("retry returned %#v, want unchanged stored group %#v", retry, original)
|
||||
}
|
||||
|
||||
if got := countLifecycleGroupFiles(t, ds, account); got != 1 {
|
||||
t.Fatalf("stored group files = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddGroupRejectsExistingDeviceMembership(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
const account = "ACCOUNT1"
|
||||
|
||||
original := lifecycleTestGroup("MASTER1", "MASTER1", "SHARED", "First pair")
|
||||
if _, err := ds.AddGroup(account, &original); err != nil {
|
||||
t.Fatalf("add original group: %v", err)
|
||||
}
|
||||
|
||||
conflicting := lifecycleTestGroup("MASTER2", "MASTER2", "SHARED", "Conflicting pair")
|
||||
_, err := ds.AddGroup(account, &conflicting)
|
||||
if !errors.Is(err, ErrGroupMembershipConflict) {
|
||||
t.Fatalf("conflicting add error = %v, want ErrGroupMembershipConflict", err)
|
||||
}
|
||||
|
||||
if got := countLifecycleGroupFiles(t, ds, account); got != 1 {
|
||||
t.Fatalf("stored group files = %d after conflict, want 1", got)
|
||||
}
|
||||
|
||||
if group, getErr := ds.GetGroupForDevice(account, "SHARED"); getErr != nil || group.ID != original.ID {
|
||||
t.Fatalf("stored group changed after conflict: group=%#v err=%v", group, getErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddGroupRejectsCrossAccountMembership(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
requested models.Group
|
||||
}{
|
||||
{
|
||||
name: "same stereo pair",
|
||||
requested: lifecycleTestGroup("MASTER1", "MASTER1", "SLAVE1", "Same pair in another account"),
|
||||
},
|
||||
{
|
||||
name: "shared member",
|
||||
requested: lifecycleTestGroup("MASTER2", "MASTER2", "SLAVE1", "Conflicting pair in another account"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
stored := lifecycleTestGroup("MASTER1", "MASTER1", "SLAVE1", "Stored pair")
|
||||
writeLifecycleGroup(t, ds, "ACCOUNT1", "1234567", stored)
|
||||
|
||||
_, err := ds.AddGroup("ACCOUNT2", &test.requested)
|
||||
if !errors.Is(err, ErrGroupMembershipConflict) {
|
||||
t.Fatalf("cross-account add error = %v, want ErrGroupMembershipConflict", err)
|
||||
}
|
||||
if got := countLifecycleGroupFiles(t, ds, "ACCOUNT1"); got != 1 {
|
||||
t.Fatalf("source account group files = %d after conflict, want 1", got)
|
||||
}
|
||||
if got := countLifecycleGroupFiles(t, ds, "ACCOUNT2"); got != 0 {
|
||||
t.Fatalf("requested account group files = %d after conflict, want 0", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddGroupDoesNotReuseMalformedSuperset(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
const account = "ACCOUNT1"
|
||||
|
||||
original := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Pair")
|
||||
if _, err := ds.AddGroup(account, &original); err != nil {
|
||||
t.Fatalf("add original group: %v", err)
|
||||
}
|
||||
|
||||
malformed := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Pair")
|
||||
malformed.Roles.Roles = append(malformed.Roles.Roles, models.GroupRole{DeviceID: "EXTRA", Role: "CENTER"})
|
||||
if _, err := ds.AddGroup(account, &malformed); !errors.Is(err, ErrGroupMembershipConflict) {
|
||||
t.Fatalf("malformed superset error = %v, want ErrGroupMembershipConflict", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteGroupGenerationForDevice(t *testing.T) {
|
||||
t.Run("removes only the exact generation containing the device", func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
const (
|
||||
account = "ACCOUNT1"
|
||||
deviceID = "SLAVE1"
|
||||
)
|
||||
|
||||
first := lifecycleTestGroup("MASTER1", "MASTER1", "SLAVE1", "First pair")
|
||||
second := lifecycleTestGroup("MASTER2", "MASTER2", "SLAVE2", "Second pair")
|
||||
if _, err := ds.AddGroup(account, &first); err != nil {
|
||||
t.Fatalf("add first group: %v", err)
|
||||
}
|
||||
if _, err := ds.AddGroup(account, &second); err != nil {
|
||||
t.Fatalf("add second group: %v", err)
|
||||
}
|
||||
|
||||
if err := ds.DeleteGroupGenerationForDevice(deviceID, first.ID, &first); err != nil {
|
||||
t.Fatalf("delete exact generation: %v", err)
|
||||
}
|
||||
|
||||
if _, err := ds.GetGroupForDevice(account, deviceID); !errors.Is(err, ErrGroupNotFound) {
|
||||
t.Fatalf("deleted device lookup error = %v, want ErrGroupNotFound", err)
|
||||
}
|
||||
if group, err := ds.GetGroupForDevice(account, "SLAVE2"); err != nil || group.ID != second.ID {
|
||||
t.Fatalf("unrelated group was not preserved: group=%#v err=%v", group, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("stale generation is an idempotent no-op", func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
const account = "ACCOUNT1"
|
||||
|
||||
group := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Current pair")
|
||||
if _, err := ds.AddGroup(account, &group); err != nil {
|
||||
t.Fatalf("add group: %v", err)
|
||||
}
|
||||
|
||||
if err := ds.DeleteGroupGenerationForDevice("MASTER", "OLDER-ID", nil); err != nil {
|
||||
t.Fatalf("delete stale generation: %v", err)
|
||||
}
|
||||
|
||||
if current, err := ds.GetGroupForDevice(account, "MASTER"); err != nil || current.ID != group.ID {
|
||||
t.Fatalf("current generation changed: group=%#v err=%v", current, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing generation is idempotent", func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
if err := ds.DeleteGroupGenerationForDevice("MASTER", "PAIR-ID", nil); err != nil {
|
||||
t.Fatalf("delete missing generation: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ambiguous duplicate generation fails closed", func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
const deviceID = "MASTER"
|
||||
|
||||
first := lifecycleTestGroup(deviceID, deviceID, "SLAVE", "First pair")
|
||||
if _, err := ds.AddGroup("ACCOUNT1", &first); err != nil {
|
||||
t.Fatalf("add first group: %v", err)
|
||||
}
|
||||
|
||||
second := lifecycleTestGroup(deviceID, deviceID, "SLAVE", "Second pair")
|
||||
writeLifecycleGroup(t, ds, "ACCOUNT2", first.ID, second)
|
||||
|
||||
err := ds.DeleteGroupGenerationForDevice(deviceID, first.ID, &first)
|
||||
if !errors.Is(err, ErrGroupDeleteAmbiguous) {
|
||||
t.Fatalf("ambiguous delete error = %v, want ErrGroupDeleteAmbiguous", err)
|
||||
}
|
||||
if got := countLifecycleGroupFiles(t, ds, "ACCOUNT1") + countLifecycleGroupFiles(t, ds, "ACCOUNT2"); got != 2 {
|
||||
t.Fatalf("stored group files = %d after ambiguity, want 2", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("same ID for another device fails closed", func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
group := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Current pair")
|
||||
if _, err := ds.AddGroup("ACCOUNT1", &group); err != nil {
|
||||
t.Fatalf("add group: %v", err)
|
||||
}
|
||||
|
||||
err := ds.DeleteGroupGenerationForDevice("OTHER", group.ID, &group)
|
||||
if !errors.Is(err, ErrGroupDeleteAmbiguous) {
|
||||
t.Fatalf("wrong-device delete error = %v, want ErrGroupDeleteAmbiguous", err)
|
||||
}
|
||||
if !ds.rootExists(ds.groupFilePath("ACCOUNT1", group.ID)) {
|
||||
t.Fatal("wrong-device delete retired the active group")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("submitted topology must match the stored generation", func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
stored := lifecycleTestGroup("MASTER", "MASTER", "REAL-SLAVE", "Current pair")
|
||||
if _, err := ds.AddGroup("ACCOUNT1", &stored); err != nil {
|
||||
t.Fatalf("add group: %v", err)
|
||||
}
|
||||
|
||||
submitted := stored
|
||||
submitted.Roles.Roles = append([]models.GroupRole(nil), stored.Roles.Roles...)
|
||||
submitted.Roles.Roles[1].DeviceID = "SUBSTITUTE-SLAVE"
|
||||
err := ds.DeleteGroupGenerationForDevice("MASTER", stored.ID, &submitted)
|
||||
if !errors.Is(err, ErrGroupDeleteAmbiguous) {
|
||||
t.Fatalf("topology mismatch error = %v, want ErrGroupDeleteAmbiguous", err)
|
||||
}
|
||||
if !ds.rootExists(ds.groupFilePath("ACCOUNT1", stored.ID)) {
|
||||
t.Fatal("topology mismatch retired the active group")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("stored name drift does not prevent exact topology deletion", func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
stored := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Renamed pair")
|
||||
stored.Roles.Roles[0].IPAddress = "192.0.2.10"
|
||||
stored.Roles.Roles[1].IPAddress = "192.0.2.11"
|
||||
if _, err := ds.AddGroup("ACCOUNT1", &stored); err != nil {
|
||||
t.Fatalf("add group: %v", err)
|
||||
}
|
||||
|
||||
expected := stored
|
||||
expected.Name = "Original snapshot"
|
||||
if err := ds.DeleteGroupGenerationForDevice("MASTER", stored.ID, &expected); err != nil {
|
||||
t.Fatalf("delete generation after name drift: %v", err)
|
||||
}
|
||||
if ds.rootExists(ds.groupFilePath("ACCOUNT1", stored.ID)) {
|
||||
t.Fatal("name drift prevented retirement of the exact topology")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRenameGroupGenerationForDevice(t *testing.T) {
|
||||
t.Run("renames an exact generation across accounts", func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
|
||||
unrelated := lifecycleTestGroup("OTHER-MASTER", "OTHER-MASTER", "OTHER-SLAVE", "Unrelated pair")
|
||||
if _, err := ds.AddGroup("ACCOUNT1", &unrelated); err != nil {
|
||||
t.Fatalf("add unrelated group: %v", err)
|
||||
}
|
||||
|
||||
group := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Original name")
|
||||
group.Roles.Roles[0].IPAddress = "192.0.2.10"
|
||||
group.Roles.Roles[1].IPAddress = "192.0.2.11"
|
||||
if _, err := ds.AddGroup("ACCOUNT2", &group); err != nil {
|
||||
t.Fatalf("add group: %v", err)
|
||||
}
|
||||
|
||||
updated, err := ds.RenameGroupGenerationForDevice("MASTER", group.ID, &group, "Renamed pair")
|
||||
if err != nil {
|
||||
t.Fatalf("rename exact generation: %v", err)
|
||||
}
|
||||
if updated.ID != group.ID || updated.Name != "Renamed pair" {
|
||||
t.Fatalf("updated group = %#v, want ID %q and renamed name", updated, group.ID)
|
||||
}
|
||||
|
||||
stored, err := ds.GetGroupForDevice("ACCOUNT2", "MASTER")
|
||||
if err != nil || !reflect.DeepEqual(stored, updated) {
|
||||
t.Fatalf("stored renamed group = %#v err=%v, want %#v", stored, err, updated)
|
||||
}
|
||||
if current, err := ds.GetGroupForDevice("ACCOUNT1", "OTHER-MASTER"); err != nil || current.Name != unrelated.Name {
|
||||
t.Fatalf("unrelated group changed: group=%#v err=%v", current, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("retry allows the stored name to differ from expected", func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
group := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Original name")
|
||||
if _, err := ds.AddGroup("ACCOUNT", &group); err != nil {
|
||||
t.Fatalf("add group: %v", err)
|
||||
}
|
||||
|
||||
if _, err := ds.RenameGroupGenerationForDevice("MASTER", group.ID, &group, "Renamed pair"); err != nil {
|
||||
t.Fatalf("first rename: %v", err)
|
||||
}
|
||||
|
||||
updated, err := ds.RenameGroupGenerationForDevice("MASTER", group.ID, &group, "Renamed pair")
|
||||
if err != nil {
|
||||
t.Fatalf("idempotent rename retry: %v", err)
|
||||
}
|
||||
if updated.Name != "Renamed pair" {
|
||||
t.Fatalf("retry returned name %q, want Renamed pair", updated.Name)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("topology mismatch does not write", func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
stored := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Original name")
|
||||
stored.Roles.Roles[0].IPAddress = "192.0.2.10"
|
||||
stored.Roles.Roles[1].IPAddress = "192.0.2.11"
|
||||
if _, err := ds.AddGroup("ACCOUNT", &stored); err != nil {
|
||||
t.Fatalf("add group: %v", err)
|
||||
}
|
||||
|
||||
before, err := ds.rootReadFile(ds.groupFilePath("ACCOUNT", stored.ID))
|
||||
if err != nil {
|
||||
t.Fatalf("read group before rename: %v", err)
|
||||
}
|
||||
|
||||
expected := stored
|
||||
expected.Roles.Roles = append([]models.GroupRole(nil), stored.Roles.Roles...)
|
||||
expected.Roles.Roles[1].IPAddress = "198.51.100.11"
|
||||
_, err = ds.RenameGroupGenerationForDevice("MASTER", stored.ID, &expected, "Renamed pair")
|
||||
if !errors.Is(err, ErrGroupDeleteAmbiguous) {
|
||||
t.Fatalf("topology mismatch error = %v, want ErrGroupDeleteAmbiguous", err)
|
||||
}
|
||||
|
||||
after, err := ds.rootReadFile(ds.groupFilePath("ACCOUNT", stored.ID))
|
||||
if err != nil {
|
||||
t.Fatalf("read group after rename: %v", err)
|
||||
}
|
||||
if !bytes.Equal(after, before) {
|
||||
t.Fatal("topology mismatch rewrote the active group")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unrelated device does not write", func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
group := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Original name")
|
||||
if _, err := ds.AddGroup("ACCOUNT", &group); err != nil {
|
||||
t.Fatalf("add group: %v", err)
|
||||
}
|
||||
|
||||
before, err := ds.rootReadFile(ds.groupFilePath("ACCOUNT", group.ID))
|
||||
if err != nil {
|
||||
t.Fatalf("read group before rename: %v", err)
|
||||
}
|
||||
|
||||
_, err = ds.RenameGroupGenerationForDevice("OTHER", group.ID, &group, "Renamed pair")
|
||||
if !errors.Is(err, ErrGroupDeleteAmbiguous) {
|
||||
t.Fatalf("unrelated-device error = %v, want ErrGroupDeleteAmbiguous", err)
|
||||
}
|
||||
|
||||
after, err := ds.rootReadFile(ds.groupFilePath("ACCOUNT", group.ID))
|
||||
if err != nil {
|
||||
t.Fatalf("read group after rename: %v", err)
|
||||
}
|
||||
if !bytes.Equal(after, before) {
|
||||
t.Fatal("unrelated-device rename rewrote the active group")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ambiguous duplicate generation does not write", func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
group := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Original name")
|
||||
writeLifecycleGroup(t, ds, "ACCOUNT1", "1234567", group)
|
||||
writeLifecycleGroup(t, ds, "ACCOUNT2", "1234567", group)
|
||||
group.ID = "1234567"
|
||||
|
||||
_, err := ds.RenameGroupGenerationForDevice("MASTER", group.ID, &group, "Renamed pair")
|
||||
if !errors.Is(err, ErrGroupDeleteAmbiguous) {
|
||||
t.Fatalf("ambiguous rename error = %v, want ErrGroupDeleteAmbiguous", err)
|
||||
}
|
||||
|
||||
for _, account := range []string{"ACCOUNT1", "ACCOUNT2"} {
|
||||
stored, getErr := ds.GetGroupForDevice(account, "MASTER")
|
||||
if getErr != nil || stored.Name != "Original name" {
|
||||
t.Fatalf("group in %s changed after ambiguity: group=%#v err=%v", account, stored, getErr)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty name is rejected", func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
group := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Original name")
|
||||
if _, err := ds.AddGroup("ACCOUNT", &group); err != nil {
|
||||
t.Fatalf("add group: %v", err)
|
||||
}
|
||||
|
||||
_, err := ds.RenameGroupGenerationForDevice("MASTER", group.ID, &group, "")
|
||||
if !errors.Is(err, ErrGroupDeleteAmbiguous) {
|
||||
t.Fatalf("empty-name error = %v, want ErrGroupDeleteAmbiguous", err)
|
||||
}
|
||||
if current, getErr := ds.GetGroupForDevice("ACCOUNT", "MASTER"); getErr != nil || current.Name != group.Name {
|
||||
t.Fatalf("group changed after empty name: group=%#v err=%v", current, getErr)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("non-master device is rejected", func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
group := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Original name")
|
||||
if _, err := ds.AddGroup("ACCOUNT", &group); err != nil {
|
||||
t.Fatalf("add group: %v", err)
|
||||
}
|
||||
|
||||
_, err := ds.RenameGroupGenerationForDevice("SLAVE", group.ID, &group, "Renamed pair")
|
||||
if !errors.Is(err, ErrGroupDeleteAmbiguous) {
|
||||
t.Fatalf("non-master error = %v, want ErrGroupDeleteAmbiguous", err)
|
||||
}
|
||||
if current, getErr := ds.GetGroupForDevice("ACCOUNT", "MASTER"); getErr != nil || current.Name != group.Name {
|
||||
t.Fatalf("group changed after non-master rename: group=%#v err=%v", current, getErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestEnsureNoGroupsForDevicesReportsStaleGroupsAcrossAccountsWithoutMutation(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
const (
|
||||
firstID = "1234567"
|
||||
secondID = "7654321"
|
||||
)
|
||||
|
||||
first := lifecycleTestGroup("MOVED", "MOVED", "OLD-SLAVE-1", "First stale pair")
|
||||
writeLifecycleGroup(t, ds, "ACCOUNT1", firstID, first)
|
||||
|
||||
second := lifecycleTestGroup("MOVED", "MOVED", "OLD-SLAVE-2", "Second stale pair")
|
||||
writeLifecycleGroup(t, ds, "ACCOUNT2", secondID, second)
|
||||
|
||||
unrelated := lifecycleTestGroup("OTHER-MASTER", "OTHER-MASTER", "OTHER-SLAVE", "Unrelated pair")
|
||||
if _, err := ds.AddGroup("ACCOUNT3", &unrelated); err != nil {
|
||||
t.Fatalf("add unrelated group: %v", err)
|
||||
}
|
||||
|
||||
if firstID == unrelated.ID || secondID == unrelated.ID {
|
||||
t.Fatalf("active generation IDs are not globally unique: %q %q %q", firstID, secondID, unrelated.ID)
|
||||
}
|
||||
|
||||
firstBefore, err := ds.rootReadFile(ds.groupFilePath("ACCOUNT1", firstID))
|
||||
if err != nil {
|
||||
t.Fatalf("read first group before check: %v", err)
|
||||
}
|
||||
secondBefore, err := ds.rootReadFile(ds.groupFilePath("ACCOUNT2", secondID))
|
||||
if err != nil {
|
||||
t.Fatalf("read second group before check: %v", err)
|
||||
}
|
||||
|
||||
err = ds.EnsureNoGroupsForDevices([]string{"MOVED"})
|
||||
if !errors.Is(err, ErrGroupMembershipConflict) {
|
||||
t.Fatalf("cross-account check error = %v, want ErrGroupMembershipConflict", err)
|
||||
}
|
||||
|
||||
var conflict *GroupMembershipConflictError
|
||||
if !errors.As(err, &conflict) {
|
||||
t.Fatalf("cross-account check error type = %T, want *GroupMembershipConflictError", err)
|
||||
}
|
||||
wantGenerations := []GroupGeneration{
|
||||
{Account: "ACCOUNT1", ID: firstID},
|
||||
{Account: "ACCOUNT2", ID: secondID},
|
||||
}
|
||||
if !reflect.DeepEqual(conflict.Generations, wantGenerations) {
|
||||
t.Fatalf("conflicting generations = %#v, want %#v", conflict.Generations, wantGenerations)
|
||||
}
|
||||
|
||||
firstAfter, err := ds.rootReadFile(ds.groupFilePath("ACCOUNT1", firstID))
|
||||
if err != nil {
|
||||
t.Fatalf("read first group after check: %v", err)
|
||||
}
|
||||
secondAfter, err := ds.rootReadFile(ds.groupFilePath("ACCOUNT2", secondID))
|
||||
if err != nil {
|
||||
t.Fatalf("read second group after check: %v", err)
|
||||
}
|
||||
if !bytes.Equal(firstAfter, firstBefore) || !bytes.Equal(secondAfter, secondBefore) {
|
||||
t.Fatal("read-only group check changed active group data")
|
||||
}
|
||||
if ds.rootExists(ds.retiredGroupFilePath("ACCOUNT1", firstID)) ||
|
||||
ds.rootExists(ds.retiredGroupFilePath("ACCOUNT2", secondID)) {
|
||||
t.Fatal("read-only group check created a tombstone")
|
||||
}
|
||||
if got := countLifecycleGroupFiles(t, ds, "ACCOUNT3"); got != 1 {
|
||||
t.Fatalf("unrelated active group files = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetireGroupAtomicallyRenamesActiveXML(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
const (
|
||||
account = "ACCOUNT1"
|
||||
groupID = "1234567"
|
||||
)
|
||||
|
||||
group := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Pair")
|
||||
writeLifecycleGroup(t, ds, account, groupID, group)
|
||||
|
||||
activePath := ds.groupFilePath(account, groupID)
|
||||
retiredPath := ds.retiredGroupFilePath(account, groupID)
|
||||
activeInfo, err := os.Stat(activePath)
|
||||
if err != nil {
|
||||
t.Fatalf("stat active group: %v", err)
|
||||
}
|
||||
activeXML, err := os.ReadFile(activePath)
|
||||
if err != nil {
|
||||
t.Fatalf("read active group: %v", err)
|
||||
}
|
||||
|
||||
if err := ds.DeleteGroup(account, groupID); err != nil {
|
||||
t.Fatalf("retire group: %v", err)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(activePath); !os.IsNotExist(err) {
|
||||
t.Fatalf("active path stat error = %v, want not exist", err)
|
||||
}
|
||||
retiredInfo, err := os.Stat(retiredPath)
|
||||
if err != nil {
|
||||
t.Fatalf("stat retired group: %v", err)
|
||||
}
|
||||
if !os.SameFile(activeInfo, retiredInfo) {
|
||||
t.Fatal("retired group is not the renamed active file")
|
||||
}
|
||||
retiredXML, err := os.ReadFile(retiredPath)
|
||||
if err != nil {
|
||||
t.Fatalf("read retired group: %v", err)
|
||||
}
|
||||
if !bytes.Equal(retiredXML, activeXML) {
|
||||
t.Fatal("retired group did not preserve the active XML contents")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureNoGroupsForDevicesRejectsActiveTombstoneAmbiguity(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
|
||||
group := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Ambiguous pair")
|
||||
if _, err := ds.AddGroup("ACCOUNT1", &group); err != nil {
|
||||
t.Fatalf("add active group: %v", err)
|
||||
}
|
||||
|
||||
if err := ds.rootMkdirAll(ds.AccountDevicesDir("ACCOUNT2"), 0755); err != nil {
|
||||
t.Fatalf("create tombstone account: %v", err)
|
||||
}
|
||||
if err := ds.atomicWriteFile(ds.retiredGroupFilePath("ACCOUNT2", group.ID), []byte("retired\n")); err != nil {
|
||||
t.Fatalf("write conflicting tombstone: %v", err)
|
||||
}
|
||||
|
||||
err := ds.EnsureNoGroupsForDevices([]string{"MASTER"})
|
||||
if !errors.Is(err, ErrGroupDeleteAmbiguous) {
|
||||
t.Fatalf("ambiguous check error = %v, want ErrGroupDeleteAmbiguous", err)
|
||||
}
|
||||
if !ds.rootExists(ds.groupFilePath("ACCOUNT1", group.ID)) {
|
||||
t.Fatal("ambiguous check removed the active group")
|
||||
}
|
||||
if _, readErr := ds.rootReadFile(ds.retiredGroupFilePath("ACCOUNT2", group.ID)); readErr != nil {
|
||||
t.Fatalf("ambiguous check changed the tombstone: %v", readErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupReadsFailClosedOnMalformedOrUnreadableData(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setup func(t *testing.T, ds *DataStore) string
|
||||
}{
|
||||
{
|
||||
name: "malformed XML",
|
||||
setup: func(t *testing.T, ds *DataStore) string {
|
||||
t.Helper()
|
||||
|
||||
path := ds.groupFilePath("ACCOUNT1", "1234567")
|
||||
if err := ds.rootMkdirAll(ds.AccountDevicesDir("ACCOUNT1"), 0755); err != nil {
|
||||
t.Fatalf("create account directory: %v", err)
|
||||
}
|
||||
if err := ds.atomicWriteFile(path, []byte("<group>")); err != nil {
|
||||
t.Fatalf("write malformed group: %v", err)
|
||||
}
|
||||
|
||||
return path
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unreadable group",
|
||||
setup: func(t *testing.T, ds *DataStore) string {
|
||||
t.Helper()
|
||||
|
||||
if err := ds.rootMkdirAll(ds.AccountDevicesDir("ACCOUNT1"), 0755); err != nil {
|
||||
t.Fatalf("create account directory: %v", err)
|
||||
}
|
||||
path := ds.groupFilePath("ACCOUNT1", "1234567")
|
||||
if err := os.Symlink("missing-group-target", path); err != nil {
|
||||
t.Fatalf("create unreadable group symlink: %v", err)
|
||||
}
|
||||
|
||||
return path
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
path := test.setup(t, ds)
|
||||
|
||||
if err := ds.EnsureNoGroupsForDevices([]string{"MASTER"}); err == nil {
|
||||
t.Fatal("EnsureNoGroupsForDevices error = nil, want datastore error")
|
||||
}
|
||||
if _, err := ds.GetGroupForDevice("ACCOUNT1", "MASTER"); err == nil || errors.Is(err, ErrGroupNotFound) {
|
||||
t.Fatalf("GetGroupForDevice error = %v, want datastore error", err)
|
||||
}
|
||||
if _, err := os.Lstat(path); err != nil {
|
||||
t.Fatalf("fail-closed reads mutated group path: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetGroupForDeviceFailsClosedOnDuplicateMembership(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
first := lifecycleTestGroup("MASTER1", "MASTER1", "SHARED", "First pair")
|
||||
second := lifecycleTestGroup("MASTER2", "MASTER2", "SHARED", "Second pair")
|
||||
|
||||
writeLifecycleGroup(t, ds, "ACCOUNT1", "1234567", first)
|
||||
writeLifecycleGroup(t, ds, "ACCOUNT1", "7654321", second)
|
||||
|
||||
group, err := ds.GetGroupForDevice("ACCOUNT1", "SHARED")
|
||||
if group != nil || !errors.Is(err, ErrGroupMembershipConflict) {
|
||||
t.Fatalf("group=%#v error=%v, want membership conflict", group, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteGroupClassifiesMissingAndAmbiguousGenerations(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
|
||||
if err := ds.DeleteGroup("ACCOUNT1", "1234567"); !errors.Is(err, ErrGroupNotFound) {
|
||||
t.Fatalf("missing delete error = %v, want ErrGroupNotFound", err)
|
||||
}
|
||||
|
||||
group := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Ambiguous pair")
|
||||
writeLifecycleGroup(t, ds, "ACCOUNT1", "7654321", group)
|
||||
if err := ds.atomicWriteFile(ds.retiredGroupFilePath("ACCOUNT1", "7654321"), []byte("retired\n")); err != nil {
|
||||
t.Fatalf("write conflicting tombstone: %v", err)
|
||||
}
|
||||
|
||||
err := ds.DeleteGroup("ACCOUNT1", "7654321")
|
||||
if !errors.Is(err, ErrGroupDeleteAmbiguous) {
|
||||
t.Fatalf("ambiguous delete error = %v, want ErrGroupDeleteAmbiguous", err)
|
||||
}
|
||||
if !ds.rootExists(ds.groupFilePath("ACCOUNT1", "7654321")) {
|
||||
t.Fatal("ambiguous delete removed the active group")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetiredStereoPairGetsFreshGeneration(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
const account = "ACCOUNT1"
|
||||
|
||||
first := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Pair")
|
||||
firstID, err := ds.AddGroup(account, &first)
|
||||
if err != nil {
|
||||
t.Fatalf("add first generation: %v", err)
|
||||
}
|
||||
if err := ds.DeleteGroupGenerationForDevice("MASTER", firstID, &first); err != nil {
|
||||
t.Fatalf("retire first generation: %v", err)
|
||||
}
|
||||
if !ds.rootExists(ds.retiredGroupFilePath(account, firstID)) {
|
||||
t.Fatalf("retired generation %q has no tombstone", firstID)
|
||||
}
|
||||
tombstone, err := ds.rootReadFile(ds.retiredGroupFilePath(account, firstID))
|
||||
if err != nil {
|
||||
t.Fatalf("read retired generation: %v", err)
|
||||
}
|
||||
var retired models.Group
|
||||
if err := xml.Unmarshal(tombstone, &retired); err != nil {
|
||||
t.Fatalf("retired generation does not contain group XML: %v", err)
|
||||
}
|
||||
if retired.ID != firstID {
|
||||
t.Fatalf("retired generation ID = %q, want %q", retired.ID, firstID)
|
||||
}
|
||||
if err := ds.DeleteGroup(account, firstID); err != nil {
|
||||
t.Fatalf("repeat exact generation delete should be idempotent: %v", err)
|
||||
}
|
||||
|
||||
second := lifecycleTestGroup("MASTER", "MASTER", "SLAVE", "Pair")
|
||||
secondID, err := ds.AddGroup(account, &second)
|
||||
if err != nil {
|
||||
t.Fatalf("add second generation: %v", err)
|
||||
}
|
||||
if secondID == firstID {
|
||||
t.Fatalf("new physical generation reused retired ID %q", firstID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package datastore
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/constants"
|
||||
)
|
||||
|
||||
func TestReadPresetSnapshotStates(t *testing.T) {
|
||||
account := "1234567"
|
||||
device := "DEVICE01"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
write []byte
|
||||
want PresetSnapshotState
|
||||
}{
|
||||
{name: "missing", want: PresetSnapshotMissing},
|
||||
{name: "empty", write: []byte(" \n"), want: PresetSnapshotEmpty},
|
||||
{name: "malformed", write: []byte("<presets>"), want: PresetSnapshotMalformed},
|
||||
{name: "valid empty", write: []byte("<presets></presets>"), want: PresetSnapshotValid},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
if tt.write != nil {
|
||||
path := filepath.Join(ds.AccountDeviceDir(account, device), constants.PresetsFile)
|
||||
if err := ds.MkdirAllUnderBase(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatalf("MkdirAllUnderBase: %v", err)
|
||||
}
|
||||
if err := ds.WriteFileUnderBase(path, tt.write, 0o644); err != nil {
|
||||
t.Fatalf("WriteFileUnderBase: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
snapshot, err := ds.ReadPresetSnapshot(account, device)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadPresetSnapshot: %v", err)
|
||||
}
|
||||
if snapshot.State != tt.want {
|
||||
t.Fatalf("state = %q, want %q", snapshot.State, tt.want)
|
||||
}
|
||||
if tt.want == PresetSnapshotValid && len(snapshot.Presets) != 0 {
|
||||
t.Fatalf("valid empty snapshot returned %d presets", len(snapshot.Presets))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadPresetSnapshotReturnsPersistedPresets(t *testing.T) {
|
||||
ds := NewDataStore(t.TempDir())
|
||||
account := "1234567"
|
||||
device := "DEVICE01"
|
||||
want := models.ServicePreset{
|
||||
ServiceContentItem: models.ServiceContentItem{Name: "Radio", Location: "http://radio.example/stream"},
|
||||
ID: "1",
|
||||
ButtonNumber: "1",
|
||||
}
|
||||
|
||||
if err := ds.SavePresets(account, device, []models.ServicePreset{want}); err != nil {
|
||||
t.Fatalf("SavePresets: %v", err)
|
||||
}
|
||||
|
||||
snapshot, err := ds.ReadPresetSnapshot(account, device)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadPresetSnapshot: %v", err)
|
||||
}
|
||||
if snapshot.State != PresetSnapshotValid {
|
||||
t.Fatalf("state = %q, want %q", snapshot.State, PresetSnapshotValid)
|
||||
}
|
||||
if len(snapshot.Presets) != 1 || snapshot.Presets[0].Name != want.Name || snapshot.Presets[0].Location != want.Location {
|
||||
t.Fatalf("presets = %+v, want Radio at %s", snapshot.Presets, want.Location)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package datastore
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
@@ -19,6 +20,10 @@ func TestIsSafeIdentifier(t *testing.T) {
|
||||
{"abc-123", true},
|
||||
{"abc.123", true},
|
||||
{"00:11:22:33:44:55", true},
|
||||
// #634: third-party/manual pairing tools (e.g. the USB-stick
|
||||
// SSH-enable method) can report a non-numeric margeAccountUUID.
|
||||
{"stick@local", true},
|
||||
{strings.Repeat("a", maxSafeIdentifierLength), true},
|
||||
{"", false},
|
||||
{"/", false},
|
||||
{"\\", false},
|
||||
@@ -30,7 +35,6 @@ func TestIsSafeIdentifier(t *testing.T) {
|
||||
{"a..b", false},
|
||||
{"a b", false},
|
||||
{"a!b", false},
|
||||
{"a@b", false},
|
||||
{"a#b", false},
|
||||
{"a$b", false},
|
||||
{"a%b", false},
|
||||
@@ -39,12 +43,17 @@ func TestIsSafeIdentifier(t *testing.T) {
|
||||
{"a*b", false},
|
||||
{"a(b", false},
|
||||
{"a)b", false},
|
||||
{"a<b", false},
|
||||
{"a>b", false},
|
||||
{`a"b`, false},
|
||||
{"a'b", false},
|
||||
{strings.Repeat("a", maxSafeIdentifierLength+1), false},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
result := isSafeIdentifier(test.id)
|
||||
result := IsSafeIdentifier(test.id)
|
||||
if result != test.expected {
|
||||
t.Errorf("isSafeIdentifier(%q) = %v; expected %v", test.id, result, test.expected)
|
||||
t.Errorf("IsSafeIdentifier(%q) = %v; expected %v", test.id, result, test.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,6 +81,8 @@ func TestSaveDeviceInfo_Validation(t *testing.T) {
|
||||
{"acc1", "dev/1", true, "invalid device ID"},
|
||||
{"acc..1", "dev1", true, "invalid account ID"},
|
||||
{"acc1", "dev..1", true, "invalid device ID"},
|
||||
// #634: a non-numeric margeAccountUUID is now accepted.
|
||||
{"stick@local", "dev1", false, ""},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
@@ -85,3 +96,40 @@ func TestSaveDeviceInfo_Validation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveAccountInfo_Validation(t *testing.T) {
|
||||
tmpDir, err := os.MkdirTemp("", "datastore-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
ds := NewDataStore(tmpDir)
|
||||
|
||||
tests := []struct {
|
||||
account string
|
||||
wantErr bool
|
||||
errMsg string
|
||||
}{
|
||||
{"acc1", false, ""},
|
||||
// #634: a non-numeric margeAccountUUID reported via
|
||||
// POST /streaming/account (see HandleMargeCreateAccount) must
|
||||
// be validated the same way SaveDeviceInfo already validates
|
||||
// device-reported account IDs.
|
||||
{"stick@local", false, ""},
|
||||
{"acc/1", true, "invalid account ID"},
|
||||
{"acc..1", true, "invalid account ID"},
|
||||
{"a<b", true, "invalid account ID"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
err := ds.SaveAccountInfo(test.account, &models.ServiceAccountInfo{AccountID: test.account})
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Errorf("SaveAccountInfo(%q) error = %v, wantErr %v", test.account, err, test.wantErr)
|
||||
continue
|
||||
}
|
||||
if test.wantErr && err.Error() != test.errMsg {
|
||||
t.Errorf("SaveAccountInfo(%q) error message = %q, want %q", test.account, err.Error(), test.errMsg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -22,12 +23,62 @@ const (
|
||||
// _/i419/design-admin-area-auth-gate.md. ShowWhile lets an entry key off
|
||||
// live server state (e.g. "only while the admin-area gate hasn't been
|
||||
// decided yet"); nil means always show (until dismissed).
|
||||
//
|
||||
// MessageFunc and DismissKeyFunc (added for #591,
|
||||
// _/i591/design-update-check.md) are the dynamic counterparts of Message
|
||||
// and ID: nil means "use the static field", as before; set means "compute
|
||||
// it from live state". The update-check notice needs both — its text names
|
||||
// a specific version, and dismissing the notice for v1.2.0 must not
|
||||
// suppress a later notice for v1.3.0, so its dismissal key has to change
|
||||
// with the detected version.
|
||||
type Announcement struct {
|
||||
ID string
|
||||
Message string
|
||||
Level string
|
||||
Targets []string
|
||||
ShowWhile func(*Server) bool
|
||||
ID string
|
||||
Message string
|
||||
MessageFunc func(*Server) string
|
||||
Level string
|
||||
Targets []string
|
||||
ShowWhile func(*Server) bool
|
||||
DismissKeyFunc func(*Server) string
|
||||
// LinkText/LinkURL add an optional link alongside Message — e.g. a
|
||||
// release's notes, or a docs page for a future announcement. LinkURLFunc
|
||||
// is the dynamic counterpart of LinkURL (nil = use the static field),
|
||||
// for links whose target depends on live state (e.g. which version was
|
||||
// detected). LinkText has no *Func counterpart: nothing here needs
|
||||
// dynamic link *text*, only a dynamic *URL* — add one only once
|
||||
// something actually needs it, per this project's KISS convention.
|
||||
LinkText string
|
||||
LinkURL string
|
||||
LinkURLFunc func(*Server) string
|
||||
}
|
||||
|
||||
// message returns the effective text: MessageFunc(s) if set, else the
|
||||
// static Message.
|
||||
func (a Announcement) message(s *Server) string {
|
||||
if a.MessageFunc != nil {
|
||||
return a.MessageFunc(s)
|
||||
}
|
||||
|
||||
return a.Message
|
||||
}
|
||||
|
||||
// linkURL returns the effective link URL: LinkURLFunc(s) if set, else the
|
||||
// static LinkURL (which may be "" — no link).
|
||||
func (a Announcement) linkURL(s *Server) string {
|
||||
if a.LinkURLFunc != nil {
|
||||
return a.LinkURLFunc(s)
|
||||
}
|
||||
|
||||
return a.LinkURL
|
||||
}
|
||||
|
||||
// dismissKey returns the effective dismissal/DTO id: DismissKeyFunc(s) if
|
||||
// set, else the static ID.
|
||||
func (a Announcement) dismissKey(s *Server) string {
|
||||
if a.DismissKeyFunc != nil {
|
||||
return a.DismissKeyFunc(s)
|
||||
}
|
||||
|
||||
return a.ID
|
||||
}
|
||||
|
||||
// announcements is the full, in-code list. announcementTargetChooser is
|
||||
@@ -43,20 +94,46 @@ var announcements = []Announcement{
|
||||
Targets: []string{announcementTargetAdmin},
|
||||
Message: "A future release will require login for this entire admin area by default (today, only " +
|
||||
"Spotify/Amazon linking and the Local Account tab do). You can opt in now in Settings, or " +
|
||||
"dismiss this once you've decided. See issue #419 for details.",
|
||||
"dismiss this once you've decided.",
|
||||
LinkText: "Issue #419",
|
||||
LinkURL: "https://github.com/gesellix/Bose-SoundTouch/issues/419",
|
||||
ShowWhile: func(s *Server) bool {
|
||||
return s.AdminAreaAuthMode() == ""
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "update-available",
|
||||
Level: "info",
|
||||
Targets: []string{announcementTargetApp, announcementTargetAdmin},
|
||||
ShowWhile: func(s *Server) bool {
|
||||
return s.UpdateCheckResult().Available
|
||||
},
|
||||
MessageFunc: func(s *Server) string {
|
||||
r := s.UpdateCheckResult()
|
||||
|
||||
return fmt.Sprintf("AfterTouch %s is available (you're on %s).", r.LatestVersion, r.CurrentVersion)
|
||||
},
|
||||
LinkText: "Release notes",
|
||||
LinkURLFunc: func(s *Server) string {
|
||||
return s.UpdateCheckResult().ReleaseURL
|
||||
},
|
||||
// Per-version, not per-family: dismissing the notice for one version
|
||||
// must not silently suppress a later, different version's notice.
|
||||
DismissKeyFunc: func(s *Server) string {
|
||||
return "update-available-" + s.UpdateCheckResult().LatestVersion
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// announcementDTO is the JSON shape returned by HandleListAnnouncements —
|
||||
// deliberately smaller than Announcement (no ShowWhile func, no Targets;
|
||||
// the caller already asked for a specific target).
|
||||
type announcementDTO struct {
|
||||
ID string `json:"id"`
|
||||
Message string `json:"message"`
|
||||
Level string `json:"level"`
|
||||
ID string `json:"id"`
|
||||
Message string `json:"message"`
|
||||
Level string `json:"level"`
|
||||
LinkText string `json:"link_text,omitempty"`
|
||||
LinkURL string `json:"link_url,omitempty"`
|
||||
}
|
||||
|
||||
func containsString(haystack []string, needle string) bool {
|
||||
@@ -88,7 +165,9 @@ func (s *Server) HandleListAnnouncements(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
active := make([]announcementDTO, 0, len(announcements))
|
||||
|
||||
for _, a := range announcements {
|
||||
for i := range announcements {
|
||||
a := &announcements[i]
|
||||
|
||||
if !containsString(a.Targets, target) {
|
||||
continue
|
||||
}
|
||||
@@ -97,11 +176,18 @@ func (s *Server) HandleListAnnouncements(w http.ResponseWriter, r *http.Request)
|
||||
continue
|
||||
}
|
||||
|
||||
if s.IsAnnouncementDismissed(a.ID) {
|
||||
key := a.dismissKey(s)
|
||||
if s.IsAnnouncementDismissed(key) {
|
||||
continue
|
||||
}
|
||||
|
||||
active = append(active, announcementDTO{ID: a.ID, Message: a.Message, Level: a.Level})
|
||||
active = append(active, announcementDTO{
|
||||
ID: key,
|
||||
Message: a.message(s),
|
||||
Level: a.Level,
|
||||
LinkText: a.LinkText,
|
||||
LinkURL: a.linkURL(s),
|
||||
})
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
@@ -123,8 +209,8 @@ func (s *Server) HandleDismissAnnouncement(w http.ResponseWriter, r *http.Reques
|
||||
|
||||
found := false
|
||||
|
||||
for _, a := range announcements {
|
||||
if a.ID == id {
|
||||
for i := range announcements {
|
||||
if announcements[i].dismissKey(s) == id {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
|
||||
@@ -5,9 +5,11 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/updatecheck"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
@@ -163,3 +165,123 @@ func TestHandleDismissAnnouncement_Success(t *testing.T) {
|
||||
t.Errorf("expected the notice to be gone from the list after dismissal, got %+v", active)
|
||||
}
|
||||
}
|
||||
|
||||
// newServerWithUpdateAvailable builds a Server whose registered
|
||||
// updatecheck.Checker reports a newer version than currentVersion, via the
|
||||
// same persisted-state-seeding path a real restart would use (not a mock —
|
||||
// exercises the real NewChecker/UpdateCheckResult round trip).
|
||||
func newServerWithUpdateAvailable(t *testing.T, currentVersion, latestVersion string) *Server {
|
||||
t.Helper()
|
||||
|
||||
s := newAnnouncementsTestServer(t)
|
||||
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
if err := ds.SaveUpdateCheckState(datastore.UpdateCheckState{
|
||||
LastCheckedAt: "2026-08-09T00:00:00Z",
|
||||
LastSeenVersion: latestVersion,
|
||||
LastReleaseURL: "https://example.invalid/releases/" + latestVersion,
|
||||
}); err != nil {
|
||||
t.Fatalf("Failed to seed update-check state: %v", err)
|
||||
}
|
||||
|
||||
s.SetUpdateChecker(updatecheck.NewChecker(ds, "owner/repo", currentVersion))
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// TestHandleListAnnouncements_UpdateAvailable is the regression test for
|
||||
// #591's reuse of the #419 announcements mechanism: the update-available
|
||||
// entry's dynamic message/target/dismissal behavior end to end.
|
||||
func TestHandleListAnnouncements_UpdateAvailable(t *testing.T) {
|
||||
t.Run("visible for both admin and app targets when available", func(t *testing.T) {
|
||||
s := newServerWithUpdateAvailable(t, "v1.0.0", "v1.2.0")
|
||||
|
||||
for _, target := range []string{announcementTargetAdmin, announcementTargetApp} {
|
||||
_, active := listAnnouncements(t, s, target)
|
||||
|
||||
var found *announcementDTO
|
||||
for i := range active {
|
||||
if active[i].ID == "update-available-v1.2.0" {
|
||||
found = &active[i]
|
||||
}
|
||||
}
|
||||
|
||||
if found == nil {
|
||||
t.Fatalf("target=%s: expected an update-available-v1.2.0 entry, got %+v", target, active)
|
||||
}
|
||||
if found.Message == "" {
|
||||
t.Errorf("target=%s: expected a non-empty dynamic message", target)
|
||||
}
|
||||
// The release URL belongs in the structured link field, not
|
||||
// embedded as text in the message — the message must stay
|
||||
// generic across other future announcements too.
|
||||
if strings.Contains(found.Message, "http") {
|
||||
t.Errorf("target=%s: expected the URL out of Message, got %q", target, found.Message)
|
||||
}
|
||||
if found.LinkURL == "" {
|
||||
t.Errorf("target=%s: expected a non-empty LinkURL", target)
|
||||
}
|
||||
if found.LinkText == "" {
|
||||
t.Errorf("target=%s: expected a non-empty LinkText", target)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("not visible when already up to date", func(t *testing.T) {
|
||||
s := newServerWithUpdateAvailable(t, "v1.2.0", "v1.2.0")
|
||||
|
||||
_, active := listAnnouncements(t, s, announcementTargetAdmin)
|
||||
if containsAnnouncementID(active, "update-available-v1.2.0") {
|
||||
t.Errorf("expected no update-available entry when up to date, got %+v", active)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("dismissing one version does not suppress a later version", func(t *testing.T) {
|
||||
s := newServerWithUpdateAvailable(t, "v1.0.0", "v1.2.0")
|
||||
|
||||
if err := s.RecordDismissal("update-available-v1.2.0"); err != nil {
|
||||
t.Fatalf("RecordDismissal failed: %v", err)
|
||||
}
|
||||
|
||||
_, active := listAnnouncements(t, s, announcementTargetAdmin)
|
||||
if containsAnnouncementID(active, "update-available-v1.2.0") {
|
||||
t.Error("expected the v1.2.0 notice to be dismissed")
|
||||
}
|
||||
|
||||
// A later check finds a newer version still: must reappear under a
|
||||
// DIFFERENT dismissal key, not stay suppressed.
|
||||
newDS := datastore.NewDataStore(t.TempDir())
|
||||
if err := newDS.SaveUpdateCheckState(datastore.UpdateCheckState{
|
||||
LastCheckedAt: "2026-08-10T00:00:00Z",
|
||||
LastSeenVersion: "v1.3.0",
|
||||
}); err != nil {
|
||||
t.Fatalf("Failed to seed newer state: %v", err)
|
||||
}
|
||||
s.SetUpdateChecker(updatecheck.NewChecker(newDS, "owner/repo", "v1.0.0"))
|
||||
|
||||
_, active = listAnnouncements(t, s, announcementTargetAdmin)
|
||||
if !containsAnnouncementID(active, "update-available-v1.3.0") {
|
||||
t.Errorf("expected the v1.3.0 notice to appear despite v1.2.0 being dismissed, got %+v", active)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestHandleDismissAnnouncement_UpdateAvailable(t *testing.T) {
|
||||
s := newServerWithUpdateAvailable(t, "v1.0.0", "v1.2.0")
|
||||
|
||||
r := chi.NewRouter()
|
||||
r.Post("/api/announcements/{id}/dismiss", s.HandleDismissAnnouncement)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/announcements/update-available-v1.2.0/dismiss", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
r.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", rr.Code)
|
||||
}
|
||||
|
||||
_, active := listAnnouncements(t, s, announcementTargetAdmin)
|
||||
if containsAnnouncementID(active, "update-available-v1.2.0") {
|
||||
t.Errorf("expected the notice to be gone after dismissal, got %+v", active)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,6 +203,9 @@ func TestHandleTuneInToken(t *testing.T) {
|
||||
ts := httptest.NewServer(r)
|
||||
defer ts.Close()
|
||||
|
||||
// Even when the speaker presents a refresh_token from a prior session,
|
||||
// the handler always mints its own token rather than echoing the input
|
||||
// back verbatim.
|
||||
payload := `{"grant_type":"refresh_token","refresh_token":"test-refresh-token"}`
|
||||
res, err := http.Post(ts.URL+"/bmx/tunein/v1/token", "application/json", strings.NewReader(payload))
|
||||
if err != nil {
|
||||
@@ -214,16 +217,98 @@ func TestHandleTuneInToken(t *testing.T) {
|
||||
t.Errorf("Expected status 200, got %v", res.Status)
|
||||
}
|
||||
|
||||
var resp map[string]string
|
||||
var resp map[string]interface{}
|
||||
if err := json.NewDecoder(res.Body).Decode(&resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if resp["access_token"] != "test-refresh-token" {
|
||||
t.Errorf("Expected access_token 'test-refresh-token', got %v", resp["access_token"])
|
||||
accessToken, _ := resp["access_token"].(string)
|
||||
refreshToken, _ := resp["refresh_token"].(string)
|
||||
|
||||
if accessToken == "" {
|
||||
t.Error("Expected a non-empty access_token")
|
||||
}
|
||||
if resp["refresh_token"] != "test-refresh-token" {
|
||||
t.Errorf("Expected refresh_token 'test-refresh-token', got %v", resp["refresh_token"])
|
||||
if refreshToken == "" {
|
||||
t.Error("Expected a non-empty refresh_token")
|
||||
}
|
||||
if accessToken != refreshToken {
|
||||
t.Errorf("Expected access_token and refresh_token to match, got %q and %q", accessToken, refreshToken)
|
||||
}
|
||||
if accessToken == "test-refresh-token" {
|
||||
t.Error("Expected a minted token, not an echo of the request's refresh_token")
|
||||
}
|
||||
|
||||
embedded, ok := resp["_embedded"].(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("Expected _embedded object in response, got %v", resp["_embedded"])
|
||||
}
|
||||
if _, ok := embedded["bmx_account"]; !ok {
|
||||
t.Error("Expected _embedded.bmx_account in response")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTuneInToken_Bootstrap covers the real-world trigger of the
|
||||
// original bug: a speaker's very first TUNEIN token request, made under
|
||||
// authenticationModel.anonymousAccount (autoCreate: true), has no prior
|
||||
// refresh_token to present at all. The old handler echoed back whatever
|
||||
// (possibly empty/absent) refresh_token it received, so this exact request
|
||||
// used to round-trip an empty token and the speaker would reject every
|
||||
// subsequent TUNEIN ContentItem selection with INVALID_SOURCE — even though
|
||||
// browse and search worked fine and the same stream URL played successfully
|
||||
// via Play URL/LOCAL_INTERNET_RADIO.
|
||||
func TestHandleTuneInToken_Bootstrap(t *testing.T) {
|
||||
r, _ := setupRouter("http://localhost:8001", nil)
|
||||
|
||||
ts := httptest.NewServer(r)
|
||||
defer ts.Close()
|
||||
|
||||
payload := `{"grant_type":"refresh_token"}`
|
||||
res, err := http.Post(ts.URL+"/bmx/tunein/v1/token", "application/json", strings.NewReader(payload))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
t.Errorf("Expected status 200, got %v", res.Status)
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := json.NewDecoder(res.Body).Decode(&resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
accessToken, _ := resp["access_token"].(string)
|
||||
refreshToken, _ := resp["refresh_token"].(string)
|
||||
|
||||
if accessToken == "" {
|
||||
t.Error("Bootstrap request (no refresh_token) must still receive a non-empty access_token")
|
||||
}
|
||||
if refreshToken == "" {
|
||||
t.Error("Bootstrap request (no refresh_token) must still receive a non-empty refresh_token")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTuneInToken_MalformedBodyRejected covers the request-validation
|
||||
// path that stayed in place alongside the unconditional-mint fix: a body
|
||||
// that isn't even valid JSON is not a normal bootstrap call (which is still
|
||||
// well-formed JSON, just with an empty/absent refresh_token — see
|
||||
// TestHandleTuneInToken_Bootstrap), so it should be rejected rather than
|
||||
// silently minting a token anyway.
|
||||
func TestHandleTuneInToken_MalformedBodyRejected(t *testing.T) {
|
||||
r, _ := setupRouter("http://localhost:8001", nil)
|
||||
|
||||
ts := httptest.NewServer(r)
|
||||
defer ts.Close()
|
||||
|
||||
res, err := http.Post(ts.URL+"/bmx/tunein/v1/token", "application/json", strings.NewReader("not json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("Expected status 400 for a malformed body, got %v", res.Status)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,10 +9,11 @@ import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/bmx"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/stations"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
@@ -47,7 +48,7 @@ func (s *Server) HandleTuneInPlayback(w http.ResponseWriter, r *http.Request) {
|
||||
sanitizeLog(r.URL.Path), sanitizeLog(r.UserAgent()))
|
||||
}
|
||||
|
||||
stationID := chi.URLParam(r, "stationID")
|
||||
stationID := strings.TrimSpace(chi.URLParam(r, "stationID"))
|
||||
|
||||
resp, err := bmx.TuneInPlayback(stationID, s.tuneInStreamFormats())
|
||||
if err != nil {
|
||||
@@ -74,8 +75,8 @@ func (s *Server) HandleTuneInPodcastInfo(w http.ResponseWriter, r *http.Request)
|
||||
sanitizeLog(r.URL.Path), sanitizeLog(r.UserAgent()))
|
||||
}
|
||||
|
||||
podcastID := chi.URLParam(r, "podcastID")
|
||||
encodedName := r.URL.Query().Get("encoded_name")
|
||||
podcastID := strings.TrimSpace(chi.URLParam(r, "podcastID"))
|
||||
encodedName := strings.TrimSpace(r.URL.Query().Get("encoded_name"))
|
||||
|
||||
resp, err := bmx.TuneInPodcastInfo(podcastID, encodedName)
|
||||
if err != nil {
|
||||
@@ -102,7 +103,7 @@ func (s *Server) HandleTuneInPlaybackPodcast(w http.ResponseWriter, r *http.Requ
|
||||
sanitizeLog(r.URL.Path), sanitizeLog(r.UserAgent()))
|
||||
}
|
||||
|
||||
podcastID := chi.URLParam(r, "podcastID")
|
||||
podcastID := strings.TrimSpace(chi.URLParam(r, "podcastID"))
|
||||
|
||||
resp, err := bmx.TuneInPlaybackPodcast(podcastID, s.tuneInStreamFormats())
|
||||
if err != nil {
|
||||
@@ -118,8 +119,32 @@ func (s *Server) HandleTuneInPlaybackPodcast(w http.ResponseWriter, r *http.Requ
|
||||
}
|
||||
}
|
||||
|
||||
// HandleTuneInToken returns a TuneIn access token.
|
||||
// HandleTuneInToken returns an anonymous TuneIn access token.
|
||||
//
|
||||
// The registry advertises TUNEIN with authenticationModel.anonymousAccount
|
||||
// (autoCreate: true) — see bmx_services.json — so the speaker's very first
|
||||
// call here is a bootstrap request with no prior refresh_token to present.
|
||||
// This handler used to echo back whatever refresh_token the speaker sent
|
||||
// (mirroring an authenticated-refresh recording), which meant that very
|
||||
// first bootstrap call round-tripped an empty token. The speaker never
|
||||
// obtained a usable TuneIn account and subsequently rejected every TUNEIN
|
||||
// ContentItem selection with INVALID_SOURCE, even though /sources reported
|
||||
// TUNEIN as READY (READY only reflects registry presence, not a live
|
||||
// account). Match HandleOrionToken's unconditional-generation shape
|
||||
// instead: always mint a token, regardless of what the speaker sent.
|
||||
//
|
||||
// The token itself is a stable, constant value (datastore.GenerateSerialSecret
|
||||
// is a pure function of the hardcoded "tunein" literal), not a fresh or
|
||||
// per-device secret — it's the same value for every device and every call.
|
||||
// That's fine today only because the Authorization gate is disabled for all
|
||||
// TuneIn handlers (see HandleTuneInReport below) and nothing validates the
|
||||
// token's uniqueness; if either of those ever changes, this would need a
|
||||
// real per-device/per-session token instead.
|
||||
func (s *Server) HandleTuneInToken(w http.ResponseWriter, r *http.Request) {
|
||||
// The unconditional mint above means we never use the decoded values,
|
||||
// but we still decode the body so a genuinely malformed request (not a
|
||||
// normal bootstrap call, which is valid JSON with an empty/absent
|
||||
// refresh_token) gets a 400 instead of silently succeeding.
|
||||
var req struct {
|
||||
GrantType string `json:"grant_type"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
@@ -130,18 +155,23 @@ func (s *Server) HandleTuneInToken(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// For now, we return the provided refresh_token as access_token and refresh_token,
|
||||
// mirroring the behavior seen in the recordings.
|
||||
resp := map[string]string{
|
||||
"access_token": req.RefreshToken,
|
||||
"refresh_token": req.RefreshToken,
|
||||
token := datastore.GenerateSerialSecret("tunein")
|
||||
|
||||
resp := map[string]interface{}{
|
||||
"_embedded": map[string]interface{}{
|
||||
"bmx_account": map[string]string{
|
||||
"displayName": "",
|
||||
"username": "",
|
||||
},
|
||||
},
|
||||
"access_token": token,
|
||||
"refresh_token": token,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if err := json.NewEncoder(w).Encode(resp); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,7 +223,7 @@ func (s *Server) HandleTuneInReport(w http.ResponseWriter, r *http.Request) {
|
||||
// - (empty) → top-level browse
|
||||
// - {encodedURI} → browse the given TuneIn URI
|
||||
// - sub/{n}/{encodedURI} → single subsection of a browse page
|
||||
// - profiles/{type}/{id}/{encodedURI} → artist/program profile page
|
||||
// - profiles/{encodedURI} → artist/program profile page
|
||||
func (s *Server) HandleTuneInNavigate(w http.ResponseWriter, r *http.Request) {
|
||||
// Authorization gate temporarily disabled (was: 401 if header missing).
|
||||
// The Stockholm browser proxy doesn't inject Authorization for requests
|
||||
@@ -206,7 +236,7 @@ func (s *Server) HandleTuneInNavigate(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
wildcard := chi.URLParam(r, "*")
|
||||
|
||||
resp, err := parseTuneInNavigatePath(wildcard)
|
||||
resp, err := stations.Navigate(stations.ProviderTuneIn, wildcard)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -219,47 +249,6 @@ func (s *Server) HandleTuneInNavigate(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
func parseTuneInNavigatePath(wildcard string) (interface{}, error) {
|
||||
if wildcard == "" {
|
||||
return bmx.TuneInNavigate("", nil)
|
||||
}
|
||||
|
||||
firstSlash := strings.Index(wildcard, "/")
|
||||
if firstSlash == -1 {
|
||||
return bmx.TuneInNavigate(wildcard, nil)
|
||||
}
|
||||
|
||||
prefix := wildcard[:firstSlash]
|
||||
rest := wildcard[firstSlash+1:]
|
||||
|
||||
switch prefix {
|
||||
case "sub":
|
||||
secondSlash := strings.Index(rest, "/")
|
||||
if secondSlash == -1 {
|
||||
return bmx.TuneInNavigate(rest, nil)
|
||||
}
|
||||
|
||||
n, err := strconv.Atoi(rest[:secondSlash])
|
||||
if err != nil {
|
||||
return bmx.TuneInNavigate(wildcard, nil)
|
||||
}
|
||||
|
||||
return bmx.TuneInNavigate(rest[secondSlash+1:], &n)
|
||||
|
||||
case "profiles":
|
||||
// profiles/{type}/{id}/{encodedURI}
|
||||
parts := strings.SplitN(rest, "/", 3)
|
||||
if len(parts) < 3 {
|
||||
return bmx.TuneInNavigate(wildcard, nil)
|
||||
}
|
||||
|
||||
return bmx.TuneInNavigateProfile(parts[2])
|
||||
|
||||
default:
|
||||
return bmx.TuneInNavigate(wildcard, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleTuneInSearch returns live TuneIn search results for the given query.
|
||||
func (s *Server) HandleTuneInSearch(w http.ResponseWriter, r *http.Request) {
|
||||
// Authorization gate temporarily disabled (was: 401 if header missing).
|
||||
@@ -271,7 +260,7 @@ func (s *Server) HandleTuneInSearch(w http.ResponseWriter, r *http.Request) {
|
||||
sanitizeLog(r.URL.Path), sanitizeLog(r.UserAgent()))
|
||||
}
|
||||
|
||||
query := r.URL.Query().Get("q")
|
||||
query := strings.TrimSpace(r.URL.Query().Get("q"))
|
||||
if query == "" {
|
||||
http.Error(w, "query parameter 'q' is required", http.StatusBadRequest)
|
||||
return
|
||||
@@ -298,7 +287,7 @@ func (s *Server) HandleTuneInSearchNext(w http.ResponseWriter, r *http.Request)
|
||||
sanitizeLog(r.URL.Path), sanitizeLog(r.UserAgent()))
|
||||
}
|
||||
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
cursor := strings.TrimSpace(r.URL.Query().Get("cursor"))
|
||||
if cursor == "" {
|
||||
http.Error(w, "cursor parameter required", http.StatusBadRequest)
|
||||
return
|
||||
@@ -319,7 +308,7 @@ func (s *Server) HandleTuneInSearchNext(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
// HandleTuneInFavorite handles POST /bmx/tunein/v1/favorite/{stationID}.
|
||||
func (s *Server) HandleTuneInFavorite(w http.ResponseWriter, r *http.Request) {
|
||||
stationID := chi.URLParam(r, "stationID")
|
||||
stationID := strings.TrimSpace(chi.URLParam(r, "stationID"))
|
||||
if err := s.ds.SaveTuneInFavorite(stationID); err != nil {
|
||||
log.Printf("Failed to persist TuneIn favorite %s: %s", sanitizeLog(stationID), sanitizeErr(err))
|
||||
}
|
||||
@@ -331,7 +320,7 @@ func (s *Server) HandleTuneInFavorite(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// HandleTuneInDeleteFavorite handles DELETE /bmx/tunein/v1/favorite/{stationID}.
|
||||
func (s *Server) HandleTuneInDeleteFavorite(w http.ResponseWriter, r *http.Request) {
|
||||
stationID := chi.URLParam(r, "stationID")
|
||||
stationID := strings.TrimSpace(chi.URLParam(r, "stationID"))
|
||||
if err := s.ds.DeleteTuneInFavorite(stationID); err != nil {
|
||||
log.Printf("Failed to delete TuneIn favorite %s: %s", sanitizeLog(stationID), sanitizeErr(err))
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
@@ -255,7 +256,12 @@ func (s *Server) addServiceHTTP(tw *tar.Writer, client *http.Client, devices []m
|
||||
if !seenAccounts[dev.AccountID] {
|
||||
seenAccounts[dev.AccountID] = true
|
||||
pfx := "http/service/account-" + dev.AccountID
|
||||
acct := base + "/streaming/account/" + dev.AccountID
|
||||
// url.PathEscape, not raw concatenation: account/device IDs can
|
||||
// contain characters like '@' (#634) that are safe as datastore
|
||||
// keys but would otherwise need escaping to survive as URL path
|
||||
// segments intact (e.g. a literal '?' or '#' would truncate the
|
||||
// path here, though IsSafeIdentifier already excludes those).
|
||||
acct := base + "/streaming/account/" + url.PathEscape(dev.AccountID)
|
||||
tryAdd(pfx+"/full.xml", acct+"/full")
|
||||
tryAdd(pfx+"/sources.xml", acct+"/sources")
|
||||
tryAdd(pfx+"/presets.xml", acct+"/presets")
|
||||
@@ -266,7 +272,7 @@ func (s *Server) addServiceHTTP(tw *tar.Writer, client *http.Client, devices []m
|
||||
}
|
||||
|
||||
dpfx := "http/service/account-" + dev.AccountID + "/device-" + dev.DeviceID
|
||||
dpath := base + "/streaming/account/" + dev.AccountID + "/device/" + dev.DeviceID
|
||||
dpath := base + "/streaming/account/" + url.PathEscape(dev.AccountID) + "/device/" + url.PathEscape(dev.DeviceID)
|
||||
tryAdd(dpfx+"/presets.xml", dpath+"/presets")
|
||||
tryAdd(dpfx+"/recents.xml", dpath+"/recents")
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/constants"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/marge"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
@@ -64,6 +66,11 @@ func (s *Server) HandleMargeCreateAccount(w http.ResponseWriter, r *http.Request
|
||||
}
|
||||
}
|
||||
|
||||
if !datastore.IsSafeIdentifier(id) {
|
||||
http.Error(w, "Invalid account ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
info := &models.ServiceAccountInfo{
|
||||
AccountID: id,
|
||||
PreferredLanguage: req.PreferredLanguage,
|
||||
@@ -813,17 +820,21 @@ func (s *Server) HandleMargeDeviceGroup(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
group, err := s.ds.GetGroupForDevice(account, device)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(constants.XMLHeader + `<group/>`))
|
||||
if errors.Is(err, datastore.ErrGroupNotFound) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(constants.XMLHeader + `<group/>`))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
data, err := xml.Marshal(group)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(constants.XMLHeader + `<group/>`))
|
||||
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -864,7 +875,13 @@ func (s *Server) HandleMargeAddGroup(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
id, err := s.ds.AddGroup(account, &group)
|
||||
if err != nil {
|
||||
if errors.Is(err, datastore.ErrGroupMembershipConflict) {
|
||||
http.Error(w, err.Error(), http.StatusConflict)
|
||||
return
|
||||
}
|
||||
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -931,7 +948,15 @@ func (s *Server) HandleMargeDeleteGroup(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
|
||||
if err := s.ds.DeleteGroup(account, groupID); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusNotFound)
|
||||
switch {
|
||||
case errors.Is(err, datastore.ErrGroupNotFound):
|
||||
http.Error(w, err.Error(), http.StatusNotFound)
|
||||
case errors.Is(err, datastore.ErrGroupDeleteAmbiguous):
|
||||
http.Error(w, err.Error(), http.StatusConflict)
|
||||
default:
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -940,10 +965,10 @@ func (s *Server) HandleMargeDeleteGroup(w http.ResponseWriter, r *http.Request)
|
||||
_, _ = w.Write([]byte(constants.XMLHeader + `<status>Group deleted successfully</status>`))
|
||||
}
|
||||
|
||||
// HandleMargeDeleteAccountGroups removes all stereo groups stored for an
|
||||
// account. Speakers send DELETE /streaming/account/{id}/group/ (trailing
|
||||
// slash, no group ID) during stereo-pair teardown. Master and slave often
|
||||
// live in different accounts, so each speaker deletes its own copy here.
|
||||
// HandleMargeDeleteAccountGroups handles legacy speaker teardown callbacks
|
||||
// that carry no group ID (e.g. factory reset). It deletes every stored group
|
||||
// for the account, mirroring the real firmware expectation that this call
|
||||
// clears all group state so a later Create isn't blocked by a stale record.
|
||||
func (s *Server) HandleMargeDeleteAccountGroups(w http.ResponseWriter, r *http.Request) {
|
||||
account := chi.URLParam(r, "account")
|
||||
|
||||
@@ -959,7 +984,7 @@ func (s *Server) HandleMargeDeleteAccountGroups(w http.ResponseWriter, r *http.R
|
||||
|
||||
w.Header().Set("Content-Type", "application/vnd.bose.streaming-v1.2+xml")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(constants.XMLHeader + `<status>Group deleted successfully</status>`))
|
||||
_, _ = w.Write([]byte(constants.XMLHeader + `<status>Group teardown acknowledged</status>`))
|
||||
}
|
||||
|
||||
// HandleMusicProviderIsEligible returns the music provider eligibility.
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/constants"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func margeLifecycleRouter(ds *datastore.DataStore) http.Handler {
|
||||
server := NewServer(ds, nil, "http://localhost:8001", false, false, false)
|
||||
router := chi.NewRouter()
|
||||
router.Use(clientIPMiddleware(false, nil, nil))
|
||||
router.Get("/streaming/account/{account}/device/{device}/group", server.HandleMargeDeviceGroup)
|
||||
router.Post("/streaming/account/{account}/group/", server.HandleMargeAddGroup)
|
||||
router.Delete("/streaming/account/{account}/group/", server.HandleMargeDeleteAccountGroups)
|
||||
router.Delete("/streaming/account/{account}/group/{groupId}", server.HandleMargeDeleteGroup)
|
||||
|
||||
return router
|
||||
}
|
||||
|
||||
func margeLifecycleGroupXML(master, left, right, name string) string {
|
||||
return fmt.Sprintf(`<group><name>%s</name><masterDeviceId>%s</masterDeviceId><roles>`+
|
||||
`<groupRole><deviceId>%s</deviceId><role>LEFT</role></groupRole>`+
|
||||
`<groupRole><deviceId>%s</deviceId><role>RIGHT</role></groupRole>`+
|
||||
`</roles></group>`, name, master, left, right)
|
||||
}
|
||||
|
||||
func margeLifecycleRequest(t *testing.T, handler http.Handler, method, path, remoteAddr, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
|
||||
request := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
request.RemoteAddr = remoteAddr
|
||||
request.Header.Set("Content-Type", "application/vnd.bose.streaming-v1.2+xml")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
|
||||
return recorder
|
||||
}
|
||||
|
||||
func margeLifecycleGroup(master, left, right, name string) models.Group {
|
||||
return models.Group{
|
||||
Name: name,
|
||||
MasterDeviceID: master,
|
||||
Roles: models.GroupRoles{Roles: []models.GroupRole{
|
||||
{DeviceID: left, Role: "LEFT"},
|
||||
{DeviceID: right, Role: "RIGHT"},
|
||||
}},
|
||||
}
|
||||
}
|
||||
|
||||
func countMargeLifecycleGroupFiles(t *testing.T, ds *datastore.DataStore, account string) int {
|
||||
t.Helper()
|
||||
|
||||
entries, err := os.ReadDir(ds.AccountDevicesDir(account))
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return 0
|
||||
}
|
||||
|
||||
t.Fatalf("read account devices directory: %v", err)
|
||||
}
|
||||
|
||||
count := 0
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() && strings.HasPrefix(entry.Name(), "Group_") && strings.HasSuffix(entry.Name(), ".xml") {
|
||||
count++
|
||||
}
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
func TestMargeAddGroupRetryReusesStoredGroup(t *testing.T) {
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
handler := margeLifecycleRouter(ds)
|
||||
const (
|
||||
account = "ACCOUNT1"
|
||||
path = "/streaming/account/" + account + "/group/"
|
||||
)
|
||||
|
||||
first := margeLifecycleRequest(t, handler, http.MethodPost, path, "192.0.2.10:1234",
|
||||
margeLifecycleGroupXML("MASTER", "MASTER", "SLAVE", "Original name"))
|
||||
if first.Code != http.StatusCreated {
|
||||
t.Fatalf("first POST status = %d, want 201; body=%s", first.Code, first.Body.String())
|
||||
}
|
||||
|
||||
var firstGroup models.Group
|
||||
if err := xml.Unmarshal(first.Body.Bytes(), &firstGroup); err != nil {
|
||||
t.Fatalf("decode first response: %v; body=%s", err, first.Body.String())
|
||||
}
|
||||
firstLocation := first.Header().Get("Location")
|
||||
if firstGroup.ID == "" || !strings.HasSuffix(firstLocation, "/group/"+firstGroup.ID) {
|
||||
t.Fatalf("first response ID=%q Location=%q", firstGroup.ID, firstLocation)
|
||||
}
|
||||
|
||||
retry := margeLifecycleRequest(t, handler, http.MethodPost, path, "192.0.2.10:1234",
|
||||
margeLifecycleGroupXML("MASTER", "MASTER", "SLAVE", "Retry name"))
|
||||
if retry.Code != http.StatusCreated {
|
||||
t.Fatalf("retry POST status = %d, want 201; body=%s", retry.Code, retry.Body.String())
|
||||
}
|
||||
|
||||
var retryGroup models.Group
|
||||
if err := xml.Unmarshal(retry.Body.Bytes(), &retryGroup); err != nil {
|
||||
t.Fatalf("decode retry response: %v; body=%s", err, retry.Body.String())
|
||||
}
|
||||
if retryGroup.ID != firstGroup.ID || retryGroup.Name != firstGroup.Name {
|
||||
t.Fatalf("retry group = %#v, want stored group %#v", retryGroup, firstGroup)
|
||||
}
|
||||
if got := retry.Header().Get("Location"); got != firstLocation {
|
||||
t.Fatalf("retry Location = %q, want %q", got, firstLocation)
|
||||
}
|
||||
if got := retry.Header().Get("Content-Type"); got != "application/vnd.bose.streaming-v1.2+xml" {
|
||||
t.Fatalf("retry Content-Type = %q", got)
|
||||
}
|
||||
if got := countMargeLifecycleGroupFiles(t, ds, account); got != 1 {
|
||||
t.Fatalf("stored group files = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMargeAddGroupMembershipConflictReturns409(t *testing.T) {
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
handler := margeLifecycleRouter(ds)
|
||||
const (
|
||||
account = "ACCOUNT1"
|
||||
path = "/streaming/account/" + account + "/group/"
|
||||
)
|
||||
|
||||
first := margeLifecycleRequest(t, handler, http.MethodPost, path, "192.0.2.10:1234",
|
||||
margeLifecycleGroupXML("MASTER1", "MASTER1", "SHARED", "First pair"))
|
||||
if first.Code != http.StatusCreated {
|
||||
t.Fatalf("first POST status = %d, want 201; body=%s", first.Code, first.Body.String())
|
||||
}
|
||||
|
||||
conflict := margeLifecycleRequest(t, handler, http.MethodPost, path, "192.0.2.20:1234",
|
||||
margeLifecycleGroupXML("MASTER2", "MASTER2", "SHARED", "Conflicting pair"))
|
||||
if conflict.Code != http.StatusConflict {
|
||||
t.Fatalf("conflicting POST status = %d, want 409; body=%s", conflict.Code, conflict.Body.String())
|
||||
}
|
||||
if got := countMargeLifecycleGroupFiles(t, ds, account); got != 1 {
|
||||
t.Fatalf("stored group files = %d after conflict, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMargeDeviceGroupReturnsEmptyGroupOnlyWhenNotFound(t *testing.T) {
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
response := margeLifecycleRequest(t, margeLifecycleRouter(ds), http.MethodGet,
|
||||
"/streaming/account/ACCOUNT1/device/MASTER/group", "192.0.2.10:1234", "")
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("missing group GET status = %d, want 200; body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
if got := response.Body.String(); got != constants.XMLHeader+`<group/>` {
|
||||
t.Fatalf("missing group GET body = %q, want empty group", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMargeDeviceGroupReturns500ForMalformedOrUnreadableData(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setup func(t *testing.T, path string)
|
||||
}{
|
||||
{
|
||||
name: "malformed XML",
|
||||
setup: func(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
|
||||
if err := os.WriteFile(path, []byte("<group>"), 0600); err != nil {
|
||||
t.Fatalf("write malformed group: %v", err)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unreadable group",
|
||||
setup: func(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
|
||||
if err := os.Symlink("missing-group-target", path); err != nil {
|
||||
t.Fatalf("create unreadable group symlink: %v", err)
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
if err := os.MkdirAll(ds.AccountDevicesDir("ACCOUNT1"), 0755); err != nil {
|
||||
t.Fatalf("create account directory: %v", err)
|
||||
}
|
||||
test.setup(t, filepath.Join(ds.AccountDevicesDir("ACCOUNT1"), "Group_1234567.xml"))
|
||||
|
||||
response := margeLifecycleRequest(t, margeLifecycleRouter(ds), http.MethodGet,
|
||||
"/streaming/account/ACCOUNT1/device/MASTER/group", "192.0.2.10:1234", "")
|
||||
if response.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("invalid group GET status = %d, want 500; body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "<group/>") {
|
||||
t.Fatalf("invalid group GET returned empty-group success: %s", response.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMargeDeleteAccountGroupsDeletesAllGroupsForAccount(t *testing.T) {
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
handler := margeLifecycleRouter(ds)
|
||||
const account = "ACCOUNT1"
|
||||
const otherAccount = "ACCOUNT2"
|
||||
|
||||
group := margeLifecycleGroup("MASTER", "MASTER", "SLAVE", "Current pair")
|
||||
if _, err := ds.AddGroup(account, &group); err != nil {
|
||||
t.Fatalf("add group: %v", err)
|
||||
}
|
||||
|
||||
otherGroup := margeLifecycleGroup("OTHER-MASTER", "OTHER-MASTER", "OTHER-SLAVE", "Other account pair")
|
||||
if _, err := ds.AddGroup(otherAccount, &otherGroup); err != nil {
|
||||
t.Fatalf("add group in other account: %v", err)
|
||||
}
|
||||
|
||||
response := margeLifecycleRequest(t, handler, http.MethodDelete,
|
||||
"/streaming/account/"+account+"/group/", "192.0.2.10:1234", "")
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("DELETE status = %d, want 200; body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
|
||||
if _, err := ds.GetGroupForDevice(account, "MASTER"); !errors.Is(err, datastore.ErrGroupNotFound) {
|
||||
t.Fatalf("generation-less teardown did not delete stored group: err=%v", err)
|
||||
}
|
||||
|
||||
if current, err := ds.GetGroupForDevice(otherAccount, "OTHER-MASTER"); err != nil || current.ID != otherGroup.ID {
|
||||
t.Fatalf("teardown affected a different account's group: group=%#v err=%v", current, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMargeDeleteGroupDoesNotHideAmbiguousActiveGeneration(t *testing.T) {
|
||||
baseDir := t.TempDir()
|
||||
ds := datastore.NewDataStore(baseDir)
|
||||
handler := margeLifecycleRouter(ds)
|
||||
const account = "ACCOUNT1"
|
||||
|
||||
group := margeLifecycleGroup("MASTER", "MASTER", "SLAVE", "Current pair")
|
||||
if _, err := ds.AddGroup(account, &group); err != nil {
|
||||
t.Fatalf("add group: %v", err)
|
||||
}
|
||||
|
||||
retiredPath := filepath.Join(ds.AccountDevicesDir(account), "Group_"+group.ID+".retired")
|
||||
if err := os.WriteFile(retiredPath, []byte("retired\n"), 0600); err != nil {
|
||||
t.Fatalf("create conflicting tombstone: %v", err)
|
||||
}
|
||||
|
||||
response := margeLifecycleRequest(t, handler, http.MethodDelete,
|
||||
"/streaming/account/"+account+"/group/"+group.ID, "192.0.2.10:1234", "")
|
||||
if response.Code != http.StatusConflict {
|
||||
t.Fatalf("ambiguous DELETE status = %d, want 409; body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
if current, err := ds.GetGroupForDevice(account, "MASTER"); err != nil || current.ID != group.ID {
|
||||
t.Fatalf("ambiguous DELETE changed active generation: group=%#v err=%v", current, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMargeDeleteMissingGroupReturns404(t *testing.T) {
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
response := margeLifecycleRequest(t, margeLifecycleRouter(ds), http.MethodDelete,
|
||||
"/streaming/account/ACCOUNT1/group/MISSING", "192.0.2.10:1234", "")
|
||||
if response.Code != http.StatusNotFound {
|
||||
t.Fatalf("missing DELETE status = %d, want 404; body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/setup"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func TestHandleMigrateDeviceMapsMigrationDataNotReadyToConflict(t *testing.T) {
|
||||
const (
|
||||
accountID = "1234567"
|
||||
deviceID = "DEVICE01"
|
||||
)
|
||||
|
||||
speaker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/info" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
_, _ = fmt.Fprintf(w, `<info deviceID="%s"><name>Test Speaker</name><margeAccountUUID>%s</margeAccountUUID></info>`, deviceID, accountID)
|
||||
}))
|
||||
defer speaker.Close()
|
||||
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
deviceIP := strings.TrimPrefix(speaker.URL, "http://")
|
||||
if err := ds.SaveDeviceInfo(accountID, deviceID, &models.ServiceDeviceInfo{
|
||||
DeviceID: deviceID,
|
||||
AccountID: accountID,
|
||||
IPAddress: deviceIP,
|
||||
Name: "Test Speaker",
|
||||
}); err != nil {
|
||||
t.Fatalf("SaveDeviceInfo: %v", err)
|
||||
}
|
||||
|
||||
manager := setup.NewManager("http://aftertouch.example:8000", ds, nil)
|
||||
server := NewServer(ds, manager, manager.ServerURL, false, false, false)
|
||||
router := chi.NewRouter()
|
||||
router.Post("/migrate/{deviceId}", server.HandleMigrateDevice)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodPost, "/migrate/"+deviceID+"?method=telnet", nil)
|
||||
router.ServeHTTP(recorder, request)
|
||||
|
||||
if recorder.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want %d; body=%s", recorder.Code, http.StatusConflict, recorder.Body.String())
|
||||
}
|
||||
|
||||
var response struct {
|
||||
OK bool `json:"ok"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if err := json.NewDecoder(recorder.Body).Decode(&response); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if response.OK {
|
||||
t.Fatal("response ok = true, want false")
|
||||
}
|
||||
if !strings.Contains(response.Message, "Data Sync") {
|
||||
t.Fatalf("message = %q, want actionable Data Sync guidance", response.Message)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/health"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/setup"
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -61,12 +62,12 @@ type pairAccountResponse struct {
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// HandlePairAccount associates the device with the supplied 7-digit account ID,
|
||||
// HandlePairAccount associates the device with the supplied account ID,
|
||||
// trying HTTP /setMargeAccount first and falling back to telnet
|
||||
// `envswitch accountid set`.
|
||||
//
|
||||
// Query params:
|
||||
// - account_id (required) — must pass setup.IsValidAccountID
|
||||
// - account_id (required) — must pass datastore.IsSafeIdentifier
|
||||
func (s *Server) HandlePairAccount(w http.ResponseWriter, r *http.Request) {
|
||||
deviceID := chi.URLParam(r, "deviceId")
|
||||
if deviceID == "" {
|
||||
@@ -75,8 +76,8 @@ func (s *Server) HandlePairAccount(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
accountID := r.URL.Query().Get("account_id")
|
||||
if !setup.IsValidAccountID(accountID) {
|
||||
writeJSONError(w, http.StatusBadRequest, "account_id must be exactly 7 digits")
|
||||
if !datastore.IsSafeIdentifier(accountID) {
|
||||
writeJSONError(w, http.StatusBadRequest, "account_id must be a non-empty, path-safe identifier")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -145,7 +146,7 @@ func (s *Server) completeSpeakerPairingFix(target health.Target) (string, error)
|
||||
}
|
||||
|
||||
accountID := target.Account
|
||||
if !setup.IsValidAccountID(accountID) {
|
||||
if !datastore.IsSafeIdentifier(accountID) {
|
||||
known, _ := s.ds.ListAccounts()
|
||||
|
||||
generated, genErr := setup.GenerateAccountID(known)
|
||||
|
||||
@@ -3,6 +3,8 @@ package handlers
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -12,8 +14,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"fmt"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/discovery"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
@@ -167,6 +167,11 @@ func (s *Server) HandleGetSettings(w http.ResponseWriter, _ *http.Request) {
|
||||
httpsOverride := s.httpsOverride
|
||||
discoveryInterval := s.discoveryInterval.String()
|
||||
discoveryEnabled := s.discoveryEnabled
|
||||
// Read the update-check fields directly rather than via
|
||||
// GetUpdateCheckSettings(): that getter takes s.mu.RLock itself, and Go's
|
||||
// sync.RWMutex is not reentrant-safe against a concurrent writer.
|
||||
updateCheckInterval := s.updateCheckInterval.String()
|
||||
updateCheckEnabled := s.updateCheckEnabled
|
||||
dnsEnabled := s.dnsEnabled
|
||||
dnsUpstream := s.dnsUpstream
|
||||
dnsBindAddr := s.dnsBindAddr
|
||||
@@ -248,6 +253,8 @@ func (s *Server) HandleGetSettings(w http.ResponseWriter, _ *http.Request) {
|
||||
"https_443_lan_host": probe443.LANHost,
|
||||
"discovery_interval": discoveryInterval,
|
||||
"discovery_enabled": discoveryEnabled,
|
||||
"update_check_interval": updateCheckInterval,
|
||||
"update_check_enabled": updateCheckEnabled,
|
||||
"dns_enabled": dnsEnabled,
|
||||
"dns_running": dnsRunning,
|
||||
"dns_actual_bind": actualBind,
|
||||
@@ -300,6 +307,40 @@ func parseDNSUpstreamList(dnsUpstream string) []string {
|
||||
return upstreamList
|
||||
}
|
||||
|
||||
// parseOptionalDuration parses a duration string that the client is allowed to
|
||||
// omit. An empty value yields a zero duration and no error, so callers can
|
||||
// treat "field omitted" as "keep the current value" while still rejecting a
|
||||
// value that was supplied but is unparseable.
|
||||
func parseOptionalDuration(value string) (time.Duration, error) {
|
||||
if value == "" {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
return time.ParseDuration(value)
|
||||
}
|
||||
|
||||
// resolvePeriodicSetting computes the new (interval, enabled) pair for one of
|
||||
// the background pollers (device discovery, update check) from a settings
|
||||
// request. When the request omitted the interval, the current one is kept. A
|
||||
// zero interval always forces the task off: both pollers treat zero as
|
||||
// "always due", so leaving the task enabled would make their poll tick the
|
||||
// work rate.
|
||||
func resolvePeriodicSetting(
|
||||
currentInterval, requestedInterval time.Duration,
|
||||
requestedIntervalProvided, requestedEnabled bool,
|
||||
) (time.Duration, bool) {
|
||||
interval := currentInterval
|
||||
if requestedIntervalProvided {
|
||||
interval = requestedInterval
|
||||
}
|
||||
|
||||
if interval == 0 {
|
||||
return interval, false
|
||||
}
|
||||
|
||||
return interval, requestedEnabled
|
||||
}
|
||||
|
||||
// HandleUpdateSettings updates the service settings.
|
||||
func (s *Server) HandleUpdateSettings(w http.ResponseWriter, r *http.Request) {
|
||||
var settings struct {
|
||||
@@ -307,6 +348,8 @@ func (s *Server) HandleUpdateSettings(w http.ResponseWriter, r *http.Request) {
|
||||
HTTPSServerURLOverride *string `json:"https_server_url_override"`
|
||||
DiscoveryInterval string `json:"discovery_interval"`
|
||||
DiscoveryEnabled bool `json:"discovery_enabled"`
|
||||
UpdateCheckInterval string `json:"update_check_interval"`
|
||||
UpdateCheckEnabled bool `json:"update_check_enabled"`
|
||||
DNSEnabled bool `json:"dns_enabled"`
|
||||
DNSUpstream string `json:"dns_upstream"`
|
||||
DNSBindAddr string `json:"dns_bind_addr"`
|
||||
@@ -370,12 +413,18 @@ func (s *Server) HandleUpdateSettings(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
interval, err := time.ParseDuration(settings.DiscoveryInterval)
|
||||
if err != nil && settings.DiscoveryInterval != "" {
|
||||
interval, err := parseOptionalDuration(settings.DiscoveryInterval)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid discovery interval: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
updateCheckInterval, err := parseOptionalDuration(settings.UpdateCheckInterval)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid update check interval: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
|
||||
// Guard rail: refuse to enable the admin-area gate while the Management
|
||||
@@ -396,14 +445,11 @@ func (s *Server) HandleUpdateSettings(w http.ResponseWriter, r *http.Request) {
|
||||
// the Target Domain (which the derived URL follows) may have changed.
|
||||
s.applyHTTPSOverrideLocked(settings.HTTPSServerURLOverride)
|
||||
|
||||
s.discoveryEnabled = settings.DiscoveryEnabled
|
||||
if settings.DiscoveryInterval != "" {
|
||||
s.discoveryInterval = interval
|
||||
}
|
||||
s.discoveryInterval, s.discoveryEnabled = resolvePeriodicSetting(
|
||||
s.discoveryInterval, interval, settings.DiscoveryInterval != "", settings.DiscoveryEnabled)
|
||||
|
||||
if s.discoveryInterval == 0 {
|
||||
s.discoveryEnabled = false
|
||||
}
|
||||
s.updateCheckInterval, s.updateCheckEnabled = resolvePeriodicSetting(
|
||||
s.updateCheckInterval, updateCheckInterval, settings.UpdateCheckInterval != "", settings.UpdateCheckEnabled)
|
||||
|
||||
s.dnsEnabled = settings.DNSEnabled
|
||||
s.dnsUpstream = parseDNSUpstreamList(settings.DNSUpstream)
|
||||
@@ -469,6 +515,8 @@ func (s *Server) HandleUpdateSettings(w http.ResponseWriter, r *http.Request) {
|
||||
persisted.RecordInteractions = currentRecord
|
||||
persisted.DiscoveryInterval = s.discoveryInterval.String()
|
||||
persisted.DiscoveryEnabled = s.discoveryEnabled
|
||||
persisted.UpdateCheckInterval = s.updateCheckInterval.String()
|
||||
persisted.UpdateCheckEnabled = s.updateCheckEnabled
|
||||
persisted.DNSEnabled = s.dnsEnabled
|
||||
persisted.DNSUpstream = s.dnsUpstream
|
||||
persisted.DNSBindAddr = s.dnsBindAddr
|
||||
@@ -671,8 +719,19 @@ func (s *Server) HandleMigrateDevice(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
output, err := s.sm.MigrateSpeaker(deviceIP, targetURL, proxyURL, options, method)
|
||||
if err != nil {
|
||||
status := http.StatusInternalServerError
|
||||
|
||||
var notReady *setup.MigrationDataNotReadyError
|
||||
|
||||
switch {
|
||||
case errors.As(err, ¬Ready):
|
||||
status = http.StatusConflict
|
||||
case errors.Is(err, setup.ErrInvalidTelnetURL):
|
||||
status = http.StatusBadRequest
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.WriteHeader(status)
|
||||
|
||||
if encodeErr := json.NewEncoder(w).Encode(map[string]interface{}{"ok": false, "message": err.Error(), "output": output}); encodeErr != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
@@ -690,7 +749,9 @@ func (s *Server) HandleMigrateDevice(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// HandleRevertMigration reverts the migration for a device.
|
||||
// HandleRevertMigration reverts the migration for a device. The existing
|
||||
// no-query path restores SSH/filesystem backups; method=telnet restores only
|
||||
// the four canonical Bose service URLs and accepts the migration URL overrides.
|
||||
func (s *Server) HandleRevertMigration(w http.ResponseWriter, r *http.Request) {
|
||||
deviceID := chi.URLParam(r, "deviceId")
|
||||
if deviceID == "" {
|
||||
@@ -718,10 +779,50 @@ func (s *Server) HandleRevertMigration(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
output, err := s.sm.RevertMigration(deviceIP)
|
||||
if err != nil {
|
||||
method := r.URL.Query().Get("method")
|
||||
if (method == "" || method == "ssh") && len(presentTelnetURLOverrides(r.URL.Query())) > 0 {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
|
||||
if encodeErr := json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"ok": false,
|
||||
"message": "Telnet URL overrides require method=telnet",
|
||||
}); encodeErr != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var output string
|
||||
|
||||
switch method {
|
||||
case "", "ssh":
|
||||
output, err = s.sm.RevertMigration(deviceIP)
|
||||
case string(setup.MigrationMethodTelnet):
|
||||
output, err = s.sm.RevertTelnetURLs(deviceIP, parseMigrationOptions(r.URL.Query()))
|
||||
default:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
|
||||
if encodeErr := json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"ok": false,
|
||||
"message": fmt.Sprintf("Unsupported revert method %q; expected ssh or telnet", method),
|
||||
}); encodeErr != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
status := http.StatusInternalServerError
|
||||
if errors.Is(err, setup.ErrInvalidTelnetURL) {
|
||||
status = http.StatusBadRequest
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
if encodeErr := json.NewEncoder(w).Encode(map[string]interface{}{"ok": false, "message": err.Error(), "output": output}); encodeErr != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
@@ -1226,7 +1327,16 @@ func (s *Server) HandleTestDNSRedirection(w http.ResponseWriter, r *http.Request
|
||||
}
|
||||
}
|
||||
|
||||
// HandleInitialSync fetches presets, recents and sources from the device and saves them to the datastore.
|
||||
// HandleInitialSync fetches presets, recents and sources from the device
|
||||
// and saves them to the datastore.
|
||||
//
|
||||
// If applying the fetched presets/recents would shrink what's already
|
||||
// stored, the sync is not applied — the response comes back 409 with the
|
||||
// diff describing what would be removed — unless the caller passes
|
||||
// ?confirmed=true, in which case it's applied unconditionally. Every call
|
||||
// re-fetches live from the speaker at that moment (see
|
||||
// setup.SyncDeviceData), so a confirmed retry re-checks current reality
|
||||
// rather than replaying a possibly-stale earlier response.
|
||||
func (s *Server) HandleInitialSync(w http.ResponseWriter, r *http.Request) {
|
||||
deviceID := chi.URLParam(r, "deviceId")
|
||||
if deviceID == "" {
|
||||
@@ -1240,13 +1350,25 @@ func (s *Server) HandleInitialSync(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.sm.SyncDeviceData(deviceIP); err != nil {
|
||||
confirmed := r.URL.Query().Get("confirmed") == "true"
|
||||
|
||||
result, err := s.sm.SyncDeviceData(deviceIP, confirmed)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"ok": true}`))
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if !result.Applied {
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
} else {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
if encodeErr := json.NewEncoder(w).Encode(result); encodeErr != nil {
|
||||
log.Printf("HandleInitialSync: failed to encode result for device %s: %s", sanitizeLog(deviceID), sanitizeErr(encodeErr))
|
||||
}
|
||||
}
|
||||
|
||||
// HandleRebootDevice reboots a device.
|
||||
@@ -1388,14 +1510,22 @@ func (s *Server) HandleGetVersionInfo(w http.ResponseWriter, _ *http.Request) {
|
||||
releaseURL = fmt.Sprintf("%s/releases/tag/%s", repoURL, version)
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(map[string]string{
|
||||
"version": version,
|
||||
"commit": commit,
|
||||
"date": date,
|
||||
"repo_url": repoURL,
|
||||
"release_url": releaseURL,
|
||||
"commit_url": commitURL,
|
||||
"data_dir": dataDir,
|
||||
// Opt-in periodic update check (#591) — UpdateCheckResult is nil-safe and
|
||||
// returns the zero value (Available: false) when the check was never
|
||||
// enabled, which is the common case.
|
||||
updateCheck := s.UpdateCheckResult()
|
||||
|
||||
if err := json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"version": version,
|
||||
"commit": commit,
|
||||
"date": date,
|
||||
"repo_url": repoURL,
|
||||
"release_url": releaseURL,
|
||||
"commit_url": commitURL,
|
||||
"data_dir": dataDir,
|
||||
"update_available": updateCheck.Available,
|
||||
"latest_version": updateCheck.LatestVersion,
|
||||
"latest_release_url": updateCheck.ReleaseURL,
|
||||
}); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
|
||||
@@ -6,10 +6,12 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/certmanager"
|
||||
@@ -443,6 +445,170 @@ func TestAdminAreaAuthRoundTrip(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolvePeriodicSetting covers the shared interval/enabled resolution
|
||||
// used by both background pollers (device discovery, update check).
|
||||
func TestResolvePeriodicSetting(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
current time.Duration
|
||||
requested time.Duration
|
||||
provided bool
|
||||
enabled bool
|
||||
wantInterval time.Duration
|
||||
wantEnabledState bool
|
||||
}{
|
||||
{"interval omitted keeps the current one", 24 * time.Hour, 0, false, true, 24 * time.Hour, true},
|
||||
{"interval supplied replaces the current one", 24 * time.Hour, 6 * time.Hour, true, true, 6 * time.Hour, true},
|
||||
{"disabling keeps the interval", 24 * time.Hour, 0, false, false, 24 * time.Hour, false},
|
||||
{"a zero interval forces it off", 24 * time.Hour, 0, true, true, 0, false},
|
||||
{"a zero current interval forces it off too", 0, 0, false, true, 0, false},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
gotInterval, gotEnabled := resolvePeriodicSetting(tc.current, tc.requested, tc.provided, tc.enabled)
|
||||
if gotInterval != tc.wantInterval || gotEnabled != tc.wantEnabledState {
|
||||
t.Errorf("%s: resolvePeriodicSetting() = %v/%v, want %v/%v",
|
||||
tc.name, gotInterval, gotEnabled, tc.wantInterval, tc.wantEnabledState)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseOptionalDuration verifies an omitted duration is not an error,
|
||||
// while a supplied-but-invalid one is.
|
||||
func TestParseOptionalDuration(t *testing.T) {
|
||||
if d, err := parseOptionalDuration(""); err != nil || d != 0 {
|
||||
t.Errorf("parseOptionalDuration(\"\") = %v/%v, want 0/nil", d, err)
|
||||
}
|
||||
|
||||
if d, err := parseOptionalDuration("90m"); err != nil || d != 90*time.Minute {
|
||||
t.Errorf("parseOptionalDuration(\"90m\") = %v/%v, want 1h30m0s/nil", d, err)
|
||||
}
|
||||
|
||||
if _, err := parseOptionalDuration("nope"); err == nil {
|
||||
t.Error("parseOptionalDuration(\"nope\") = nil error, want a parse error")
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCheckSettingsRoundTrip covers the Settings-page control for the
|
||||
// opt-in update check (#591 follow-up): POST /setup/settings must update the
|
||||
// live values the background poller reads, persist them, and hand them back
|
||||
// on GET so the UI reflects what was saved.
|
||||
func TestUpdateCheckSettingsRoundTrip(t *testing.T) {
|
||||
tempDir, err := os.MkdirTemp("", "update-check-settings-roundtrip-test")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
ds := datastore.NewDataStore(tempDir)
|
||||
_ = ds.Initialize()
|
||||
|
||||
r, server := setupRouter("http://127.0.0.1:8000", ds)
|
||||
ts := httptest.NewServer(r)
|
||||
defer ts.Close()
|
||||
|
||||
// Default state: opted out, with a nonzero interval so enabling it later
|
||||
// doesn't need an interval to be supplied.
|
||||
if interval, enabled := server.GetUpdateCheckSettings(); enabled || interval == 0 {
|
||||
t.Fatalf("Expected the check to default to disabled with a nonzero interval, got %v/%v", interval, enabled)
|
||||
}
|
||||
|
||||
enableBody, err := json.Marshal(map[string]interface{}{
|
||||
"server_url": "http://127.0.0.1:8000",
|
||||
"update_check_enabled": true,
|
||||
"update_check_interval": "6h",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal request body: %v", err)
|
||||
}
|
||||
|
||||
res, err := http.Post(ts.URL+"/setup/settings", "application/json", bytes.NewBuffer(enableBody))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
t.Fatalf("POST /setup/settings (enable): expected 200, got %v", res.Status)
|
||||
}
|
||||
|
||||
interval, enabled := server.GetUpdateCheckSettings()
|
||||
if !enabled || interval != 6*time.Hour {
|
||||
t.Errorf("Expected live settings 6h/true, got %v/%v", interval, enabled)
|
||||
}
|
||||
|
||||
persisted, err := ds.GetSettings()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to reload settings: %v", err)
|
||||
}
|
||||
if !persisted.UpdateCheckEnabled || persisted.UpdateCheckInterval != "6h0m0s" {
|
||||
t.Errorf("Expected persisted 6h0m0s/true, got %q/%v",
|
||||
persisted.UpdateCheckInterval, persisted.UpdateCheckEnabled)
|
||||
}
|
||||
|
||||
res, err = http.Get(ts.URL + "/setup/settings")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
var got map[string]interface{}
|
||||
if err := json.NewDecoder(res.Body).Decode(&got); err != nil {
|
||||
t.Fatalf("Failed to decode GET /setup/settings: %v", err)
|
||||
}
|
||||
if got["update_check_enabled"] != true {
|
||||
t.Errorf("GET /setup/settings: expected update_check_enabled true, got %+v", got["update_check_enabled"])
|
||||
}
|
||||
if got["update_check_interval"] != "6h0m0s" {
|
||||
t.Errorf("GET /setup/settings: expected update_check_interval 6h0m0s, got %+v", got["update_check_interval"])
|
||||
}
|
||||
|
||||
// An unparseable interval must be rejected before anything is applied.
|
||||
badBody, err := json.Marshal(map[string]interface{}{
|
||||
"server_url": "http://127.0.0.1:8000",
|
||||
"update_check_enabled": true,
|
||||
"update_check_interval": "not-a-duration",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal request body: %v", err)
|
||||
}
|
||||
|
||||
res, err = http.Post(ts.URL+"/setup/settings", "application/json", bytes.NewBuffer(badBody))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("POST /setup/settings (bad interval): expected 400, got %v", res.Status)
|
||||
}
|
||||
|
||||
// A zero interval must force the check off rather than leave the poller
|
||||
// hitting GitHub on every tick.
|
||||
zeroBody, err := json.Marshal(map[string]interface{}{
|
||||
"server_url": "http://127.0.0.1:8000",
|
||||
"update_check_enabled": true,
|
||||
"update_check_interval": "0s",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal request body: %v", err)
|
||||
}
|
||||
|
||||
res, err = http.Post(ts.URL+"/setup/settings", "application/json", bytes.NewBuffer(zeroBody))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
t.Fatalf("POST /setup/settings (zero interval): expected 200, got %v", res.Status)
|
||||
}
|
||||
|
||||
if _, enabled := server.GetUpdateCheckSettings(); enabled {
|
||||
t.Error("Expected a zero interval to disable the update check")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleGetVersionInfo_IncludesAbsoluteDataDir verifies /api/setup/version
|
||||
// reports the actual data directory in use, resolved to an absolute path —
|
||||
// added so operators running the service locally (not in Docker, where the
|
||||
@@ -468,7 +634,7 @@ func TestHandleGetVersionInfo_IncludesAbsoluteDataDir(t *testing.T) {
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
var got map[string]string
|
||||
var got map[string]interface{}
|
||||
if err := json.NewDecoder(res.Body).Decode(&got); err != nil {
|
||||
t.Fatalf("Failed to decode response: %v", err)
|
||||
}
|
||||
@@ -483,6 +649,45 @@ func TestHandleGetVersionInfo_IncludesAbsoluteDataDir(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleGetVersionInfo_UpdateCheckFields verifies the #591 fields are
|
||||
// present and reflect a nil-checker default (Available: false) when the
|
||||
// update check was never enabled — the common case.
|
||||
func TestHandleGetVersionInfo_UpdateCheckFields(t *testing.T) {
|
||||
tempDir, err := os.MkdirTemp("", "version-info-updatecheck-test")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
ds := datastore.NewDataStore(tempDir)
|
||||
_ = ds.Initialize()
|
||||
|
||||
r, _ := setupRouter("http://127.0.0.1:8000", ds)
|
||||
ts := httptest.NewServer(r)
|
||||
defer ts.Close()
|
||||
|
||||
res, err := http.Get(ts.URL + "/setup/version")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
var got map[string]interface{}
|
||||
if err := json.NewDecoder(res.Body).Decode(&got); err != nil {
|
||||
t.Fatalf("Failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
if got["update_available"] != false {
|
||||
t.Errorf("Expected update_available=false by default, got %v", got["update_available"])
|
||||
}
|
||||
if _, ok := got["latest_version"]; !ok {
|
||||
t.Error("Expected a latest_version key in the response")
|
||||
}
|
||||
if _, ok := got["latest_release_url"]; !ok {
|
||||
t.Error("Expected a latest_release_url key in the response")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationAndCA(t *testing.T) {
|
||||
tempDir, err := os.MkdirTemp("", "handlers-test")
|
||||
if err != nil {
|
||||
@@ -500,6 +705,10 @@ func TestMigrationAndCA(t *testing.T) {
|
||||
sm.NewSSH = func(host string) setup.SSHClient {
|
||||
return &mockSSH{host: host}
|
||||
}
|
||||
telnetMock := &mockSetupTelnet{}
|
||||
sm.NewTelnet = func(string) setup.TelnetClient {
|
||||
return telnetMock
|
||||
}
|
||||
|
||||
// Mock HTTPGet to avoid real network timeouts
|
||||
sm.HTTPGet = func(url string) (*http.Response, error) {
|
||||
@@ -510,6 +719,12 @@ func TestMigrationAndCA(t *testing.T) {
|
||||
Body: io.NopCloser(strings.NewReader(xml)),
|
||||
}, nil
|
||||
}
|
||||
if strings.HasSuffix(url, "/presets") {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Body: io.NopCloser(strings.NewReader(`<presets/>`)),
|
||||
}, nil
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusNotFound,
|
||||
Body: io.NopCloser(strings.NewReader("Not Found")),
|
||||
@@ -528,6 +743,7 @@ func TestMigrationAndCA(t *testing.T) {
|
||||
IPAddress: "192.0.2.10",
|
||||
AccountID: "default",
|
||||
})
|
||||
_ = ds.SavePresets("default", "192.0.2.10", nil)
|
||||
|
||||
// 1. Test GET /setup/ca.crt
|
||||
res, err := http.Get(ts.URL + "/setup/ca.crt")
|
||||
@@ -565,6 +781,22 @@ func TestMigrationAndCA(t *testing.T) {
|
||||
t.Errorf("Migrate: Expected output field in response")
|
||||
}
|
||||
|
||||
// Unsafe telnet migration input is a client error and never reaches the speaker.
|
||||
unsafeMigrateCommandCount := len(telnetMock.commands)
|
||||
unsafeTarget := url.QueryEscape("http://192.0.2.100:8000\r\nsys reboot")
|
||||
res, err = http.Post(ts.URL+"/setup/migrate/192.0.2.10?method=telnet&target_url="+unsafeTarget, "application/json", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("Unsafe telnet migration: expected status 400, got %v", res.Status)
|
||||
}
|
||||
if len(telnetMock.commands) != unsafeMigrateCommandCount {
|
||||
t.Errorf("Unsafe telnet migration sent commands: before=%d after=%d", unsafeMigrateCommandCount, len(telnetMock.commands))
|
||||
}
|
||||
|
||||
// 3. Test POST /setup/trust-ca/{deviceIP}
|
||||
res, err = http.Post(ts.URL+"/setup/trust-ca/192.0.2.10", "application/json", nil)
|
||||
if err != nil {
|
||||
@@ -627,6 +859,81 @@ func TestMigrationAndCA(t *testing.T) {
|
||||
if _, ok := result["output"]; !ok {
|
||||
t.Errorf("RemoveRemote: Expected output field in response")
|
||||
}
|
||||
|
||||
// 6. Telnet-only revert uses the dedicated URL restore path.
|
||||
res, err = http.Post(ts.URL+"/setup/revert/192.0.2.10?method=telnet", "application/json", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
t.Errorf("Telnet revert: expected status OK, got %v", res.Status)
|
||||
}
|
||||
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
|
||||
t.Fatalf("Telnet revert: failed to decode response: %v", err)
|
||||
}
|
||||
if result["ok"] != true {
|
||||
t.Errorf("Telnet revert: expected ok=true, got %v", result["ok"])
|
||||
}
|
||||
|
||||
commands := strings.Join(telnetMock.commands, "\n")
|
||||
for _, want := range []string{
|
||||
"sys configuration margeServerUrl https://streaming.bose.com",
|
||||
"sys configuration statsServerUrl https://events.api.bosecm.com",
|
||||
"sys configuration swUpdateUrl https://worldwide.bose.com/updates/soundtouch",
|
||||
"sys configuration bmxRegistryUrl https://content.api.bose.io/bmx/registry/v1/services",
|
||||
"envswitch boseurls set https://streaming.bose.com https://worldwide.bose.com/updates/soundtouch",
|
||||
"getpdo CurrentSystemConfiguration",
|
||||
} {
|
||||
if !strings.Contains(commands, want) {
|
||||
t.Errorf("Telnet revert commands missing %q:\n%s", want, commands)
|
||||
}
|
||||
}
|
||||
|
||||
// 7. SSH revert rejects telnet-only URL overrides instead of ignoring them.
|
||||
commandCount := len(telnetMock.commands)
|
||||
res, err = http.Post(ts.URL+"/setup/revert/192.0.2.10?method=ssh&marge_url=https%3A%2F%2Foverride.example%2Fmarge", "application/json", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("SSH revert with telnet overrides: expected status 400, got %v", res.Status)
|
||||
}
|
||||
if len(telnetMock.commands) != commandCount {
|
||||
t.Errorf("SSH revert with telnet overrides sent telnet commands: before=%d after=%d", commandCount, len(telnetMock.commands))
|
||||
}
|
||||
|
||||
// 8. Unsafe telnet URL input fails before any command is sent.
|
||||
unsafeURL := url.QueryEscape("https://override.example/marge\r\nsys reboot")
|
||||
res, err = http.Post(ts.URL+"/setup/revert/192.0.2.10?method=telnet&marge_url="+unsafeURL, "application/json", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("Unsafe telnet URL: expected status 400, got %v", res.Status)
|
||||
}
|
||||
if len(telnetMock.commands) != commandCount {
|
||||
t.Errorf("Unsafe telnet URL sent commands: before=%d after=%d", commandCount, len(telnetMock.commands))
|
||||
}
|
||||
|
||||
// 9. Unknown revert methods fail before touching either transport.
|
||||
res, err = http.Post(ts.URL+"/setup/revert/192.0.2.10?method=invalid", "application/json", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("Invalid revert method: expected status 400, got %v", res.Status)
|
||||
}
|
||||
if len(telnetMock.commands) != commandCount {
|
||||
t.Errorf("Invalid revert method sent telnet commands: before=%d after=%d", commandCount, len(telnetMock.commands))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveDevice(t *testing.T) {
|
||||
@@ -728,6 +1035,40 @@ type mockSSH struct {
|
||||
uploaded map[string][]byte
|
||||
}
|
||||
|
||||
type mockSetupTelnet struct {
|
||||
commands []string
|
||||
}
|
||||
|
||||
func (m *mockSetupTelnet) Dial() error { return nil }
|
||||
|
||||
func (m *mockSetupTelnet) Probe() (string, error) { return "->", nil }
|
||||
|
||||
func (m *mockSetupTelnet) SendCommand(command string) (string, error) {
|
||||
m.commands = append(m.commands, command)
|
||||
if command == "getpdo CurrentSystemConfiguration" {
|
||||
return `margeServerUrl {
|
||||
text: "https://streaming.bose.com"
|
||||
}
|
||||
statsServerUrl {
|
||||
text: "https://events.api.bosecm.com"
|
||||
}
|
||||
swUpdateUrl {
|
||||
text: "https://worldwide.bose.com/updates/soundtouch"
|
||||
}
|
||||
bmxRegistryUrl {
|
||||
text: "https://content.api.bose.io/bmx/registry/v1/services"
|
||||
}`, nil
|
||||
}
|
||||
if fields := strings.Fields(command); len(fields) == 5 &&
|
||||
fields[0] == "envswitch" && fields[1] == "boseurls" && fields[2] == "set" {
|
||||
return "Setting Bose Server URLs to " + fields[3] + " and " + fields[4] + "\n->OK\n->", nil
|
||||
}
|
||||
|
||||
return "OK", nil
|
||||
}
|
||||
|
||||
func (m *mockSetupTelnet) Close() error { return nil }
|
||||
|
||||
func (m *mockSSH) Run(command string) (string, error) {
|
||||
if strings.Contains(command, "cat /etc/hosts") {
|
||||
m.runCount++
|
||||
@@ -761,3 +1102,9 @@ func (m *mockSSH) UploadContent(content []byte, remotePath string) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Connect/Close are no-ops here — the mock has no real connection to
|
||||
// reuse, and every test call already goes through Run/UploadContent above
|
||||
// regardless of whether Connect was called first.
|
||||
func (m *mockSSH) Connect() error { return nil }
|
||||
func (m *mockSSH) Close() error { return nil }
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/setup"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// TestHandleInitialSync_DestructiveSyncReturns409ThenAppliesWhenConfirmed is
|
||||
// an HTTP-level regression test for #614's Sync-button data-loss bug (see
|
||||
// setup.TestSyncDeviceData_DestructiveSyncRequiresConfirmation for the
|
||||
// lower-level coverage of the same fix): a device already has more presets
|
||||
// stored than the mock speaker's live /presets now reports. The first,
|
||||
// unconfirmed sync request must come back 409 with the diff and must not
|
||||
// write anything; a retry with ?confirmed=true must apply it.
|
||||
func TestHandleInitialSync_DestructiveSyncReturns409ThenAppliesWhenConfirmed(t *testing.T) {
|
||||
const (
|
||||
accountID = "1234567"
|
||||
deviceID = "AABBCCDDEEFF"
|
||||
)
|
||||
|
||||
// A real local server, not a black-hole IP: notifySpeakerSourcesUpdated
|
||||
// (part of the confirmed-apply path) uses its own HTTP client rather
|
||||
// than the injectable sm.HTTPGet, so it needs somewhere real to fail
|
||||
// fast against (404) instead of timing out.
|
||||
mockDevice := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/info":
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
fmt.Fprintf(w, `<?xml version="1.0" encoding="UTF-8"?><info deviceID="%s"><name>Test Device</name><type>SoundTouch 20</type><margeAccountUUID>%s</margeAccountUUID></info>`, deviceID, accountID)
|
||||
case "/presets":
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
fmt.Fprint(w, `<?xml version="1.0" encoding="UTF-8"?><presets><preset id="1"><ContentItem source="LOCAL_INTERNET_RADIO" type="stationurl" location="/x" isPresetable="true"><itemName>Station 1</itemName></ContentItem></preset></presets>`)
|
||||
case "/recents":
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
fmt.Fprint(w, `<?xml version="1.0" encoding="UTF-8"?><recents></recents>`)
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer mockDevice.Close()
|
||||
|
||||
deviceIP := mockDevice.Listener.Addr().String()
|
||||
|
||||
tempDir, err := os.MkdirTemp("", "handlers-sync-destructive-guard-*")
|
||||
if err != nil {
|
||||
t.Fatalf("tempdir: %v", err)
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(tempDir) }()
|
||||
|
||||
ds := datastore.NewDataStore(tempDir)
|
||||
|
||||
seeded := []models.ServicePreset{
|
||||
{ID: "1", ButtonNumber: "1", ServiceContentItem: models.ServiceContentItem{Name: "Station 1"}},
|
||||
{ID: "2", ButtonNumber: "2", ServiceContentItem: models.ServiceContentItem{Name: "Station 2"}},
|
||||
}
|
||||
if err := ds.SavePresets(accountID, deviceID, seeded); err != nil {
|
||||
t.Fatalf("seed SavePresets: %v", err)
|
||||
}
|
||||
|
||||
if err := ds.SaveDeviceInfo(accountID, deviceID, &models.ServiceDeviceInfo{
|
||||
DeviceID: deviceID,
|
||||
AccountID: accountID,
|
||||
IPAddress: deviceIP,
|
||||
}); err != nil {
|
||||
t.Fatalf("SaveDeviceInfo: %v", err)
|
||||
}
|
||||
|
||||
sm := setup.NewManager("http://localhost:8000", ds, nil)
|
||||
|
||||
server := NewServer(ds, sm, "http://localhost:8000", false, false, false)
|
||||
|
||||
r := chi.NewRouter()
|
||||
r.Post("/api/setup/sync/{deviceId}", server.HandleInitialSync)
|
||||
|
||||
ts := httptest.NewServer(r)
|
||||
defer ts.Close()
|
||||
|
||||
// First, unconfirmed request: must be refused with 409.
|
||||
resp, err := http.Post(ts.URL+"/api/setup/sync/"+deviceID, "application/json", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("POST sync (unconfirmed): %v", err)
|
||||
}
|
||||
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
if resp.StatusCode != http.StatusConflict {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("expected 409 for a destructive unconfirmed sync, got %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
var result setup.SyncResult
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
t.Fatalf("decode 409 body: %v", err)
|
||||
}
|
||||
|
||||
if result.Applied {
|
||||
t.Fatal("expected Applied=false in the 409 response")
|
||||
}
|
||||
|
||||
if !result.Destructive {
|
||||
t.Fatal("expected Destructive=true in the 409 response")
|
||||
}
|
||||
|
||||
presetsAfterRefusal, err := ds.GetPresets(accountID, deviceID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetPresets after refused sync: %v", err)
|
||||
}
|
||||
|
||||
if len(presetsAfterRefusal) != 2 {
|
||||
t.Fatalf("expected the original 2 presets to survive the refused sync, got %d", len(presetsAfterRefusal))
|
||||
}
|
||||
|
||||
// Retry, confirmed: must apply.
|
||||
resp2, err := http.Post(ts.URL+"/api/setup/sync/"+deviceID+"?confirmed=true", "application/json", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("POST sync (confirmed): %v", err)
|
||||
}
|
||||
|
||||
defer func() { _ = resp2.Body.Close() }()
|
||||
|
||||
if resp2.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp2.Body)
|
||||
t.Fatalf("expected 200 for a confirmed sync, got %d: %s", resp2.StatusCode, body)
|
||||
}
|
||||
|
||||
var confirmedResult setup.SyncResult
|
||||
if err := json.NewDecoder(resp2.Body).Decode(&confirmedResult); err != nil {
|
||||
t.Fatalf("decode 200 body: %v", err)
|
||||
}
|
||||
|
||||
if !confirmedResult.Applied {
|
||||
t.Fatal("expected Applied=true after confirming")
|
||||
}
|
||||
|
||||
presetsAfterConfirm, err := ds.GetPresets(accountID, deviceID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetPresets after confirmed sync: %v", err)
|
||||
}
|
||||
|
||||
if len(presetsAfterConfirm) != 1 {
|
||||
t.Fatalf("expected confirmed sync to shrink to 1 preset, got %d", len(presetsAfterConfirm))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/updatecheck"
|
||||
)
|
||||
|
||||
// TestUpdateCheckResult_NilCheckerIsSafe verifies the default (opt-in
|
||||
// checker never registered) returns a safe zero value rather than
|
||||
// panicking — the common case, since UPDATE_CHECK_ENABLED defaults to
|
||||
// false.
|
||||
func TestUpdateCheckResult_NilCheckerIsSafe(t *testing.T) {
|
||||
s := NewServer(nil, nil, "http://localhost", false, false, false)
|
||||
|
||||
result := s.UpdateCheckResult()
|
||||
if result.Available {
|
||||
t.Error("Expected a nil checker to report Available=false")
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCheckResult_ReflectsRegisteredChecker verifies SetUpdateChecker
|
||||
// wires the checker in and UpdateCheckResult reads through to it.
|
||||
func TestUpdateCheckResult_ReflectsRegisteredChecker(t *testing.T) {
|
||||
s := NewServer(nil, nil, "http://localhost", false, false, false)
|
||||
|
||||
checker := updatecheck.NewChecker(nil, "owner/repo", "v1.0.0")
|
||||
s.SetUpdateChecker(checker)
|
||||
|
||||
result := s.UpdateCheckResult()
|
||||
if result.CurrentVersion != "v1.0.0" {
|
||||
t.Errorf("Expected UpdateCheckResult to read through to the registered checker, got %+v", result)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/setup"
|
||||
)
|
||||
|
||||
// TestIssue634_NonNumericMargeAccountUUIDDoesNotLoseDevice reproduces
|
||||
// https://github.com/gesellix/Bose-SoundTouch/issues/634
|
||||
//
|
||||
// A SoundTouch 10 had SSH enabled via the USB-stick method (rather than
|
||||
// AfterTouch's own telnet-based enable-ssh flow) and, when discovered,
|
||||
// reported a `margeAccountUUID` of `stick@local` instead of the usual
|
||||
// 7-digit numeric Bose account ID. `handleDiscoveredDevice`
|
||||
// (pkg/service/handlers/server.go) passes MargeAccountUUID straight
|
||||
// through to DataStore.SaveDeviceInfo, which used to reject anything
|
||||
// containing "@" as an "invalid account ID" via isSafeIdentifier's
|
||||
// strict alnum-only allowlist. The device was never persisted at all.
|
||||
//
|
||||
// The fix widened datastore.IsSafeIdentifier to accept any device-reported
|
||||
// identifier that's safe to use as a path component / XML value /
|
||||
// telnet-command token, rather than requiring Bose's own 7-digit numeric
|
||||
// format. setup's separate, stricter 7-digit-only IsValidAccountID was
|
||||
// deleted outright in favor of calling datastore.IsSafeIdentifier directly
|
||||
// everywhere an account ID needs validating — one validator, not two. So
|
||||
// handleDiscoveredDevice needed no changes: it already passed
|
||||
// MargeAccountUUID through unmodified, and now the datastore accepts it.
|
||||
//
|
||||
// What this test locks in:
|
||||
//
|
||||
// - A speaker reporting a non-numeric margeAccountUUID is saved
|
||||
// under that account verbatim (not coerced to "default" — "default"
|
||||
// remains reserved for a genuinely empty/unpaired margeAccountUUID).
|
||||
//
|
||||
// What this test would catch if it flipped:
|
||||
//
|
||||
// - If IsSafeIdentifier's allowlist regresses to reject "@" again,
|
||||
// GetDeviceInfo below would error with "invalid account ID" instead
|
||||
// of returning the device — the #634 symptom.
|
||||
func TestIssue634_NonNumericMargeAccountUUIDDoesNotLoseDevice(t *testing.T) {
|
||||
tempDir, err := os.MkdirTemp("", "issue634-*")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
const deviceInfoXML = `<info deviceID="001122334455">
|
||||
<name>Kitchen SoundTouch</name>
|
||||
<type>SoundTouch 10</type>
|
||||
<margeAccountUUID>stick@local</margeAccountUUID>
|
||||
<components>
|
||||
<component>
|
||||
<componentCategory>SCM</componentCategory>
|
||||
<softwareVersion>27.0.6.46330.5043500 epdbuild.trunk.hepdswbld04.2022-08-04T11:20:29</softwareVersion>
|
||||
<serialNumber>I6332527703739342000020</serialNumber>
|
||||
</component>
|
||||
<component>
|
||||
<componentCategory>PackagedProduct</componentCategory>
|
||||
<softwareVersion>27.0.6.46330.5043500 epdbuild.trunk.hepdswbld04.2022-08-04T11:20:29</softwareVersion>
|
||||
<serialNumber>069231P63364828AE</serialNumber>
|
||||
</component>
|
||||
</components>
|
||||
<margeURL>https://streaming.bose.com</margeURL>
|
||||
<networkInfo type="SCM">
|
||||
<macAddress>001122334455</macAddress>
|
||||
<ipAddress>203.0.113.10</ipAddress>
|
||||
</networkInfo>
|
||||
<moduleType>sm2</moduleType>
|
||||
<variant>rhino</variant>
|
||||
<variantMode>normal</variantMode>
|
||||
<countryCode>US</countryCode>
|
||||
<regionCode>US</regionCode>
|
||||
</info>`
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/info" {
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
fmt.Fprint(w, deviceInfoXML)
|
||||
} else {
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
deviceIP := server.URL[len("http://"):]
|
||||
ds := datastore.NewDataStore(tempDir)
|
||||
sm := setup.NewManager(server.URL, ds, nil)
|
||||
|
||||
srv := NewServer(ds, sm, server.URL, false, false, false)
|
||||
|
||||
discoveredDevice := models.DiscoveredDevice{
|
||||
Host: deviceIP,
|
||||
Name: "Legacy Discovery Name",
|
||||
ModelID: "SoundTouch 10",
|
||||
SerialNo: "",
|
||||
DiscoveryMethod: "UPnP",
|
||||
}
|
||||
|
||||
t.Logf("Test scenario: /info reports non-numeric margeAccountUUID %q", "stick@local")
|
||||
|
||||
srv.handleDiscoveredDevice(discoveredDevice)
|
||||
|
||||
const (
|
||||
expectedAccountID = "stick@local"
|
||||
expectedDeviceID = "001122334455"
|
||||
)
|
||||
|
||||
deviceInfo, err := ds.GetDeviceInfo(expectedAccountID, expectedDeviceID)
|
||||
if err != nil {
|
||||
t.Fatalf("device was not saved under account %q: %v (this is the #634 symptom — "+
|
||||
"SaveDeviceInfo rejects the raw margeAccountUUID as an invalid account ID)",
|
||||
expectedAccountID, err)
|
||||
}
|
||||
|
||||
if deviceInfo.Name != "Kitchen SoundTouch" {
|
||||
t.Errorf("Name = %q, want %q", deviceInfo.Name, "Kitchen SoundTouch")
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,13 @@ package handlers
|
||||
|
||||
import "net/url"
|
||||
|
||||
var telnetMigrationURLKeys = []string{
|
||||
"marge_url",
|
||||
"stats_url",
|
||||
"sw_update_url",
|
||||
"bmx_url",
|
||||
}
|
||||
|
||||
// migrationOptionKeys is the allow-list of query parameters carried into
|
||||
// the migration manager's options map. Two families coexist:
|
||||
//
|
||||
@@ -43,3 +50,15 @@ func parseMigrationOptions(query url.Values) map[string]string {
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func presentTelnetURLOverrides(query url.Values) []string {
|
||||
var present []string
|
||||
|
||||
for _, key := range telnetMigrationURLKeys {
|
||||
if _, ok := query[key]; ok {
|
||||
present = append(present, key)
|
||||
}
|
||||
}
|
||||
|
||||
return present
|
||||
}
|
||||
|
||||
@@ -226,23 +226,28 @@ type errResolve string
|
||||
func (e errResolve) Error() string { return string(e) }
|
||||
|
||||
func TestCheck443Reachability_LANProbeMatchesListenerOutcome(t *testing.T) {
|
||||
// Spin up a listener on a random port and use that port via resolver
|
||||
// trickery: we point the LAN host at 127.0.0.1 and rely on the fact that
|
||||
// nothing answers on :443 in test environments. The point of this test
|
||||
// is to lock in the result-shape: when localhost:443 is closed (the
|
||||
// default in CI), the function still returns a well-formed result and
|
||||
// reports the resolved LAN host. Uses HTTPS so the NotApplicable
|
||||
// short-circuit doesn't fire.
|
||||
res := Check443Reachability(8443, "https://1.2.3.4:8443", func(string) (string, error) {
|
||||
return "1.2.3.4", nil
|
||||
// Point the LAN host at 127.0.0.1 and rely on the fact that nothing
|
||||
// answers on :443 in test environments. The point of this test is to
|
||||
// lock in the result-shape: when localhost:443 is closed (the default
|
||||
// in CI), the function still returns a well-formed result and reports
|
||||
// the resolved LAN host. Uses HTTPS so the NotApplicable short-circuit
|
||||
// doesn't fire.
|
||||
//
|
||||
// Deliberately NOT a real routable address like 1.2.3.4: probing an
|
||||
// arbitrary internet destination's reachability depends on the tester's
|
||||
// own network path (transparent proxies, DPI middleboxes, or sinkholed
|
||||
// "known test IP" blocklists can all make it appear reachable), which
|
||||
// is exactly what made this test fail outside CI (#683).
|
||||
res := Check443Reachability(8443, "https://127.0.0.1:8443", func(string) (string, error) {
|
||||
return "127.0.0.1", nil
|
||||
}, 200*time.Millisecond)
|
||||
|
||||
if res.Skipped {
|
||||
t.Fatalf("expected Skipped=false, got true")
|
||||
}
|
||||
|
||||
if res.LANHost != "1.2.3.4" {
|
||||
t.Errorf("expected LANHost=1.2.3.4, got %q", res.LANHost)
|
||||
if res.LANHost != "127.0.0.1" {
|
||||
t.Errorf("expected LANHost=127.0.0.1, got %q", res.LANHost)
|
||||
}
|
||||
|
||||
// In any sane CI environment nothing is listening on :443, so both
|
||||
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/setup"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/spotify"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/tts"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/updatecheck"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/ssh"
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
@@ -51,6 +52,8 @@ type Server struct {
|
||||
recordEnabled bool
|
||||
discoveryInterval time.Duration
|
||||
discoveryEnabled bool
|
||||
updateCheckInterval time.Duration // live update-check interval; see SetUpdateCheckSettings
|
||||
updateCheckEnabled bool // live update-check opt-in; defaults off (#591)
|
||||
dnsEnabled bool
|
||||
dnsUpstream []string
|
||||
dnsBindAddr string
|
||||
@@ -70,6 +73,7 @@ type Server struct {
|
||||
mgmtPassword string
|
||||
adminAreaAuth string // "" (unset) / "enabled" / "disabled" — see datastore.Settings.AdminAreaAuth
|
||||
dismissedAnnouncements map[string]time.Time // announcement id -> most recent dismissal; see RecordDismissal
|
||||
updateChecker *updatecheck.Checker // the HTTP-checking object; nil unless SetUpdateChecker was called
|
||||
spotifyClientID string
|
||||
spotifyClientSecret string
|
||||
spotifyRedirectURI string
|
||||
@@ -139,10 +143,14 @@ func NewServer(ds *datastore.DataStore, sm *setup.Manager, serverURL string, red
|
||||
recordEnabled: recordEnabled,
|
||||
discoveryInterval: 5 * time.Minute,
|
||||
discoveryEnabled: true,
|
||||
peerObserver: newPeerObserver(),
|
||||
healthRegistry: health.NewRegistry(),
|
||||
authProbes: newAuthProbeRegistry(defaultAuthProbeTTL),
|
||||
deprecatedRoutes: newDeprecatedRouteTracker(),
|
||||
// The update check is opt-in (#591): only the interval gets a default,
|
||||
// updateCheckEnabled stays false so no install starts making outbound
|
||||
// GitHub calls without an explicit yes.
|
||||
updateCheckInterval: 24 * time.Hour,
|
||||
peerObserver: newPeerObserver(),
|
||||
healthRegistry: health.NewRegistry(),
|
||||
authProbes: newAuthProbeRegistry(defaultAuthProbeTTL),
|
||||
deprecatedRoutes: newDeprecatedRouteTracker(),
|
||||
}
|
||||
|
||||
health.RegisterSourcesXMLPresent(s.healthRegistry, ds)
|
||||
@@ -581,6 +589,28 @@ func (s *Server) SetDiscoverySettings(interval time.Duration, enabled bool) {
|
||||
s.discoveryEnabled = enabled
|
||||
}
|
||||
|
||||
// SetUpdateCheckSettings sets the live update-check settings for the server.
|
||||
//
|
||||
// Kept adjacent to its getter (rather than next to GetDiscoverySettings
|
||||
// further down) so the pair reads as one unit; the background goroutine in
|
||||
// soundtouch-service re-reads them on every poll, which is what makes the
|
||||
// Settings-page toggle take effect without a restart.
|
||||
func (s *Server) SetUpdateCheckSettings(interval time.Duration, enabled bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.updateCheckInterval = interval
|
||||
s.updateCheckEnabled = enabled
|
||||
}
|
||||
|
||||
// GetUpdateCheckSettings returns the current update-check interval and enabled state.
|
||||
func (s *Server) GetUpdateCheckSettings() (time.Duration, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
return s.updateCheckInterval, s.updateCheckEnabled
|
||||
}
|
||||
|
||||
// SetDevicesChangedHook registers a callback fired after the known device set
|
||||
// changes (a discovery sweep or a manual add). The embedded web UI uses it to
|
||||
// re-sync its registry from the shared datastore — the single source of truth —
|
||||
@@ -1126,6 +1156,34 @@ func (s *Server) IsAnnouncementDismissed(id string) bool {
|
||||
return ok
|
||||
}
|
||||
|
||||
// SetUpdateChecker registers the update checker (#591). The checker itself is
|
||||
// always constructed and registered, regardless of whether the periodic check
|
||||
// is enabled, so /api/setup/version and the Announcements banner can read
|
||||
// LastResult() (e.g. a result persisted by an earlier run) even before the
|
||||
// periodic check has ever run. Only the periodic background check is gated by
|
||||
// the live enabled setting — see SetUpdateCheckSettings. Callers that leave
|
||||
// this nil are still safe: UpdateCheckResult returns the zero value.
|
||||
func (s *Server) SetUpdateChecker(c *updatecheck.Checker) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.updateChecker = c
|
||||
}
|
||||
|
||||
// UpdateCheckResult returns the last known update-check result, or the
|
||||
// zero value (Available: false) if the check was never enabled.
|
||||
func (s *Server) UpdateCheckResult() updatecheck.Result {
|
||||
s.mu.RLock()
|
||||
checker := s.updateChecker
|
||||
s.mu.RUnlock()
|
||||
|
||||
if checker == nil {
|
||||
return updatecheck.Result{}
|
||||
}
|
||||
|
||||
return checker.LastResult()
|
||||
}
|
||||
|
||||
// SetInternalPaths sets the internal paths for the server.
|
||||
func (s *Server) SetInternalPaths(paths []string) {
|
||||
s.mu.Lock()
|
||||
@@ -1294,6 +1352,19 @@ func (s *Server) GetSettings() (string, string) {
|
||||
return s.serverURL, s.httpsServerURL
|
||||
}
|
||||
|
||||
// DNSHijackEnabled reports whether this server's DNS-hijack redirection
|
||||
// (SetDNSSettings) is currently active. DNS-level migration never changes a
|
||||
// speaker's own reported MargeURL -- only how a Bose cloud hostname resolves
|
||||
// on the network -- so callers use this alongside
|
||||
// discovery.InterceptedBoseHosts to recognize such a speaker as effectively
|
||||
// local despite its MargeURL literally being a Bose hostname.
|
||||
func (s *Server) DNSHijackEnabled() bool {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
return s.dnsEnabled
|
||||
}
|
||||
|
||||
// IsSpotifyConfigured returns whether Spotify integration is configured.
|
||||
func (s *Server) IsSpotifyConfigured() bool {
|
||||
s.mu.RLock()
|
||||
|
||||
@@ -129,6 +129,20 @@ pre { background-color: #eee; padding: 10px; overflow-x: auto; font-size: 12px;
|
||||
background-color: #d32f2f;
|
||||
}
|
||||
|
||||
/* .btn-primary marks the one "do the thing" confirm action of a panel
|
||||
(Save Settings, Apply Suggested/Custom Plan, Enable SSH, …). Everything
|
||||
else stays the plain default button so color consistently signals the
|
||||
same two meanings everywhere: primary = confirm, danger = destructive. */
|
||||
.btn-primary {
|
||||
background-color: #2196f3;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 5px 10px;
|
||||
}
|
||||
.btn-primary:hover {
|
||||
background-color: #1769aa;
|
||||
}
|
||||
|
||||
.badge {
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user