Compare commits
@@ -0,0 +1,5 @@
|
||||
# Files intentionally not linked in docs/SUMMARY.md.
|
||||
# Paths are relative to the docs/ directory.
|
||||
# Lines starting with # and blank lines are ignored.
|
||||
|
||||
#analysis/bose-soundtouch-community-tools.md
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
# Docker/Service Settings
|
||||
SOUNDTOUCH_HOSTNAME=soundtouch.local
|
||||
SOUNDTOUCH_VERSION=latest
|
||||
|
||||
# Discovery Settings
|
||||
DISCOVERY_TIMEOUT=5s
|
||||
|
||||
@@ -37,6 +37,12 @@
|
||||
},
|
||||
{
|
||||
"pattern": "https://apkpure.com/bose-soundtouch/com.bose.soundtouch"
|
||||
},
|
||||
{
|
||||
"pattern": "^https://bose\\.fandom\\.com/"
|
||||
},
|
||||
{
|
||||
"pattern": "^https://www\\.reddit\\.com/"
|
||||
}
|
||||
],
|
||||
"replacementPatterns": [
|
||||
|
||||
@@ -112,7 +112,7 @@ jobs:
|
||||
if [ "${{ matrix.goos }}" = "windows" ]; then
|
||||
output_name="${output_name}.exe"
|
||||
fi
|
||||
go build -o "$output_name" ./cmd/soundtouch-cli
|
||||
go build -trimpath -ldflags="-s -w" -o "$output_name" ./cmd/soundtouch-cli
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
@@ -220,7 +220,7 @@ jobs:
|
||||
|
||||
- name: Test CLI build and help
|
||||
run: |
|
||||
go build -o soundtouch-cli ./cmd/soundtouch-cli
|
||||
go build -trimpath -ldflags="-s -w" -o soundtouch-cli ./cmd/soundtouch-cli
|
||||
./soundtouch-cli -help
|
||||
|
||||
- name: Test library imports
|
||||
|
||||
@@ -151,6 +151,7 @@ jobs:
|
||||
rm -f "$OUTPUT_NAME" "$OUTPUT_NAME.sha256" "$OUTPUT_NAME.sha512"
|
||||
|
||||
if ! go build \
|
||||
-trimpath \
|
||||
-ldflags="-s -w" \
|
||||
-o "$OUTPUT_NAME" \
|
||||
"$CMD_PATH"; then
|
||||
@@ -171,6 +172,9 @@ jobs:
|
||||
|
||||
# Build Web
|
||||
build_binary "soundtouch-web" "./cmd/soundtouch-web"
|
||||
|
||||
# Build Backup
|
||||
build_binary "soundtouch-backup" "./cmd/soundtouch-backup"
|
||||
id: build
|
||||
|
||||
- name: Generate individual checksums
|
||||
@@ -178,6 +182,7 @@ jobs:
|
||||
CLI_NAME="${{ steps.build.outputs.soundtouch-cli }}"
|
||||
SVC_NAME="${{ steps.build.outputs.soundtouch-service }}"
|
||||
WEB_NAME="${{ steps.build.outputs.soundtouch-web }}"
|
||||
BCK_NAME="${{ steps.build.outputs.soundtouch-backup }}"
|
||||
|
||||
# Use atomic operations to avoid conflicts
|
||||
TEMP_DIR=$(mktemp -d)
|
||||
@@ -194,6 +199,7 @@ jobs:
|
||||
generate_checksums "$CLI_NAME"
|
||||
generate_checksums "$SVC_NAME"
|
||||
generate_checksums "$WEB_NAME"
|
||||
generate_checksums "$BCK_NAME"
|
||||
|
||||
# Cleanup
|
||||
rm -rf "$TEMP_DIR"
|
||||
@@ -207,6 +213,7 @@ jobs:
|
||||
build/soundtouch-cli-v*
|
||||
build/soundtouch-service-v*
|
||||
build/soundtouch-web-v*
|
||||
build/soundtouch-backup-v*
|
||||
retention-days: 1
|
||||
|
||||
checksums:
|
||||
@@ -233,7 +240,7 @@ jobs:
|
||||
mkdir -p release-files
|
||||
|
||||
# Move all files from subdirectories to the collection directory
|
||||
find . -mindepth 2 -type f \( -name "soundtouch-cli-*" -o -name "soundtouch-service-*" -o -name "soundtouch-web-*" \) -exec mv {} release-files/ \;
|
||||
find . -mindepth 2 -type f \( -name "soundtouch-cli-*" -o -name "soundtouch-service-*" -o -name "soundtouch-web-*" -o -name "soundtouch-backup-*" \) -exec mv {} release-files/ \;
|
||||
|
||||
# Remove empty directories
|
||||
find . -type d -empty -delete
|
||||
@@ -248,14 +255,14 @@ jobs:
|
||||
# Generate combined checksums (exclude individual .sha256/.sha512 files)
|
||||
if ls soundtouch-* 1> /dev/null 2>&1; then
|
||||
# Only checksum the actual binaries, not the .sha256/.sha512 files
|
||||
ls soundtouch-* | grep -v '\.sha256$' | grep -v '\.sha512$' | xargs sha256sum > checksums.sha256
|
||||
ls soundtouch-* | grep -v '\.sha256$' | grep -v '\.sha512$' | xargs sha512sum > checksums.sha512
|
||||
ls soundtouch-cli-* soundtouch-service-* soundtouch-web-* soundtouch-backup-* | grep -v '\.sha256$' | grep -v '\.sha512$' | xargs sha256sum > checksums.sha256
|
||||
ls soundtouch-cli-* soundtouch-service-* soundtouch-web-* soundtouch-backup-* | grep -v '\.sha256$' | grep -v '\.sha512$' | xargs sha512sum > checksums.sha512
|
||||
|
||||
echo "📋 Generated combined checksums:"
|
||||
cat checksums.sha256
|
||||
|
||||
# Verify all expected files are present (binaries only, not checksum files)
|
||||
EXPECTED_COUNT=21 # 7 platforms * 3 binaries
|
||||
EXPECTED_COUNT=28 # 7 platforms * 4 binaries
|
||||
ACTUAL_COUNT=$(ls soundtouch-* | grep -v '\.sha256$' | grep -v '\.sha512$' | wc -l)
|
||||
|
||||
if [[ $ACTUAL_COUNT -ne $EXPECTED_COUNT ]]; then
|
||||
@@ -392,6 +399,12 @@ jobs:
|
||||
./soundtouch-web
|
||||
\`\`\`
|
||||
|
||||
### SoundTouch Backup
|
||||
\`\`\`bash
|
||||
# Back up cloud account and all paired speakers in one go
|
||||
./soundtouch-backup all
|
||||
\`\`\`
|
||||
|
||||
## 🧪 Tested Hardware
|
||||
|
||||
- Bose SoundTouch 10
|
||||
@@ -410,7 +423,7 @@ jobs:
|
||||
- Windows (amd64)
|
||||
- FreeBSD (amd64)
|
||||
|
||||
`soundtouch-cli`, `soundtouch-service`, and `soundtouch-web` are included.
|
||||
`soundtouch-cli`, `soundtouch-service`, `soundtouch-web`, and `soundtouch-backup` are included.
|
||||
|
||||
## 🔐 Checksums
|
||||
|
||||
@@ -466,6 +479,7 @@ jobs:
|
||||
release-assets/soundtouch-cli-v*
|
||||
release-assets/soundtouch-service-v*
|
||||
release-assets/soundtouch-web-v*
|
||||
release-assets/soundtouch-backup-v*
|
||||
release-assets/checksums.sha256
|
||||
release-assets/checksums.sha512
|
||||
fail_on_unmatched_files: true
|
||||
@@ -493,6 +507,7 @@ jobs:
|
||||
release-assets/soundtouch-cli-v*
|
||||
release-assets/soundtouch-service-v*
|
||||
release-assets/soundtouch-web-v*
|
||||
release-assets/soundtouch-backup-v*
|
||||
release-assets/checksums.sha256
|
||||
release-assets/checksums.sha512
|
||||
fail_on_unmatched_files: true
|
||||
@@ -572,7 +587,7 @@ jobs:
|
||||
- name: Notify success
|
||||
run: |
|
||||
echo "🎉 Release ${{ needs.validate.outputs.version }} completed successfully!"
|
||||
echo "📦 Binaries built for 7 platforms (CLI, Service, and Web)"
|
||||
echo "📦 Binaries built for 7 platforms (CLI, Service, Web, and Backup)"
|
||||
echo "🐳 Docker image published to ghcr.io"
|
||||
echo "🔐 Checksums generated and verified"
|
||||
echo "📋 Release notes automatically generated"
|
||||
|
||||
@@ -12,6 +12,7 @@ dist/
|
||||
#example-upnp
|
||||
|
||||
# Root-level binary executables (exclude built binaries in root)
|
||||
/soundtouch-backup
|
||||
/soundtouch-cli
|
||||
/soundtouch-service
|
||||
/soundtouch-web
|
||||
@@ -57,6 +58,15 @@ vendor/
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
|
||||
# Android MITM setup — downloaded/generated artefacts, not committed
|
||||
scripts/android/bose.apk
|
||||
scripts/android/frida-server
|
||||
scripts/android/frida-server.xz
|
||||
scripts/android/frida/
|
||||
scripts/android/frida-venv/
|
||||
scripts/android/captures/
|
||||
scripts/android/mitm/
|
||||
|
||||
# Temporary files
|
||||
*.tmp
|
||||
*.temp
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# Build stage
|
||||
FROM --platform=$BUILDPLATFORM golang:1.26.2-alpine AS builder
|
||||
FROM --platform=$BUILDPLATFORM golang:1.26.3-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
|
||||
|
||||
@@ -24,81 +24,99 @@ SCANNER_NAME=mdns-scanner
|
||||
SCANNER_PATH=./cmd/$(SCANNER_NAME)
|
||||
FAVICON_GEN_NAME=favicon-gen
|
||||
FAVICON_GEN_PATH=./cmd/$(FAVICON_GEN_NAME)
|
||||
BACKUP_NAME=soundtouch-backup
|
||||
BACKUP_PATH=./cmd/$(BACKUP_NAME)
|
||||
BUILD_DIR=./build
|
||||
|
||||
# Version info
|
||||
# No ldflags needed - using debug.BuildInfo since Go 1.18
|
||||
# Build flags: strip debug info/DWARF for smaller binaries, remove local paths for reproducibility
|
||||
BUILDFLAGS=-trimpath -ldflags="-s -w"
|
||||
|
||||
all: check build
|
||||
|
||||
build: build-cli build-service build-web build-examples build-favicon-gen
|
||||
build: build-cli build-service build-web build-examples build-favicon-gen build-backup
|
||||
|
||||
build-cli:
|
||||
@echo "Building $(BINARY_NAME)..."
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
$(GOBUILD) -o $(BUILD_DIR)/$(BINARY_NAME) $(BINARY_PATH)
|
||||
$(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME) $(BINARY_PATH)
|
||||
|
||||
build-service:
|
||||
@echo "Building $(SERVICE_NAME)..."
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
$(GOBUILD) -o $(BUILD_DIR)/$(SERVICE_NAME) $(SERVICE_PATH)
|
||||
$(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(SERVICE_NAME) $(SERVICE_PATH)
|
||||
|
||||
build-web:
|
||||
@echo "Building $(WEB_NAME)..."
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
$(GOBUILD) -o $(BUILD_DIR)/$(WEB_NAME) $(WEB_PATH)
|
||||
$(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(WEB_NAME) $(WEB_PATH)
|
||||
|
||||
build-examples:
|
||||
@echo "Building $(EXAMPLE_MDNS_NAME)..."
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
$(GOBUILD) -o $(BUILD_DIR)/$(EXAMPLE_MDNS_NAME) $(EXAMPLE_MDNS_PATH)
|
||||
$(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(EXAMPLE_MDNS_NAME) $(EXAMPLE_MDNS_PATH)
|
||||
@echo "Building $(EXAMPLE_UPNP_NAME)..."
|
||||
$(GOBUILD) -o $(BUILD_DIR)/$(EXAMPLE_UPNP_NAME) $(EXAMPLE_UPNP_PATH)
|
||||
$(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(EXAMPLE_UPNP_NAME) $(EXAMPLE_UPNP_PATH)
|
||||
@echo "Building $(SCANNER_NAME)..."
|
||||
$(GOBUILD) -o $(BUILD_DIR)/$(SCANNER_NAME) $(SCANNER_PATH)
|
||||
$(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(SCANNER_NAME) $(SCANNER_PATH)
|
||||
|
||||
build-favicon-gen:
|
||||
@echo "Building $(FAVICON_GEN_NAME)..."
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
$(GOBUILD) -o $(BUILD_DIR)/$(FAVICON_GEN_NAME) $(FAVICON_GEN_PATH)
|
||||
$(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(FAVICON_GEN_NAME) $(FAVICON_GEN_PATH)
|
||||
|
||||
build-all: build-linux build-darwin build-windows build-examples-all
|
||||
build-backup:
|
||||
@echo "Building $(BACKUP_NAME)..."
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
$(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(BACKUP_NAME) $(BACKUP_PATH)
|
||||
|
||||
build-all: build-linux build-linux-armv7 build-darwin build-windows build-examples-all
|
||||
|
||||
build-linux:
|
||||
@echo "Building for Linux..."
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
GOOS=linux GOARCH=amd64 $(GOBUILD) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-amd64 $(BINARY_PATH)
|
||||
GOOS=linux GOARCH=amd64 $(GOBUILD) -o $(BUILD_DIR)/$(SERVICE_NAME)-linux-amd64 $(SERVICE_PATH)
|
||||
GOOS=linux GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-amd64 $(BINARY_PATH)
|
||||
GOOS=linux GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(SERVICE_NAME)-linux-amd64 $(SERVICE_PATH)
|
||||
GOOS=linux GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(BACKUP_NAME)-linux-amd64 $(BACKUP_PATH)
|
||||
|
||||
build-linux-armv7:
|
||||
@echo "Building for Linux ARMv7 (CGO_ENABLED=0 for kernel 3.14+ compatibility)..."
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
GOOS=linux GOARCH=arm GOARM=7 CGO_ENABLED=0 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(SERVICE_NAME)-linux-armv7 $(SERVICE_PATH)
|
||||
GOOS=linux GOARCH=arm GOARM=7 CGO_ENABLED=0 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-armv7 $(BINARY_PATH)
|
||||
GOOS=linux GOARCH=arm GOARM=7 CGO_ENABLED=0 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(BACKUP_NAME)-linux-armv7 $(BACKUP_PATH)
|
||||
|
||||
build-darwin:
|
||||
@echo "Building for macOS..."
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
GOOS=darwin GOARCH=amd64 $(GOBUILD) -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-amd64 $(BINARY_PATH)
|
||||
GOOS=darwin GOARCH=arm64 $(GOBUILD) -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-arm64 $(BINARY_PATH)
|
||||
GOOS=darwin GOARCH=amd64 $(GOBUILD) -o $(BUILD_DIR)/$(SERVICE_NAME)-darwin-amd64 $(SERVICE_PATH)
|
||||
GOOS=darwin GOARCH=arm64 $(GOBUILD) -o $(BUILD_DIR)/$(SERVICE_NAME)-darwin-arm64 $(SERVICE_PATH)
|
||||
GOOS=darwin GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-amd64 $(BINARY_PATH)
|
||||
GOOS=darwin GOARCH=arm64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-arm64 $(BINARY_PATH)
|
||||
GOOS=darwin GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(SERVICE_NAME)-darwin-amd64 $(SERVICE_PATH)
|
||||
GOOS=darwin GOARCH=arm64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(SERVICE_NAME)-darwin-arm64 $(SERVICE_PATH)
|
||||
GOOS=darwin GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(BACKUP_NAME)-darwin-amd64 $(BACKUP_PATH)
|
||||
GOOS=darwin GOARCH=arm64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(BACKUP_NAME)-darwin-arm64 $(BACKUP_PATH)
|
||||
|
||||
build-windows:
|
||||
@echo "Building for Windows..."
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
GOOS=windows GOARCH=amd64 $(GOBUILD) -o $(BUILD_DIR)/$(BINARY_NAME)-windows-amd64.exe $(BINARY_PATH)
|
||||
GOOS=windows GOARCH=amd64 $(GOBUILD) -o $(BUILD_DIR)/$(SERVICE_NAME)-windows-amd64.exe $(SERVICE_PATH)
|
||||
GOOS=windows GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-windows-amd64.exe $(BINARY_PATH)
|
||||
GOOS=windows GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(SERVICE_NAME)-windows-amd64.exe $(SERVICE_PATH)
|
||||
GOOS=windows GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(BACKUP_NAME)-windows-amd64.exe $(BACKUP_PATH)
|
||||
|
||||
build-examples-all:
|
||||
@echo "Building examples for all platforms..."
|
||||
@mkdir -p $(BUILD_DIR)
|
||||
GOOS=linux GOARCH=amd64 $(GOBUILD) -o $(BUILD_DIR)/$(EXAMPLE_MDNS_NAME)-linux-amd64 $(EXAMPLE_MDNS_PATH)
|
||||
GOOS=darwin GOARCH=amd64 $(GOBUILD) -o $(BUILD_DIR)/$(EXAMPLE_MDNS_NAME)-darwin-amd64 $(EXAMPLE_MDNS_PATH)
|
||||
GOOS=darwin GOARCH=arm64 $(GOBUILD) -o $(BUILD_DIR)/$(EXAMPLE_MDNS_NAME)-darwin-arm64 $(EXAMPLE_MDNS_PATH)
|
||||
GOOS=windows GOARCH=amd64 $(GOBUILD) -o $(BUILD_DIR)/$(EXAMPLE_MDNS_NAME)-windows-amd64.exe $(EXAMPLE_MDNS_PATH)
|
||||
GOOS=linux GOARCH=amd64 $(GOBUILD) -o $(BUILD_DIR)/$(EXAMPLE_UPNP_NAME)-linux-amd64 $(EXAMPLE_UPNP_PATH)
|
||||
GOOS=darwin GOARCH=amd64 $(GOBUILD) -o $(BUILD_DIR)/$(EXAMPLE_UPNP_NAME)-darwin-amd64 $(EXAMPLE_UPNP_PATH)
|
||||
GOOS=darwin GOARCH=arm64 $(GOBUILD) -o $(BUILD_DIR)/$(EXAMPLE_UPNP_NAME)-darwin-arm64 $(EXAMPLE_UPNP_PATH)
|
||||
GOOS=windows GOARCH=amd64 $(GOBUILD) -o $(BUILD_DIR)/$(EXAMPLE_UPNP_NAME)-windows-amd64.exe $(EXAMPLE_UPNP_PATH)
|
||||
GOOS=linux GOARCH=amd64 $(GOBUILD) -o $(BUILD_DIR)/$(SCANNER_NAME)-linux-amd64 $(SCANNER_PATH)
|
||||
GOOS=darwin GOARCH=amd64 $(GOBUILD) -o $(BUILD_DIR)/$(SCANNER_NAME)-darwin-amd64 $(SCANNER_PATH)
|
||||
GOOS=darwin GOARCH=arm64 $(GOBUILD) -o $(BUILD_DIR)/$(SCANNER_NAME)-darwin-arm64 $(SCANNER_PATH)
|
||||
GOOS=windows GOARCH=amd64 $(GOBUILD) -o $(BUILD_DIR)/$(SCANNER_NAME)-windows-amd64.exe $(SCANNER_PATH)
|
||||
GOOS=linux GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(EXAMPLE_MDNS_NAME)-linux-amd64 $(EXAMPLE_MDNS_PATH)
|
||||
GOOS=darwin GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(EXAMPLE_MDNS_NAME)-darwin-amd64 $(EXAMPLE_MDNS_PATH)
|
||||
GOOS=darwin GOARCH=arm64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(EXAMPLE_MDNS_NAME)-darwin-arm64 $(EXAMPLE_MDNS_PATH)
|
||||
GOOS=windows GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(EXAMPLE_MDNS_NAME)-windows-amd64.exe $(EXAMPLE_MDNS_PATH)
|
||||
GOOS=linux GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(EXAMPLE_UPNP_NAME)-linux-amd64 $(EXAMPLE_UPNP_PATH)
|
||||
GOOS=darwin GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(EXAMPLE_UPNP_NAME)-darwin-amd64 $(EXAMPLE_UPNP_PATH)
|
||||
GOOS=darwin GOARCH=arm64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(EXAMPLE_UPNP_NAME)-darwin-arm64 $(EXAMPLE_UPNP_PATH)
|
||||
GOOS=windows GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(EXAMPLE_UPNP_NAME)-windows-amd64.exe $(EXAMPLE_UPNP_PATH)
|
||||
GOOS=linux GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(SCANNER_NAME)-linux-amd64 $(SCANNER_PATH)
|
||||
GOOS=darwin GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(SCANNER_NAME)-darwin-amd64 $(SCANNER_PATH)
|
||||
GOOS=darwin GOARCH=arm64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(SCANNER_NAME)-darwin-arm64 $(SCANNER_PATH)
|
||||
GOOS=windows GOARCH=amd64 $(GOBUILD) $(BUILDFLAGS) -o $(BUILD_DIR)/$(SCANNER_NAME)-windows-amd64.exe $(SCANNER_PATH)
|
||||
|
||||
test:
|
||||
@echo "Running tests..."
|
||||
@@ -124,6 +142,7 @@ test-http-client:
|
||||
--env-file /workdir/http-client.env.json \
|
||||
--env ci \
|
||||
/workdir/spotify_registration.http \
|
||||
/workdir/amazon_registration.http \
|
||||
/workdir/create_account.http \
|
||||
/workdir/register_device.http \
|
||||
/workdir/spotify_full_flow.http \
|
||||
@@ -135,6 +154,7 @@ test-http-client:
|
||||
/workdir/get_soundtouch_updates.http \
|
||||
/workdir/get_streaming_token.http \
|
||||
/workdir/post_oauth_token.http \
|
||||
/workdir/post_oauth_token_amazon.http \
|
||||
/workdir/get_provider_settings.http \
|
||||
/workdir/tunein_playback_station.http \
|
||||
/workdir/set_preset_6.http \
|
||||
@@ -155,6 +175,7 @@ test-http-client:
|
||||
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 down; \
|
||||
exit $$EXIT_CODE
|
||||
|
||||
@@ -259,6 +280,18 @@ dev-web-port: build-web
|
||||
fi
|
||||
cd cmd/soundtouch-web && ../../$(BUILD_DIR)/$(WEB_NAME) -port $(PORT)
|
||||
|
||||
dev-backup: build-backup
|
||||
@echo "Running backup tool..."
|
||||
$(BUILD_DIR)/$(BACKUP_NAME) --help
|
||||
|
||||
dev-backup-cloud: build-backup
|
||||
@echo "Running cloud backup..."
|
||||
$(BUILD_DIR)/$(BACKUP_NAME) cloud
|
||||
|
||||
dev-backup-local: build-backup
|
||||
@echo "Running local backup (auto-discover)..."
|
||||
$(BUILD_DIR)/$(BACKUP_NAME) local --discover
|
||||
|
||||
dev-web-host: build-web
|
||||
@echo "Starting web UI with specific host..."
|
||||
@if [ -z "$(HOST)" ]; then \
|
||||
@@ -267,11 +300,12 @@ dev-web-host: build-web
|
||||
fi
|
||||
cd cmd/soundtouch-web && ../../$(BUILD_DIR)/$(WEB_NAME) -host $(HOST)
|
||||
|
||||
install: build-cli build-service build-web
|
||||
install: build-cli build-service build-web build-backup
|
||||
@echo "Installing binaries to $(GOPATH)/bin..."
|
||||
cp $(BUILD_DIR)/$(BINARY_NAME) $(GOPATH)/bin/
|
||||
cp $(BUILD_DIR)/$(SERVICE_NAME) $(GOPATH)/bin/
|
||||
cp $(BUILD_DIR)/$(WEB_NAME) $(GOPATH)/bin/
|
||||
cp $(BUILD_DIR)/$(BACKUP_NAME) $(GOPATH)/bin/
|
||||
|
||||
clean:
|
||||
@echo "Cleaning..."
|
||||
@@ -307,9 +341,11 @@ help:
|
||||
@echo " build - Build the CLI tool, service, and examples"
|
||||
@echo " build-cli - Build only the CLI tool"
|
||||
@echo " build-service - Build only the service"
|
||||
@echo " build-backup - Build only the backup tool"
|
||||
@echo " build-favicon-gen - Build the favicon generator"
|
||||
@echo " build-examples - Build only the example programs"
|
||||
@echo " build-all - Build for all platforms"
|
||||
@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 " check - Run fmt, vet, and tests"
|
||||
@@ -331,6 +367,9 @@ help:
|
||||
@echo " dev-scan-all - Scan all mDNS services on network"
|
||||
@echo " dev-scan-soundtouch - Scan specifically for SoundTouch mDNS services"
|
||||
@echo " dev-scan-http - Scan for HTTP mDNS services"
|
||||
@echo " dev-backup - Build and show backup tool help"
|
||||
@echo " dev-backup-cloud - Build and run cloud backup (prompts for credentials)"
|
||||
@echo " dev-backup-local - Build and run local backup (auto-discover speakers)"
|
||||
@echo " dev-web - Build and run web UI (default port 8080)"
|
||||
@echo " dev-web-port - Build and run web UI on custom port (PORT=8888)"
|
||||
@echo " dev-web-host - Build and run web UI with specific device (HOST=ip)"
|
||||
|
||||
@@ -1,549 +1,127 @@
|
||||
# Bose SoundTouch Toolkit
|
||||
|
||||
A comprehensive solution for controlling and preserving Bose SoundTouch devices, including a Go library, CLI tool, and a local service for cloud emulation.
|
||||
|
||||
[](https://pkg.go.dev/github.com/gesellix/bose-soundtouch)
|
||||
[](https://goreportcard.com/report/github.com/gesellix/bose-soundtouch)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
|
||||
> **Note**: This is an independent project based on the [official Bose SoundTouch Web API documentation](https://assets.bosecreative.com/m/496577402d128874/original/SoundTouch-Web-API.pdf). Not affiliated with or endorsed by Bose Corporation.
|
||||
> Independent project. Not affiliated with or endorsed by Bose Corporation.
|
||||
|
||||
## Features
|
||||
## Context: Cloud Shutdown
|
||||
|
||||
- ✅ **Complete API Coverage**: All available SoundTouch Web API endpoints implemented
|
||||
- 🎵 **Media Control**: Play, pause, stop, volume, bass, balance, source selection
|
||||
- 🔔 **Smart Notifications**: TTS messages, URL audio content, notification beeps (ST-10)
|
||||
- 🏠 **Multiroom Support**: Create and manage zones across multiple speakers
|
||||
- ⚡ **Real-time Events**: WebSocket connection for live device state monitoring
|
||||
- 🔍 **Device Discovery**: Automatic discovery via UPnP/SSDP and mDNS
|
||||
- 📻 **Content Navigation**: Browse and search TuneIn, Pandora, Spotify, local music
|
||||
- 📻 **Custom Radio**: Play any stream URL via [flexible proxying](docs/guides/CLI-REFERENCE.md#custom-radio-selection-via-soundtouch-service)
|
||||
- 📻 **RadioBrowser**: Access thousands of internet radio stations via [radio-browser.info](docs/reference/radio-browser.md)
|
||||
- 🎙️ **Station Management**: Add and play radio stations without presets
|
||||
- 🖥️ **CLI Tool**: Comprehensive command-line interface
|
||||
- 🌐 **SoundTouch Service**: Emulate Bose cloud services for offline device operation
|
||||
- 🔧 **Service Migration**: Migrate devices to use local services instead of Bose cloud (XML, Hosts, or DNS redirection)
|
||||
- 🔍 **DNS Discovery & Interception**: Dynamic DNS server for intercepting and logging Bose service queries (requires port 53)
|
||||
- 📊 **DNS Discovery Analysis**: Track and deduplicate all device DNS queries to discover hidden hostnames
|
||||
- 📊 **Traffic Analysis**: Proxy and log device communications
|
||||
- 📝 **HTTP Recording**: Persist interactions as re-playable `.http` files
|
||||
- 🔄 **Endpoint Mirroring**: Asynchronously mirror local requests to Bose cloud for parity testing
|
||||
- ⚖️ **Parity Logging**: Detect and record discrepancies between local and official Bose responses
|
||||
- 🧹 **Session Management**: Manage and cleanup recorded interaction sessions
|
||||
- 🔒 **Production Ready**: Extensive testing with real SoundTouch hardware
|
||||
- 🌐 **Cross-Platform**: Windows, macOS, Linux support
|
||||
Bose is shutting down SoundTouch cloud services on **May 6, 2026**. After that, music service browsing, preset sync, and the official SoundTouch app stop working. This toolkit lets you keep your speakers fully functional.
|
||||
|
||||
## Quick Start
|
||||
See the [Survival Guide](https://gesellix.github.io/Bose-SoundTouch/guides/SURVIVAL-GUIDE.html) for the full picture.
|
||||
|
||||
### Installation
|
||||
---
|
||||
|
||||
## Tools
|
||||
|
||||
### soundtouch-service — AfterTouch
|
||||
|
||||
A local server that replaces the Bose cloud ("AfterTouch"). Once your speaker is redirected to it, you have full control without any Bose cloud dependency. The built-in web UI at `http://localhost:8000` handles all setup — no config files needed to get started.
|
||||
|
||||
**Two scenarios:**
|
||||
|
||||
**Before shutdown — migrate your existing setup**
|
||||
While the Bose cloud is still running, use `soundtouch-backup` to save your account data. The local service web UI then helps with the migration so your speaker keeps its presets and credentials.
|
||||
|
||||
**After shutdown or factory reset — start fresh**
|
||||
Create a local account, configure your speakers, and start using them immediately. No Bose infrastructure required.
|
||||
|
||||
**Redirecting your speaker**
|
||||
|
||||
The service needs a stable address on your local network (e.g. `soundtouch.fritz.box` or `soundtouch.local`). The speaker must then be redirected to resolve the Bose cloud hostnames to that address. Two supported methods:
|
||||
|
||||
| Method | How it works | Notes |
|
||||
|--------------|-------------------------------------|--------------------------------------------------------------|
|
||||
| XML redirect | Upload a config XML via the Web API | Surgical; covers only registered endpoints; best for testing |
|
||||
| DNS/DHCP | Serve custom DNS on your network | Covers all devices at once; requires port 53 and TLS |
|
||||
|
||||
The web UI walks you through each method. DNS redirect requires HTTPS — the service manages its own CA certificate and the web UI guides you through trusting it on each speaker.
|
||||
|
||||
> **Note:** A hosts-file method (direct SSH edits to `/etc/hosts`) also exists in the codebase but is deprecated and not exposed in the web UI.
|
||||
|
||||
**Enabling SSH via USB stick**
|
||||
|
||||
Some setup steps require SSH access to the speaker. Enable it once per device: 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)), and insert it while the speaker is powered on. After reboot, root SSH is available with no password.
|
||||
|
||||
See [Device Initial Setup](https://gesellix.github.io/Bose-SoundTouch/guides/DEVICE-INITIAL-SETUP.html) and [Migration Guide](https://gesellix.github.io/Bose-SoundTouch/guides/MIGRATION-GUIDE.html) for step-by-step instructions.
|
||||
|
||||
---
|
||||
|
||||
### soundtouch-backup
|
||||
|
||||
Backs up your Bose cloud account (presets, paired devices, music sources) and each speaker's local state before the shutdown. Run `soundtouch-backup all` to capture everything in one step; it authenticates with the Bose cloud, then polls each paired speaker over the local network.
|
||||
|
||||
See the [soundtouch-backup README](cmd/soundtouch-backup/README.md) for usage.
|
||||
|
||||
---
|
||||
|
||||
### soundtouch-cli
|
||||
|
||||
Command-line control of any SoundTouch device: play/pause/volume, presets, source selection, multiroom zones, device discovery, and more. Works entirely over the local network — no cloud dependency. Well-suited for scripting and home automation.
|
||||
|
||||
See the [CLI Reference](https://gesellix.github.io/Bose-SoundTouch/guides/CLI-REFERENCE.html) for full usage.
|
||||
|
||||
---
|
||||
|
||||
### soundtouch-web
|
||||
|
||||
A standalone web UI for device control — play, pause, volume, preset selection, real-time status — served from a local Go binary. Complements `soundtouch-service` when you want a dedicated device-control interface separate from the setup/admin UI.
|
||||
|
||||
See the [soundtouch-web README](cmd/soundtouch-web/README.md) for usage.
|
||||
|
||||
---
|
||||
|
||||
### Go library
|
||||
|
||||
`pkg/client` provides a Go API for all SoundTouch device endpoints: media control, volume, presets, sources, zones, real-time WebSocket events, and device discovery. Use it to build your own integrations.
|
||||
|
||||
#### Install CLI and Service Tools
|
||||
```bash
|
||||
go install github.com/gesellix/bose-soundtouch/cmd/soundtouch-cli@latest
|
||||
go install github.com/gesellix/bose-soundtouch/cmd/soundtouch-service@latest
|
||||
```
|
||||
|
||||
#### Add Library to Your Project
|
||||
```bash
|
||||
go get github.com/gesellix/bose-soundtouch
|
||||
```
|
||||
|
||||
### CLI Usage
|
||||
See the [API Reference](https://gesellix.github.io/Bose-SoundTouch/reference/API-ENDPOINTS.html) and [pkg.go.dev](https://pkg.go.dev/github.com/gesellix/bose-soundtouch) for documentation.
|
||||
|
||||
Find SoundTouch devices on your network:
|
||||
```bash
|
||||
soundtouch-cli discover devices
|
||||
```
|
||||
|
||||
Control a device (replace `192.168.1.100` with your speaker's IP):
|
||||
```bash
|
||||
# Basic information
|
||||
soundtouch-cli --host 192.168.1.100 info
|
||||
|
||||
# Media controls
|
||||
soundtouch-cli --host 192.168.1.100 play start
|
||||
soundtouch-cli --host 192.168.1.100 volume set --level 50
|
||||
|
||||
# Preset management
|
||||
soundtouch-cli --host 192.168.1.100 preset list
|
||||
```
|
||||
|
||||
For full CLI documentation, see the [CLI Reference](https://gesellix.github.io/Bose-SoundTouch/guides/CLI-REFERENCE.html).
|
||||
|
||||
### SoundTouch Service (Cloud Shutdown Protection)
|
||||
|
||||
The `soundtouch-service` is a local server that emulates Bose's cloud services. This is critical for keeping your speakers functional after the **Bose Cloud Shutdown in May 2026**.
|
||||
|
||||
#### Key Features:
|
||||
- **🏠 Local Emulation**: BMX and Marge service implementation
|
||||
- **🔌 Easy Setup**: Activate SSH via USB stick (`remote_services` file)
|
||||
- **🔧 Device Migration**: Seamlessly transition devices to local control
|
||||
- **🌐 Web Management UI**: Easy browser-based setup and management
|
||||
- **💾 Persistent Data**: Store presets, recents, and sources locally
|
||||
- **🔄 Endpoint Mirroring**: Asynchronously mirror local requests to Bose cloud for parity testing
|
||||
- **⚖️ Parity Logging**: Detect and record discrepancies between local and official Bose responses
|
||||
- **📝 HTTP Recording**: Persist all interactions as re-playable `.http` files
|
||||
- **🧹 Session Management**: Manage and cleanup recorded interaction sessions
|
||||
|
||||
#### Quick Start:
|
||||
```bash
|
||||
# Start the service
|
||||
soundtouch-service
|
||||
```
|
||||
Open `http://localhost:8000` in your browser to manage your devices. Documentation is also available directly through the web interface.
|
||||
|
||||
For a comprehensive guide on transitioning your system, see the [Bose Cloud Shutdown: Survival Guide](https://gesellix.github.io/Bose-SoundTouch/guides/SURVIVAL-GUIDE.html).
|
||||
|
||||
Detailed service configuration and Docker instructions can be found in [SoundTouch Service Guide](https://gesellix.github.io/Bose-SoundTouch/guides/SOUNDTOUCH-SERVICE.html).
|
||||
|
||||
For professional migration tips and safety measures, see the [Migration & Safety Guide](https://gesellix.github.io/Bose-SoundTouch/guides/MIGRATION-SAFETY.html).
|
||||
|
||||
### Library Usage
|
||||
|
||||
#### Basic Control
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/client"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Connect to your SoundTouch device
|
||||
c := client.NewClient(&client.Config{
|
||||
Host: "192.168.1.100",
|
||||
Port: 8090,
|
||||
})
|
||||
|
||||
// Get device information
|
||||
info, err := c.GetDeviceInfo()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Printf("Device: %s\n", info.Name)
|
||||
|
||||
// Control playback
|
||||
err = c.Play()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Set volume
|
||||
err = c.SetVolume(50)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Device Discovery
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/discovery"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Discover SoundTouch devices
|
||||
service := discovery.NewService(5 * time.Second)
|
||||
devices, err := service.DiscoverDevices(context.Background())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
for _, device := range devices {
|
||||
fmt.Printf("Found: %s at %s:%d\n",
|
||||
device.Name, device.Host, device.Port)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Real-time Events
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/client"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
)
|
||||
|
||||
func main() {
|
||||
c := client.NewClient(&client.Config{
|
||||
Host: "192.168.1.100",
|
||||
Port: 8090,
|
||||
})
|
||||
|
||||
// Subscribe to device events
|
||||
events, err := c.SubscribeToEvents(context.Background())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
for event := range events {
|
||||
switch e := event.(type) {
|
||||
case *models.NowPlayingUpdated:
|
||||
fmt.Printf("Now playing: %s by %s\n", e.Track, e.Artist)
|
||||
case *models.VolumeUpdated:
|
||||
fmt.Printf("Volume changed to: %d\n", e.ActualVolume)
|
||||
case *models.ConnectionStateUpdated:
|
||||
fmt.Printf("Connection state: %s\n", e.State)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Preset Management
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/client"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
)
|
||||
|
||||
func main() {
|
||||
c := client.NewClient(&client.Config{
|
||||
Host: "192.168.1.100",
|
||||
Port: 8090,
|
||||
})
|
||||
|
||||
// Get current presets
|
||||
presets, err := c.GetPresets()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
fmt.Printf("Found %d presets\n", len(presets.Preset))
|
||||
|
||||
// Store currently playing content as preset 1
|
||||
err = c.StoreCurrentAsPreset(1)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Store Spotify playlist as preset 2
|
||||
spotifyContent := &models.ContentItem{
|
||||
Source: "SPOTIFY",
|
||||
Type: "uri",
|
||||
Location: "spotify:playlist:37i9dQZF1DXcBWIGoYBM5M",
|
||||
SourceAccount: "your_username",
|
||||
IsPresetable: true,
|
||||
ItemName: "Today's Top Hits",
|
||||
}
|
||||
err = c.StorePreset(2, spotifyContent)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Store radio station as preset 3
|
||||
radioContent := &models.ContentItem{
|
||||
Source: "TUNEIN",
|
||||
Type: "stationurl",
|
||||
Location: "/v1/playbook/station/s33828",
|
||||
IsPresetable: true,
|
||||
ItemName: "K-LOVE Radio",
|
||||
}
|
||||
err = c.StorePreset(3, radioContent)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Select preset 1
|
||||
err = c.SelectPreset(1)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
fmt.Println("Preset management complete!")
|
||||
}
|
||||
```
|
||||
|
||||
#### Multiroom Zones
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/client"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
)
|
||||
|
||||
func main() {
|
||||
master := client.NewClient(&client.Config{
|
||||
Host: "192.168.1.100", // Master speaker
|
||||
Port: 8090,
|
||||
})
|
||||
|
||||
// Create a multiroom zone
|
||||
zone := &models.Zone{
|
||||
Master: "192.168.1.100",
|
||||
Members: []models.ZoneMember{
|
||||
{IPAddress: "192.168.1.101"}, // Living room
|
||||
{IPAddress: "192.168.1.102"}, // Kitchen
|
||||
},
|
||||
}
|
||||
|
||||
err := master.SetZone(zone)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
fmt.Println("Multiroom zone created!")
|
||||
}
|
||||
```
|
||||
|
||||
#### Speaker Notifications (ST-10 only)
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/client"
|
||||
)
|
||||
|
||||
func main() {
|
||||
c := client.NewClient(&client.Config{
|
||||
Host: "192.168.1.100",
|
||||
Port: 8090,
|
||||
})
|
||||
|
||||
// Play Text-to-Speech message (language code "EN", "DE", etc.)
|
||||
err := c.PlayTTS("Welcome home!", "your-app-key", "EN", 70)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Play audio content from URL
|
||||
err = c.PlayURL(
|
||||
"https://example.com/doorbell.mp3",
|
||||
"your-app-key",
|
||||
"Doorbell",
|
||||
"Front Door",
|
||||
"Visitor Alert",
|
||||
80,
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Play notification beep
|
||||
err = c.PlayNotificationBeep()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
fmt.Println("Notifications sent!")
|
||||
}
|
||||
```
|
||||
|
||||
## Supported Devices
|
||||
|
||||
This library supports all Bose SoundTouch-compatible devices, including:
|
||||
|
||||
- SoundTouch 10, 20, 30 series
|
||||
- SoundTouch Portable
|
||||
- Wave SoundTouch music system
|
||||
- SoundTouch-enabled Bose speakers
|
||||
|
||||
**Tested Hardware**:
|
||||
- ✅ SoundTouch 10
|
||||
- ✅ SoundTouch 20
|
||||
|
||||
## API Coverage
|
||||
|
||||
| Feature | Status | Description |
|
||||
|---------|--------|-------------|
|
||||
| Device Info | ✅ Complete | Device details, name, capabilities |
|
||||
| Media Control | ✅ Complete | Play/pause/stop, track navigation |
|
||||
| Volume & Audio | ✅ Complete | Volume, bass, balance control |
|
||||
| Source Selection | ✅ Complete | Spotify, Bluetooth, AUX, etc. |
|
||||
| Content Navigation | ✅ Complete | Browse music libraries, radio stations |
|
||||
| Station Management | ✅ Complete | Search, add, remove stations |
|
||||
| Preset Management | ✅ Complete | Store, select, remove presets |
|
||||
| Real-time Events | ✅ Complete | WebSocket event streaming |
|
||||
| Multiroom Zones | ✅ Complete | Zone creation and management |
|
||||
| Speaker Notifications | ✅ Complete | TTS, URL audio, beep alerts (ST-10) |
|
||||
| System Settings | ✅ Complete | Clock, display, network info |
|
||||
| Advanced Audio | ✅ Complete | DSP controls, tone controls |
|
||||
|
||||
**API Limitations**: None - all documented SoundTouch Web API functionality is implemented, including endpoints discovered via the comprehensive [SoundTouch Plus Wiki](https://github.com/thlucas1/homeassistantcomponent_soundtouchplus/wiki/SoundTouch-WebServices-API).
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
- 📖 [Contributing Guide](CONTRIBUTING.md) - How to contribute to the project
|
||||
- 📚 [API Reference](https://gesellix.github.io/Bose-SoundTouch/reference/API-ENDPOINTS.html) - Complete endpoint documentation
|
||||
- 🔧 [CLI Reference](https://gesellix.github.io/Bose-SoundTouch/guides/CLI-REFERENCE.html) - Command-line tool guide
|
||||
- 🌐 [SoundTouch Service Guide](https://gesellix.github.io/Bose-SoundTouch/guides/SOUNDTOUCH-SERVICE.html) - Local service setup and migration
|
||||
- 🎯 [Getting Started](https://gesellix.github.io/Bose-SoundTouch/guides/GETTING-STARTED.html) - Detailed setup and usage
|
||||
- 📻 [Preset Quick Start](https://gesellix.github.io/Bose-SoundTouch/PRESET-QUICKSTART.md) - Favorite content management
|
||||
- 🧭 [Navigation Guide](https://gesellix.github.io/Bose-SoundTouch/NAVIGATION-GUIDE.md) - Content browsing and station management
|
||||
- 📋 [Navigation API Reference](https://gesellix.github.io/Bose-SoundTouch/API-NAVIGATION-REFERENCE.md) - Navigation API documentation
|
||||
- ⚙️ [Advanced Features](https://gesellix.github.io/Bose-SoundTouch/reference/SYSTEM-ENDPOINTS.html) - Advanced functionality
|
||||
- 🏠 [Multiroom Setup](https://gesellix.github.io/Bose-SoundTouch/reference/ZONE-MANAGEMENT.html) - Zone configuration guide
|
||||
- ⚡ [WebSocket Events](https://gesellix.github.io/Bose-SoundTouch/reference/WEBSOCKET-EVENTS.html) - Real-time event handling
|
||||
- 🔔 [Speaker Notifications](https://gesellix.github.io/Bose-SoundTouch/reference/SPEAKER-ENDPOINT.html) - TTS and audio notifications guide
|
||||
- 🔍 [Device Discovery](https://gesellix.github.io/Bose-SoundTouch/reference/DISCOVERY.html) - Discovery configuration
|
||||
- 🛠️ [Troubleshooting](https://gesellix.github.io/Bose-SoundTouch/guides/TROUBLESHOOTING.html) - Common issues and solutions
|
||||
- [Getting Started](https://gesellix.github.io/Bose-SoundTouch/guides/GETTING-STARTED.html)
|
||||
- [Survival Guide](https://gesellix.github.io/Bose-SoundTouch/guides/SURVIVAL-GUIDE.html)
|
||||
- [Migration Guide](https://gesellix.github.io/Bose-SoundTouch/guides/MIGRATION-GUIDE.html)
|
||||
- [Device Initial Setup](https://gesellix.github.io/Bose-SoundTouch/guides/DEVICE-INITIAL-SETUP.html)
|
||||
- [Migration & Safety Guide](https://gesellix.github.io/Bose-SoundTouch/guides/MIGRATION-SAFETY.html)
|
||||
- [CLI Reference](https://gesellix.github.io/Bose-SoundTouch/guides/CLI-REFERENCE.html)
|
||||
- [SoundTouch Service Guide](https://gesellix.github.io/Bose-SoundTouch/guides/SOUNDTOUCH-SERVICE.html)
|
||||
- [HTTPS & CA Setup](https://gesellix.github.io/Bose-SoundTouch/guides/HTTPS-SETUP.html)
|
||||
- [API Reference](https://gesellix.github.io/Bose-SoundTouch/reference/API-ENDPOINTS.html)
|
||||
|
||||
## Development
|
||||
---
|
||||
|
||||
### Prerequisites
|
||||
- Go 1.25.6 or later
|
||||
- Optional: SoundTouch device for testing
|
||||
## Related projects
|
||||
|
||||
### Building from Source
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://github.com/gesellix/bose-soundtouch.git
|
||||
cd Bose-SoundTouch
|
||||
- **[SoundCork](https://github.com/deborahgu/soundcork)** (Deborah Kaplan et al.) — Python service interception; pioneered the cloud emulation approach this project builds on
|
||||
- **[SoundCork Stockholm App](https://github.com/krahl/soundcork-stockholm-app)** — Companion app for SoundCork
|
||||
- **[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
|
||||
|
||||
# Install dependencies
|
||||
go mod download
|
||||
|
||||
# Build CLI tool
|
||||
make build
|
||||
|
||||
# Run tests
|
||||
make test
|
||||
|
||||
# Install CLI locally
|
||||
go install ./cmd/soundtouch-cli
|
||||
```
|
||||
|
||||
### Contributing
|
||||
|
||||
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details on:
|
||||
|
||||
- Setting up your development environment
|
||||
- Coding guidelines and best practices
|
||||
- Testing with real devices
|
||||
- Submitting pull requests
|
||||
|
||||
## Examples
|
||||
|
||||
Check out the [examples/](examples/) directory for more usage patterns:
|
||||
|
||||
- **Basic HTTP Client**: Simple device control
|
||||
- **Preset Management**: Store and manage favorite content
|
||||
- **Navigation & Stations**: Browse content and manage radio stations
|
||||
- **WebSocket Events**: Real-time monitoring
|
||||
- **Device Discovery**: Finding devices on your network
|
||||
- **Multiroom Management**: Zone operations
|
||||
- **Advanced Audio**: DSP and tone controls
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
||||
|
||||
## Disclaimer
|
||||
|
||||
This is an independent project based on the official Bose SoundTouch Web API documentation provided by Bose Corporation. It is not affiliated with, endorsed by, or supported by Bose Corporation. Use at your own risk.
|
||||
|
||||
SoundTouch is a trademark of Bose Corporation.
|
||||
|
||||
## SoundTouch End of Life Notice
|
||||
|
||||
**Important:** Bose has announced that [SoundTouch cloud support will end on May 6, 2026](https://www.bose.com/soundtouch-end-of-life).
|
||||
|
||||
**What will continue to work:**
|
||||
- ✅ Local API control (this library's primary functionality)
|
||||
- ✅ Bluetooth, AirPlay, Spotify Connect, and AUX streaming
|
||||
- ✅ Remote control features (Play, Pause, Skip, Volume)
|
||||
- ✅ Multiroom grouping
|
||||
|
||||
**What will stop working:**
|
||||
- ❌ Cloud-based preset sync between devices and SoundTouch app
|
||||
- ❌ Browsing music services directly from the SoundTouch app
|
||||
- ❌ Cloud-based features and updates
|
||||
|
||||
**What continues to work:**
|
||||
- ✅ Local preset management via this API client (store, select, remove)
|
||||
- ✅ Direct content playback (stations, playlists, etc.)
|
||||
|
||||
This Go library will continue to work as it uses the local Web API for direct device control, which is unaffected by the cloud service discontinuation. The local preset management functionality implemented in this library (discovered through the [SoundTouch Plus Wiki](https://github.com/thlucas1/homeassistantcomponent_soundtouchplus/wiki/SoundTouch-WebServices-API)) provides an alternative to the cloud-based preset features that will be discontinued.
|
||||
|
||||
**Community Alternatives**: See the [Related Projects & Credits](#related-projects--credits) section below for additional tools like SoundCork that provide cloud service alternatives and the SoundTouch Plus project that offers comprehensive Home Assistant integration.
|
||||
|
||||
## Related Projects & Credits
|
||||
|
||||
This project builds upon the excellent work of several community projects:
|
||||
|
||||
### SoundCork 🍾
|
||||
- **Project**: [SoundCork - SoundTouch API Intercept](https://github.com/deborahgu/soundcork)
|
||||
- **Authors**: Deborah Kaplan and contributors
|
||||
- **Our Implementation**: The `soundtouch-service` in this project is heavily inspired by SoundCork's Python implementation. SoundCork pioneered the approach of intercepting and emulating Bose's cloud services, providing the foundation for offline SoundTouch operation.
|
||||
- **Key Contributions**: Service emulation architecture, BMX/Marge endpoint discovery, device migration strategies
|
||||
- **License**: MIT License
|
||||
|
||||
### ÜberBöse API 🎵
|
||||
- **Project**: [ÜberBöse API](https://github.com/julius-d/ueberboese-api)
|
||||
- **Author**: Julius
|
||||
- **Our Implementation**: This project provided valuable insights into advanced SoundTouch API endpoints and helped make our implementation more complete, particularly for content navigation and advanced device features.
|
||||
- **Key Contributions**: Extended API endpoint documentation, advanced feature discovery
|
||||
- **License**: MIT License
|
||||
|
||||
### SoundTouch Plus 🏠
|
||||
- **Project**: [SoundTouch Plus Home Assistant Component](https://github.com/thlucas1/homeassistantcomponent_soundtouchplus)
|
||||
- **Wiki**: [SoundTouch WebServices API Documentation](https://github.com/thlucas1/homeassistantcomponent_soundtouchplus/wiki/SoundTouch-WebServices-API)
|
||||
- **Author**: Todd Lucas
|
||||
- **Our Implementation**: The comprehensive API documentation in the SoundTouch Plus Wiki provided invaluable insights into undocumented endpoints beyond the official API, enabling our preset management and content navigation features.
|
||||
- **Key Contributions**: Extensive API endpoint documentation, real-world usage patterns
|
||||
- **License**: MIT License
|
||||
|
||||
### SoundTouch Hook 🪝
|
||||
- **Project**: [Bose SoundTouch Hook](https://github.com/CodeFinder2/bose-soundtouch-hook)
|
||||
- **Author**: Adrian Böckenkamp
|
||||
- **Our Implementation**: This project provides a powerful framework for intercepting and hooking into internal device processes using `LD_PRELOAD`. It was instrumental in verifying internal function calls and understanding how the device validates cloud domains.
|
||||
- **Key Contributions**: Reverse engineering framework, process hooking, cross-compilation toolchain
|
||||
- **License**: GPL-3.0 License
|
||||
|
||||
### Community Ecosystem
|
||||
|
||||
These projects together form a comprehensive ecosystem for SoundTouch device management:
|
||||
|
||||
- **This Project**: Go library + CLI + service for programmatic control and offline operation
|
||||
- **SoundCork**: Python-based service interception and cloud replacement
|
||||
- **SoundTouch Plus**: Home Assistant integration with extensive device support
|
||||
- **ÜberBöse**: API research and advanced endpoint discovery
|
||||
- **SoundTouch Hook**: Advanced reverse engineering and process instrumentation
|
||||
|
||||
We are grateful to these projects and their maintainers for paving the way and providing the foundation that made this comprehensive Go implementation possible. The SoundTouch community's collaborative approach to reverse engineering and documentation has been invaluable.
|
||||
|
||||
### Contributing Back
|
||||
|
||||
If you discover new endpoints, features, or improvements through this library, please consider contributing back to these projects as well. The stronger our community ecosystem becomes, the better we can support SoundTouch devices beyond Bose's official support timeline.
|
||||
---
|
||||
|
||||
## Support
|
||||
|
||||
- 🐛 **Bug Reports**: [Create an issue](https://github.com/gesellix/bose-soundtouch/issues/new)
|
||||
- 💡 **Feature Requests**: [Start a discussion](https://github.com/gesellix/bose-soundtouch/discussions)
|
||||
- ❓ **Questions**: Check [existing discussions](https://github.com/gesellix/bose-soundtouch/discussions)
|
||||
- 📖 **Documentation**: [Online Documentation](https://gesellix.github.io/Bose-SoundTouch/)
|
||||
- 🔍 **New Discoveries**: [Undocumented Community Features](https://gesellix.github.io/Bose-SoundTouch/UNDOCUMENTED-COMMUNITY-FEATURES.md)
|
||||
- 🌐 **Upstream Analysis**: [Upstream URLs & Domains](https://gesellix.github.io/Bose-SoundTouch/analysis/UPSTREAM-URLS.html)
|
||||
- 🔧 **Redirection Guide**: [Device Redirect Methods](https://gesellix.github.io/Bose-SoundTouch/analysis/DEVICE-REDIRECT-METHODS.html)
|
||||
- 🐣 **Initial Setup**: [Device Initial Setup Variants](https://gesellix.github.io/Bose-SoundTouch/guides/DEVICE-INITIAL-SETUP.html)
|
||||
- 📜 **Logging & Debugging**: [Device Logging Guide](https://gesellix.github.io/Bose-SoundTouch/DEVICE-LOGGING.md)
|
||||
- 🔒 **HTTPS & CA Setup**: [HTTPS & Custom CA Guide](https://gesellix.github.io/Bose-SoundTouch/guides/HTTPS-SETUP.html)
|
||||
- Bug reports: [GitHub Issues](https://github.com/gesellix/bose-soundtouch/issues/new)
|
||||
- Questions & discussions: [GitHub Discussions](https://github.com/gesellix/bose-soundtouch/discussions)
|
||||
|
||||
---
|
||||
|
||||
**Star this project** ⭐ if you find it useful!
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
MIT — see [LICENSE](LICENSE).
|
||||
|
||||
SoundTouch is a trademark of Bose Corporation.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// Package main provides a mock Amazon LWA server for testing purposes.
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/testutils/amazon"
|
||||
)
|
||||
|
||||
func main() {
|
||||
port := flag.Int("port", 8080, "Port to listen on")
|
||||
|
||||
flag.Parse()
|
||||
|
||||
log.Printf("Starting mock Amazon LWA server on port %d", *port)
|
||||
|
||||
if err := http.ListenAndServe(fmt.Sprintf(":%d", *port), amazon.NewAmazonHandler()); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
# soundtouch-backup
|
||||
|
||||
A standalone tool for backing up Bose SoundTouch data — both your **cloud account** (presets, devices, sources) and the **local filesystem** of each speaker — before the Bose cloud services shut down on May 6, 2026.
|
||||
|
||||
## Overview
|
||||
|
||||
| Subcommand | What it backs up |
|
||||
|------------|----------------------------------------------------------------------------------------------------|
|
||||
| `all` | Cloud account **and** all paired speakers in one step — the recommended starting point |
|
||||
| `cloud` | Bose account profile, paired devices, cloud presets, music service sources |
|
||||
| `local` | Speaker HTTP API data (presets, sources, volume, …) and optionally device filesystem files via SSH |
|
||||
|
||||
Output is a single `.tar.gz` archive (or `.zip`) with a dated root directory.
|
||||
|
||||
## Building
|
||||
|
||||
```bash
|
||||
make build-backup
|
||||
# binary: ./build/soundtouch-backup
|
||||
```
|
||||
|
||||
Or install alongside the other tools:
|
||||
|
||||
```bash
|
||||
make install
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Combined backup (recommended)
|
||||
|
||||
The `all` command is the simplest way to capture everything: it authenticates with the Bose cloud, backs up your account data, then reads the IP addresses from `devices.xml` and backs up each reachable speaker over HTTP.
|
||||
|
||||
```bash
|
||||
# Interactive — prompts for email and password
|
||||
soundtouch-backup all
|
||||
|
||||
# Non-interactive
|
||||
soundtouch-backup all --email you@example.com --password secret
|
||||
|
||||
# Include SSH filesystem backup for each speaker
|
||||
soundtouch-backup all --ssh
|
||||
|
||||
# Environment variables
|
||||
BOSE_EMAIL=you@example.com BOSE_PASSWORD=secret soundtouch-backup all --ssh
|
||||
```
|
||||
|
||||
**Flags**
|
||||
|
||||
| Flag | Short | Default | Description |
|
||||
|--------------|--------|---------------------------------------|--------------------------------------------------------|
|
||||
| `--email` | `-e` | — | Bose account email (`$BOSE_EMAIL`) |
|
||||
| `--password` | `--pw` | — | Bose account password (`$BOSE_PASSWORD`) |
|
||||
| `--ssh` | | on | Also capture filesystem files via SSH for each speaker |
|
||||
| `--output` | `-o` | `soundtouch-backup-YYYY-MM-DD.tar.gz` | Output archive path |
|
||||
| `--format` | | `tar.gz` | Archive format: `tar.gz` or `zip` |
|
||||
|
||||
Speakers that are offline or unreachable at the time of backup are skipped with a `✗` warning; the cloud data is still saved.
|
||||
|
||||
---
|
||||
|
||||
### Cloud backup
|
||||
|
||||
Backs up data from your Bose account at `streaming.bose.com`. Credentials are prompted interactively if not supplied as flags.
|
||||
|
||||
```bash
|
||||
# Interactive — prompts for email, masked password input
|
||||
soundtouch-backup cloud
|
||||
|
||||
# Non-interactive
|
||||
soundtouch-backup cloud --email you@example.com --password secret
|
||||
|
||||
# Environment variables (avoids secrets in shell history)
|
||||
BOSE_EMAIL=you@example.com BOSE_PASSWORD=secret soundtouch-backup cloud
|
||||
|
||||
# Zip output
|
||||
soundtouch-backup cloud --format zip --output my-bose-cloud.zip
|
||||
```
|
||||
|
||||
**Flags**
|
||||
|
||||
| Flag | Short | Default | Description |
|
||||
|--------------|--------|---------------------------------------|---------------------------------------------------|
|
||||
| `--email` | `-e` | — | Bose account email (`$BOSE_EMAIL`) |
|
||||
| `--password` | `--pw` | — | Bose account password (`$BOSE_PASSWORD`) |
|
||||
| `--output` | `-o` | `soundtouch-backup-YYYY-MM-DD.tar.gz` | Output archive path (`$SOUNDTOUCH_BACKUP_OUTPUT`) |
|
||||
| `--format` | | `tar.gz` | Archive format: `tar.gz` or `zip` |
|
||||
|
||||
**What gets fetched**
|
||||
|
||||
| File in archive | Source endpoint |
|
||||
|--------------------------|---------------------------------------------------------------------------------|
|
||||
| `cloud/emailaddress.xml` | `GET /streaming/account/{id}/emailaddress` |
|
||||
| `cloud/devices.xml` | `GET /streaming/account/{id}/devices` |
|
||||
| `cloud/sources.xml` | `GET /streaming/account/{id}/sources` |
|
||||
| `cloud/presets.xml` | `GET /streaming/account/{id}/presets/all` |
|
||||
| `cloud/full.xml` | `GET /streaming/account/{id}/full` (may overlap with the above; skipped if 4xx) |
|
||||
|
||||
---
|
||||
|
||||
### Local backup
|
||||
|
||||
Backs up each speaker over its HTTP API on port 8090. With `--ssh`, also captures key filesystem files via SSH.
|
||||
|
||||
```bash
|
||||
# Auto-discover all speakers on the local network
|
||||
soundtouch-backup local
|
||||
|
||||
# Specific speaker
|
||||
soundtouch-backup local --host 192.168.178.28
|
||||
|
||||
# Multiple speakers
|
||||
soundtouch-backup local --host 192.168.178.28 --host 192.168.178.35
|
||||
|
||||
# Include SSH filesystem backup
|
||||
soundtouch-backup local --ssh
|
||||
|
||||
# Longer discovery window on busy networks
|
||||
soundtouch-backup local --discover-timeout 10s
|
||||
```
|
||||
|
||||
**Flags**
|
||||
|
||||
| Flag | Short | Default | Description |
|
||||
|----------------------|-------|---------------------------------------|--------------------------------------------------|
|
||||
| `--host` | `-H` | — | Speaker host/IP, repeatable (`$SOUNDTOUCH_HOST`) |
|
||||
| `--port` | `-p` | `8090` | Speaker HTTP port (`$SOUNDTOUCH_PORT`) |
|
||||
| `--discover` | `-d` | auto | Force mDNS/UPnP discovery |
|
||||
| `--discover-timeout` | | `5s` | Discovery timeout |
|
||||
| `--ssh` | | on | Also capture filesystem files via SSH |
|
||||
| `--output` | `-o` | `soundtouch-backup-YYYY-MM-DD.tar.gz` | Output archive path |
|
||||
| `--format` | | `tar.gz` | Archive format: `tar.gz` or `zip` |
|
||||
|
||||
**What gets fetched via HTTP**
|
||||
|
||||
| File | Device endpoint |
|
||||
|---------------------|-----------------|
|
||||
| `info.xml` | `/info` |
|
||||
| `name.xml` | `/name` |
|
||||
| `presets.xml` | `/presets` |
|
||||
| `sources.xml` | `/sources` |
|
||||
| `now_playing.xml` | `/now_playing` |
|
||||
| `volume.xml` | `/volume` |
|
||||
| `bass.xml` | `/bass` |
|
||||
| `balance.xml` | `/balance` |
|
||||
| `capabilities.xml` | `/capabilities` |
|
||||
| `network_info.xml` | `/networkInfo` |
|
||||
| `clock_display.xml` | `/clockDisplay` |
|
||||
| `zone.xml` | `/getZone` |
|
||||
|
||||
Endpoints that return HTTP 4xx (not supported on the device model) are silently skipped.
|
||||
|
||||
**What gets fetched via SSH** (`--ssh`)
|
||||
|
||||
SSH connects as `root@<host>:22` with an empty password, which is the default for SoundTouch firmware.
|
||||
|
||||
Individual files:
|
||||
|
||||
| Remote path | Notes |
|
||||
|---------------------------|--------------------------------------------|
|
||||
| `/etc/hosts` | DNS redirect state |
|
||||
| `/etc/resolv.conf` | DNS resolver configuration |
|
||||
| `/etc/remote_services` | Service registration (post-migration only) |
|
||||
| `/mnt/nv/remote_services` | Alternative location for remote services |
|
||||
|
||||
Directories (all regular files recursively):
|
||||
|
||||
| Remote path | Contents |
|
||||
|----------------------------------|----------------------------------------------------------------------------|
|
||||
| `/opt/Bose/etc/` | Full Bose configuration directory, including `SoundTouchSdkPrivateCfg.xml` |
|
||||
| `/mnt/nv/BoseApp-Persistence/1/` | Persisted app state |
|
||||
|
||||
Missing files and directories are silently skipped with a `⚠` warning.
|
||||
|
||||
---
|
||||
|
||||
## Archive structure
|
||||
|
||||
Both subcommands write into a single dated archive:
|
||||
|
||||
```
|
||||
soundtouch-backup-2026-05-02/
|
||||
├── cloud/
|
||||
│ ├── emailaddress.xml
|
||||
│ ├── devices.xml
|
||||
│ ├── sources.xml
|
||||
│ └── presets.xml
|
||||
└── local/
|
||||
├── A_Sound_Machine/
|
||||
│ ├── info.xml
|
||||
│ ├── presets.xml
|
||||
│ ├── sources.xml
|
||||
│ ├── volume.xml
|
||||
│ ├── …
|
||||
│ └── ssh/
|
||||
│ ├── etc/
|
||||
│ │ ├── hosts
|
||||
│ │ └── resolv.conf
|
||||
│ ├── opt/Bose/etc/
|
||||
│ │ └── SoundTouchSdkPrivateCfg.xml
|
||||
│ └── mnt/nv/BoseApp-Persistence/1/
|
||||
└── Sound_Machinechen/
|
||||
└── …
|
||||
```
|
||||
|
||||
Running `cloud` and `local` separately produces two archives. To combine them, use the same `--output` path for both invocations — each adds its own subdirectory so they won't collide (`.tar.gz` does not support appending; use `--format zip` if you need a single archive from two runs, or just keep them separate).
|
||||
|
||||
## See also
|
||||
|
||||
- [Cloud Shutdown Survival Guide](../../docs/guides/SURVIVAL-GUIDE.md) — full migration context
|
||||
- [`soundtouch-cli`](../soundtouch-cli/) — live device control
|
||||
- [`soundtouch-service`](../soundtouch-service/) — local cloud replacement
|
||||
@@ -0,0 +1,119 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
func allCommand() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "all",
|
||||
Usage: "Back up cloud account then all paired speakers in one go",
|
||||
Description: "Authenticates with the Bose cloud, backs up account data, then reads" +
|
||||
" the device IP addresses from the cloud device list and backs up each reachable" +
|
||||
" speaker over HTTP (and optionally SSH).",
|
||||
Flags: append(outputFlags,
|
||||
&cli.StringFlag{
|
||||
Name: "email",
|
||||
Aliases: []string{"e"},
|
||||
Usage: "Bose account email",
|
||||
EnvVars: []string{"BOSE_EMAIL"},
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "password",
|
||||
Aliases: []string{"pw"},
|
||||
Usage: "Bose account password",
|
||||
EnvVars: []string{"BOSE_PASSWORD"},
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "ssh",
|
||||
Usage: "Also back up device filesystem files via SSH (root@host:22, no password required)",
|
||||
Value: true,
|
||||
},
|
||||
),
|
||||
Action: runAllBackup,
|
||||
}
|
||||
}
|
||||
|
||||
func runAllBackup(c *cli.Context) error {
|
||||
doSSH := c.Bool("ssh")
|
||||
output := resolveOutputPath(c.String("output"), c.String("format"))
|
||||
format := c.String("format")
|
||||
|
||||
// 1. Cloud backup
|
||||
client, err := setupCloudClient(c.String("email"), c.String("password"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
root := archiveRoot()
|
||||
files := collectCloudFiles(client, root)
|
||||
|
||||
if len(files) == 0 {
|
||||
return fmt.Errorf("no cloud data fetched")
|
||||
}
|
||||
|
||||
// 2. Resolve speakers from devices.xml, then back each one up
|
||||
devicesData := files[root+"/cloud/devices.xml"]
|
||||
if devicesData == nil {
|
||||
printWarn("devices.xml not available — skipping local backup")
|
||||
} else {
|
||||
targets := parseDevicesXML(devicesData)
|
||||
if len(targets) == 0 {
|
||||
printWarn("no device IP addresses found in devices.xml")
|
||||
} else {
|
||||
fmt.Printf("Found %d device(s) in cloud account, attempting local backup...\n", len(targets))
|
||||
}
|
||||
|
||||
hc := &http.Client{Timeout: 10 * time.Second}
|
||||
|
||||
for k, v := range collectLocalFiles(hc, targets, root, doSSH) {
|
||||
files[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
if err := writeArchive(output, format, files); err != nil {
|
||||
return fmt.Errorf("writing archive: %w", err)
|
||||
}
|
||||
|
||||
fmt.Printf("Archive written: %s (%d files)\n", output, len(files))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type xmlDevice struct {
|
||||
Name string `xml:"name"`
|
||||
IPAddress string `xml:"ipaddress"`
|
||||
}
|
||||
|
||||
type xmlDevices struct {
|
||||
XMLName xml.Name `xml:"devices"`
|
||||
Devices []xmlDevice `xml:"device"`
|
||||
}
|
||||
|
||||
// parseDevicesXML extracts speaker targets from a devices.xml cloud response.
|
||||
func parseDevicesXML(data []byte) []speakerTarget {
|
||||
var d xmlDevices
|
||||
|
||||
if err := xml.Unmarshal(data, &d); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var targets []speakerTarget
|
||||
|
||||
for _, dev := range d.Devices {
|
||||
if dev.IPAddress == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
// Pass name as a hint for error messages; backupSpeakerHTTP re-fetches
|
||||
// from /info to get the current name and include info.xml in the archive.
|
||||
targets = append(targets, speakerTarget{host: dev.IPAddress, port: 8090, name: dev.Name})
|
||||
}
|
||||
|
||||
return targets
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
const (
|
||||
streamingBase = "https://streaming.bose.com"
|
||||
streamingCT = "application/vnd.bose.streaming-v1.1+xml"
|
||||
stockholmVer = "27.0.13-4277+8963611.epdbuild.develop.hepdswbld04.2025-10-02T13:17:00"
|
||||
nativeFrameVer = "27.0.2 -3353+4ae7c78.epdbuild.HEAD.ssgbld02.2023-10-12T15:10Z"
|
||||
protocolVer = "67"
|
||||
appGUID = "b94dedd1-a61b-492b-b86b-2bc32c9261f4"
|
||||
appUserAgent = "Mozilla/5.0 (Linux; Android 13; Android SDK built for arm64 Build/TE1A.220922.034; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/101.0.4951.61 Mobile Safari/537.36 Manufacturer/unknown DeviceModel/Android-SDK-built-for-arm64 SOUNDTOUCH_MOBILE_APP/" + appGUID
|
||||
)
|
||||
|
||||
func cloudCommand() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "cloud",
|
||||
Usage: "Back up your Bose SoundTouch cloud account (devices, presets, sources)",
|
||||
Flags: append(outputFlags,
|
||||
&cli.StringFlag{
|
||||
Name: "email",
|
||||
Aliases: []string{"e"},
|
||||
Usage: "Bose account email",
|
||||
EnvVars: []string{"BOSE_EMAIL"},
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "password",
|
||||
Aliases: []string{"pw"},
|
||||
Usage: "Bose account password",
|
||||
EnvVars: []string{"BOSE_PASSWORD"},
|
||||
},
|
||||
),
|
||||
Action: runCloudBackup,
|
||||
}
|
||||
}
|
||||
|
||||
func runCloudBackup(c *cli.Context) error {
|
||||
output := resolveOutputPath(c.String("output"), c.String("format"))
|
||||
format := c.String("format")
|
||||
|
||||
client, err := setupCloudClient(c.String("email"), c.String("password"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
root := archiveRoot()
|
||||
files := collectCloudFiles(client, root)
|
||||
|
||||
if len(files) == 0 {
|
||||
return fmt.Errorf("no data fetched")
|
||||
}
|
||||
|
||||
if err := writeArchive(output, format, files); err != nil {
|
||||
return fmt.Errorf("writing archive: %w", err)
|
||||
}
|
||||
|
||||
fmt.Printf("Archive written: %s (%d files)\n", output, len(files))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// setupCloudClient prompts for missing credentials, then authenticates with the Bose cloud.
|
||||
func setupCloudClient(email, password string) (*cloudClient, error) {
|
||||
if email == "" || password == "" {
|
||||
var err error
|
||||
|
||||
email, password, err = promptCredentials(email)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("credentials: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if email == "" || password == "" {
|
||||
return nil, fmt.Errorf("email and password are required")
|
||||
}
|
||||
|
||||
fmt.Printf("Authenticating as %s...\n", email)
|
||||
|
||||
client, err := loginToCloud(email, password)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("authentication failed: %w", err)
|
||||
}
|
||||
|
||||
printOK(fmt.Sprintf("Authenticated (account ID: %s)", client.accountID))
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// collectCloudFiles fetches all cloud account data and returns a files map ready for
|
||||
// archiving. Keys are prefixed with root (e.g. "soundtouch-backup-2026-05-02/cloud/").
|
||||
func collectCloudFiles(client *cloudClient, root string) map[string][]byte {
|
||||
type cloudEndpoint struct {
|
||||
label string
|
||||
filename string
|
||||
fetch func(*cloudClient) ([]byte, error)
|
||||
}
|
||||
|
||||
endpoints := []cloudEndpoint{
|
||||
{"email address", "emailaddress.xml", fetchEmailAddress},
|
||||
{"devices", "devices.xml", fetchDevices},
|
||||
{"sources", "sources.xml", fetchSources},
|
||||
{"presets", "presets.xml", fetchPresets},
|
||||
{"full account", "full.xml", fetchFull},
|
||||
}
|
||||
|
||||
files := make(map[string][]byte)
|
||||
|
||||
for _, ep := range endpoints {
|
||||
data, err := ep.fetch(client)
|
||||
if err != nil {
|
||||
printFail(fmt.Sprintf("%s: %v", ep.label, err))
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
files[root+"/cloud/"+ep.filename] = data
|
||||
printOK(fmt.Sprintf("%s (%d bytes)", ep.label, len(data)))
|
||||
}
|
||||
|
||||
return files
|
||||
}
|
||||
|
||||
type cloudClient struct {
|
||||
http *http.Client
|
||||
accountID string
|
||||
token string
|
||||
}
|
||||
|
||||
type loginXML struct {
|
||||
XMLName xml.Name `xml:"login"`
|
||||
Username string `xml:"username"`
|
||||
Password string `xml:"password"`
|
||||
}
|
||||
|
||||
var accountIDRe = regexp.MustCompile(`<account\s+id="([^"]+)"`)
|
||||
|
||||
func loginToCloud(email, password string) (*cloudClient, error) {
|
||||
loginBody, err := xml.Marshal(loginXML{Username: email, Password: password})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
body := []byte(`<?xml version="1.0" encoding="UTF-8"?>`)
|
||||
body = append(body, loginBody...)
|
||||
|
||||
req, err := http.NewRequest("POST", streamingBase+"/streaming/account/login", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
setStreamingHeaders(req, "")
|
||||
|
||||
hc := &http.Client{Timeout: 30 * time.Second}
|
||||
|
||||
resp, err := hc.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
token := resp.Header.Get("credentials")
|
||||
if token == "" {
|
||||
return nil, fmt.Errorf("no credentials in response — check your email and password")
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
m := accountIDRe.FindSubmatch(data)
|
||||
if len(m) < 2 {
|
||||
return nil, fmt.Errorf("could not extract account ID from login response")
|
||||
}
|
||||
|
||||
return &cloudClient{http: hc, accountID: string(m[1]), token: token}, nil
|
||||
}
|
||||
|
||||
func setStreamingHeaders(req *http.Request, token string) {
|
||||
req.Header.Set("content-type", streamingCT)
|
||||
req.Header.Set("accept", streamingCT)
|
||||
req.Header.Set("clienttype", "SOUNDTOUCH_MOBILE_APP")
|
||||
req.Header.Set("version_stockholmversion", stockholmVer)
|
||||
req.Header.Set("version_nativeframeversion", nativeFrameVer)
|
||||
req.Header.Set("version_protocolversion", protocolVer)
|
||||
req.Header.Set("user-agent", appUserAgent)
|
||||
req.Header.Set("guid", appGUID)
|
||||
req.Header.Set("x-requested-with", "com.bose.soundtouch")
|
||||
req.Header.Set("pragma", "no-cache")
|
||||
req.Header.Set("cache-control", "no-cache")
|
||||
|
||||
if token != "" {
|
||||
req.Header.Set("authorization", token)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *cloudClient) get(path string) ([]byte, error) {
|
||||
url := fmt.Sprintf("%s%s?_=%d", streamingBase, path, time.Now().UnixMilli())
|
||||
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
setStreamingHeaders(req, c.token)
|
||||
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
return io.ReadAll(io.LimitReader(resp.Body, 2*1024*1024))
|
||||
}
|
||||
|
||||
func fetchEmailAddress(c *cloudClient) ([]byte, error) {
|
||||
return c.get("/streaming/account/" + c.accountID + "/emailaddress")
|
||||
}
|
||||
|
||||
func fetchDevices(c *cloudClient) ([]byte, error) {
|
||||
return c.get("/streaming/account/" + c.accountID + "/devices")
|
||||
}
|
||||
|
||||
func fetchSources(c *cloudClient) ([]byte, error) {
|
||||
return c.get("/streaming/account/" + c.accountID + "/sources")
|
||||
}
|
||||
|
||||
func fetchPresets(c *cloudClient) ([]byte, error) {
|
||||
return c.get("/streaming/account/" + c.accountID + "/presets/all")
|
||||
}
|
||||
|
||||
func fetchFull(c *cloudClient) ([]byte, error) {
|
||||
return c.get("/streaming/account/" + c.accountID + "/full")
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/config"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/discovery"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/ssh"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
var localEndpoints = []struct {
|
||||
path string
|
||||
file string
|
||||
}{
|
||||
{"/info", "info.xml"},
|
||||
{"/name", "name.xml"},
|
||||
{"/presets", "presets.xml"},
|
||||
{"/sources", "sources.xml"},
|
||||
{"/now_playing", "now_playing.xml"},
|
||||
{"/volume", "volume.xml"},
|
||||
{"/bass", "bass.xml"},
|
||||
{"/balance", "balance.xml"},
|
||||
{"/capabilities", "capabilities.xml"},
|
||||
{"/networkInfo", "network_info.xml"},
|
||||
{"/clockDisplay", "clock_display.xml"},
|
||||
{"/getZone", "zone.xml"},
|
||||
}
|
||||
|
||||
// sshFiles lists individual device filesystem paths captured via SSH.
|
||||
// Paths that may not exist on all devices are silently skipped.
|
||||
var sshFiles = []string{
|
||||
"/etc/hosts",
|
||||
"/etc/resolv.conf",
|
||||
"/etc/remote_services",
|
||||
"/mnt/nv/remote_services",
|
||||
}
|
||||
|
||||
// sshDirs lists device directories whose contents are recursively captured via SSH.
|
||||
var sshDirs = []string{
|
||||
"/opt/Bose/etc",
|
||||
"/mnt/nv/BoseApp-Persistence/1",
|
||||
}
|
||||
|
||||
func localCommand() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "local",
|
||||
Usage: "Back up one or more SoundTouch speakers on your local network",
|
||||
Flags: append(outputFlags,
|
||||
&cli.StringSliceFlag{
|
||||
Name: "host",
|
||||
Aliases: []string{"H"},
|
||||
Usage: "Speaker host/IP (repeatable for multiple speakers)",
|
||||
EnvVars: []string{"SOUNDTOUCH_HOST"},
|
||||
},
|
||||
&cli.IntFlag{
|
||||
Name: "port",
|
||||
Aliases: []string{"p"},
|
||||
Usage: "Speaker HTTP port",
|
||||
Value: 8090,
|
||||
EnvVars: []string{"SOUNDTOUCH_PORT"},
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "discover",
|
||||
Aliases: []string{"d"},
|
||||
Usage: "Auto-discover speakers on the local network",
|
||||
},
|
||||
&cli.DurationFlag{
|
||||
Name: "discover-timeout",
|
||||
Usage: "Discovery timeout",
|
||||
Value: 5 * time.Second,
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "ssh",
|
||||
Usage: "Also back up device filesystem files via SSH (root@host:22, no password required)",
|
||||
Value: true,
|
||||
},
|
||||
),
|
||||
Action: runLocalBackup,
|
||||
}
|
||||
}
|
||||
|
||||
type speakerTarget struct {
|
||||
host string
|
||||
port int
|
||||
name string
|
||||
}
|
||||
|
||||
func runLocalBackup(c *cli.Context) error {
|
||||
hosts := c.StringSlice("host")
|
||||
port := c.Int("port")
|
||||
doDiscover := c.Bool("discover") || len(hosts) == 0
|
||||
discoverTimeout := c.Duration("discover-timeout")
|
||||
doSSH := c.Bool("ssh")
|
||||
output := resolveOutputPath(c.String("output"), c.String("format"))
|
||||
format := c.String("format")
|
||||
|
||||
var targets []speakerTarget
|
||||
|
||||
if doDiscover {
|
||||
fmt.Printf("Discovering speakers (timeout: %s)...\n", discoverTimeout)
|
||||
|
||||
ctx, cancel := context.WithTimeout(c.Context, discoverTimeout)
|
||||
defer cancel()
|
||||
|
||||
cfg, _ := config.LoadFromEnv()
|
||||
svc := discovery.NewUnifiedDiscoveryService(cfg)
|
||||
|
||||
found, discErr := svc.DiscoverDevices(ctx)
|
||||
if discErr != nil {
|
||||
printWarn(fmt.Sprintf("Discovery failed: %v", discErr))
|
||||
}
|
||||
|
||||
for _, d := range found {
|
||||
targets = append(targets, speakerTarget{host: d.Host, port: d.Port, name: d.Name})
|
||||
printOK(fmt.Sprintf("Found: %s (%s:%d)", d.Name, d.Host, d.Port))
|
||||
}
|
||||
}
|
||||
|
||||
for _, h := range hosts {
|
||||
targets = append(targets, speakerTarget{host: h, port: port})
|
||||
}
|
||||
|
||||
if len(targets) == 0 {
|
||||
return fmt.Errorf("no speakers found — use --host <ip> or --discover")
|
||||
}
|
||||
|
||||
hc := &http.Client{Timeout: 10 * time.Second}
|
||||
root := archiveRoot()
|
||||
files := collectLocalFiles(hc, targets, root, doSSH)
|
||||
|
||||
if len(files) == 0 {
|
||||
return fmt.Errorf("no data collected")
|
||||
}
|
||||
|
||||
if err := writeArchive(output, format, files); err != nil {
|
||||
return fmt.Errorf("writing archive: %w", err)
|
||||
}
|
||||
|
||||
fmt.Printf("Archive written: %s (%d files)\n", output, len(files))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// collectLocalFiles backs up all targets over HTTP (and optionally SSH) and returns
|
||||
// a files map ready for archiving. Keys are prefixed with root.
|
||||
func collectLocalFiles(hc *http.Client, targets []speakerTarget, root string, doSSH bool) map[string][]byte {
|
||||
files := make(map[string][]byte)
|
||||
|
||||
for _, t := range targets {
|
||||
name, entries, err := backupSpeakerHTTP(hc, t)
|
||||
if err != nil {
|
||||
printFail(fmt.Sprintf("%s:%d — %v", t.host, t.port, err))
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
dir := root + "/local/" + sanitizeName(name) + "/"
|
||||
|
||||
for filename, data := range entries {
|
||||
files[dir+filename] = data
|
||||
}
|
||||
|
||||
printOK(fmt.Sprintf("%s: %d files via HTTP", name, len(entries)))
|
||||
|
||||
if doSSH {
|
||||
sshEntries := backupSpeakerSSH(t.host, name)
|
||||
|
||||
for filename, data := range sshEntries {
|
||||
files[dir+filename] = data
|
||||
}
|
||||
|
||||
if len(sshEntries) > 0 {
|
||||
printOK(fmt.Sprintf("%s: %d files via SSH", name, len(sshEntries)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return files
|
||||
}
|
||||
|
||||
func backupSpeakerHTTP(hc *http.Client, t speakerTarget) (name string, files map[string][]byte, err error) {
|
||||
base := fmt.Sprintf("http://%s:%d", t.host, t.port)
|
||||
files = make(map[string][]byte)
|
||||
name = t.name
|
||||
infoFetched := false
|
||||
|
||||
if name == "" {
|
||||
data, ferr := fetchRaw(hc, base+"/info")
|
||||
if ferr != nil {
|
||||
return "", nil, fmt.Errorf("cannot reach %s: %w", base, ferr)
|
||||
}
|
||||
|
||||
files["info.xml"] = data
|
||||
infoFetched = true
|
||||
|
||||
if extracted := xmlFirst(data, "name"); extracted != "" {
|
||||
name = extracted
|
||||
} else {
|
||||
name = t.host
|
||||
}
|
||||
}
|
||||
|
||||
for _, ep := range localEndpoints {
|
||||
if ep.path == "/info" && infoFetched {
|
||||
continue
|
||||
}
|
||||
|
||||
data, ferr := fetchRaw(hc, base+ep.path)
|
||||
if ferr != nil {
|
||||
printWarn(fmt.Sprintf("%s: skipped %s (%v)", name, ep.file, ferr))
|
||||
continue
|
||||
}
|
||||
|
||||
files[ep.file] = data
|
||||
}
|
||||
|
||||
return name, files, nil
|
||||
}
|
||||
|
||||
// backupSpeakerSSH connects to the device via SSH and reads the key filesystem paths.
|
||||
// Files that don't exist on the device are silently skipped.
|
||||
// Returned map keys are relative paths within the device backup directory (e.g. "ssh/etc/hosts").
|
||||
func backupSpeakerSSH(host, deviceName string) map[string][]byte {
|
||||
client := ssh.NewClient(host)
|
||||
files := make(map[string][]byte)
|
||||
|
||||
for _, remotePath := range sshFiles {
|
||||
data, err := client.ReadFile(remotePath)
|
||||
if err != nil {
|
||||
// Most missing files are expected (e.g. /etc/remote_services only exists post-migration)
|
||||
printWarn(fmt.Sprintf("%s: SSH skipped %s (%v)", deviceName, remotePath, err))
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) == 0 {
|
||||
printWarn(fmt.Sprintf("%s: SSH empty file %s", deviceName, remotePath))
|
||||
}
|
||||
|
||||
files["ssh"+remotePath] = data
|
||||
}
|
||||
|
||||
for _, remoteDir := range sshDirs {
|
||||
dirFiles, err := client.ReadDir(remoteDir)
|
||||
if err != nil {
|
||||
printWarn(fmt.Sprintf("%s: SSH skipped dir %s (%v)", deviceName, remoteDir, err))
|
||||
continue
|
||||
}
|
||||
|
||||
for path, data := range dirFiles {
|
||||
files["ssh"+path] = data
|
||||
}
|
||||
}
|
||||
|
||||
return files
|
||||
}
|
||||
|
||||
func fetchRaw(hc *http.Client, url string) ([]byte, error) {
|
||||
resp, err := hc.Get(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 400 {
|
||||
return nil, fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
return io.ReadAll(io.LimitReader(resp.Body, 1024*1024))
|
||||
}
|
||||
|
||||
func xmlFirst(data []byte, field string) string {
|
||||
re := regexp.MustCompile(`<` + regexp.QuoteMeta(field) + `[^>]*>([^<]+)</` + regexp.QuoteMeta(field) + `>`)
|
||||
|
||||
m := re.FindSubmatch(data)
|
||||
if len(m) >= 2 {
|
||||
return strings.TrimSpace(string(m[1]))
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"archive/zip"
|
||||
"bufio"
|
||||
"compress/gzip"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/urfave/cli/v2"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
const (
|
||||
FormatTarGz = "tar.gz"
|
||||
FormatZip = "zip"
|
||||
)
|
||||
|
||||
var outputFlags = []cli.Flag{
|
||||
&cli.StringFlag{
|
||||
Name: "output",
|
||||
Aliases: []string{"o"},
|
||||
Usage: "Output archive file (default: soundtouch-backup-YYYY-MM-DD.tar.gz)",
|
||||
EnvVars: []string{"SOUNDTOUCH_BACKUP_OUTPUT"},
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "format",
|
||||
Usage: "Archive format: tar.gz or zip",
|
||||
Value: FormatTarGz,
|
||||
},
|
||||
}
|
||||
|
||||
func resolveOutputPath(output, format string) string {
|
||||
date := time.Now().Format("2006-01-02")
|
||||
|
||||
ext := ".tar.gz"
|
||||
if format == FormatZip {
|
||||
ext = ".zip"
|
||||
}
|
||||
|
||||
filename := "soundtouch-backup-" + date + ext
|
||||
|
||||
if output == "" {
|
||||
return filename
|
||||
}
|
||||
|
||||
if info, err := os.Stat(output); err == nil && info.IsDir() {
|
||||
return output + string(os.PathSeparator) + filename
|
||||
}
|
||||
|
||||
return output
|
||||
}
|
||||
|
||||
func archiveRoot() string {
|
||||
return "soundtouch-backup-" + time.Now().Format("2006-01-02")
|
||||
}
|
||||
|
||||
func writeArchive(outputPath, format string, files map[string][]byte) error {
|
||||
if format == FormatZip {
|
||||
return writeZip(outputPath, files)
|
||||
}
|
||||
|
||||
return writeTarGz(outputPath, files)
|
||||
}
|
||||
|
||||
func writeTarGz(outputPath string, files map[string][]byte) error {
|
||||
f, err := os.Create(outputPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
gz := gzip.NewWriter(f)
|
||||
defer gz.Close()
|
||||
|
||||
tw := tar.NewWriter(gz)
|
||||
defer tw.Close()
|
||||
|
||||
now := time.Now()
|
||||
for name, data := range files {
|
||||
hdr := &tar.Header{
|
||||
Name: name,
|
||||
Mode: 0644,
|
||||
Size: int64(len(data)),
|
||||
ModTime: now,
|
||||
Typeflag: tar.TypeReg,
|
||||
}
|
||||
if err := tw.WriteHeader(hdr); err != nil {
|
||||
return fmt.Errorf("tar header %s: %w", name, err)
|
||||
}
|
||||
|
||||
if _, err := tw.Write(data); err != nil {
|
||||
return fmt.Errorf("tar write %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeZip(outputPath string, files map[string][]byte) error {
|
||||
f, err := os.Create(outputPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
zw := zip.NewWriter(f)
|
||||
defer zw.Close()
|
||||
|
||||
for name, data := range files {
|
||||
w, err := zw.Create(name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("zip entry %s: %w", name, err)
|
||||
}
|
||||
|
||||
if _, err := w.Write(data); err != nil {
|
||||
return fmt.Errorf("zip write %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func promptCredentials(emailHint string) (email, password string, err error) {
|
||||
r := bufio.NewReader(os.Stdin)
|
||||
|
||||
if emailHint != "" {
|
||||
email = emailHint
|
||||
} else {
|
||||
fmt.Print("Bose account email: ")
|
||||
|
||||
email, err = r.ReadString('\n')
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
email = strings.TrimSpace(email)
|
||||
}
|
||||
|
||||
fmt.Print("Password: ")
|
||||
|
||||
raw, termErr := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
|
||||
fmt.Println()
|
||||
|
||||
if termErr != nil {
|
||||
err = fmt.Errorf("reading password: %w (tip: use --password flag or BOSE_PASSWORD env var)", termErr)
|
||||
return
|
||||
}
|
||||
|
||||
password = string(raw)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func sanitizeName(name string) string {
|
||||
r := strings.NewReplacer(
|
||||
"/", "_", "\\", "_", ":", "_",
|
||||
"*", "_", "?", "_", "\"", "_",
|
||||
"<", "_", ">", "_", "|", "_",
|
||||
" ", "_",
|
||||
)
|
||||
|
||||
return r.Replace(name)
|
||||
}
|
||||
|
||||
func printOK(msg string) { fmt.Printf(" ✓ %s\n", msg) }
|
||||
func printFail(msg string) { fmt.Printf(" ✗ %s\n", msg) }
|
||||
func printWarn(msg string) { fmt.Printf(" ⚠ %s\n", msg) }
|
||||
@@ -0,0 +1,37 @@
|
||||
// Package main implements the soundtouch-backup tool for backing up Bose SoundTouch
|
||||
// cloud account data and local speaker filesystem files.
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
var version = "dev"
|
||||
|
||||
func init() {
|
||||
if info, ok := debug.ReadBuildInfo(); ok {
|
||||
if info.Main.Version != "" && info.Main.Version != "(devel)" {
|
||||
version = info.Main.Version
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
app := &cli.App{
|
||||
Name: "soundtouch-backup",
|
||||
Usage: "Back up Bose SoundTouch account and speaker data",
|
||||
Version: version,
|
||||
Commands: []*cli.Command{
|
||||
allCommand(),
|
||||
cloudCommand(),
|
||||
localCommand(),
|
||||
},
|
||||
}
|
||||
if err := app.Run(os.Args); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/discovery"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/amazon"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/certmanager"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/handlers"
|
||||
@@ -119,6 +120,58 @@ func initializeDefaultSources(ds *datastore.DataStore) {
|
||||
}
|
||||
}
|
||||
|
||||
func initMusicServices(config serviceConfig, server *handlers.Server) {
|
||||
if config.spotifyClientID != "" {
|
||||
spotifyService := spotify.NewSpotifyService(
|
||||
config.spotifyClientID,
|
||||
config.spotifyClientSecret,
|
||||
config.spotifyRedirectURI,
|
||||
config.dataDir,
|
||||
)
|
||||
if config.spotifyTokenURL != "" || config.spotifyAPIBase != "" {
|
||||
spotifyService.SetEndpoints(config.spotifyTokenURL, config.spotifyAPIBase)
|
||||
}
|
||||
|
||||
if err := spotifyService.Load(); err != nil {
|
||||
log.Printf("[Spotify] Failed to load accounts: %v", err)
|
||||
}
|
||||
|
||||
server.SetSpotifyService(spotifyService)
|
||||
|
||||
clientIDPrefix := config.spotifyClientID
|
||||
if len(clientIDPrefix) > 8 {
|
||||
clientIDPrefix = clientIDPrefix[:8]
|
||||
}
|
||||
|
||||
log.Printf("Spotify service initialized (client ID: %s...)", clientIDPrefix)
|
||||
}
|
||||
|
||||
if config.amazonClientID != "" {
|
||||
amazonService := amazon.NewAmazonService(
|
||||
config.amazonClientID,
|
||||
config.amazonClientSecret,
|
||||
config.amazonRedirectURI,
|
||||
config.dataDir,
|
||||
)
|
||||
if config.amazonTokenURL != "" || config.amazonProfileURL != "" {
|
||||
amazonService.SetEndpoints(config.amazonTokenURL, config.amazonProfileURL)
|
||||
}
|
||||
|
||||
if err := amazonService.Load(); err != nil {
|
||||
log.Printf("[Amazon] Failed to load accounts: %v", err)
|
||||
}
|
||||
|
||||
server.SetAmazonService(amazonService)
|
||||
|
||||
clientIDPrefix := config.amazonClientID
|
||||
if len(clientIDPrefix) > 8 {
|
||||
clientIDPrefix = clientIDPrefix[:8]
|
||||
}
|
||||
|
||||
log.Printf("Amazon Music service initialized (client ID: %s...)", clientIDPrefix)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
updateBuildInfo()
|
||||
|
||||
@@ -187,6 +240,12 @@ func main() {
|
||||
Value: true,
|
||||
EnvVars: []string{"RECORD_INTERACTIONS"},
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "discovery-enabled",
|
||||
Usage: "Enable periodic device discovery",
|
||||
Value: true,
|
||||
EnvVars: []string{"DISCOVERY_ENABLED"},
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "discovery-interval",
|
||||
Usage: "Device discovery interval",
|
||||
@@ -222,8 +281,7 @@ func main() {
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "spotify-redirect-uri",
|
||||
Usage: "Spotify OAuth redirect URI",
|
||||
Value: "ueberboese-login://spotify",
|
||||
Usage: "Spotify OAuth redirect URI (defaults to <server-url>/mgmt/spotify/callback)",
|
||||
EnvVars: []string{"SPOTIFY_REDIRECT_URI"},
|
||||
},
|
||||
&cli.StringFlag{
|
||||
@@ -236,6 +294,31 @@ func main() {
|
||||
Usage: "Spotify API base URL (for testing)",
|
||||
EnvVars: []string{"SPOTIFY_API_BASE"},
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "amazon-client-id",
|
||||
Usage: "Amazon LWA OAuth client ID",
|
||||
EnvVars: []string{"AMAZON_CLIENT_ID"},
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "amazon-client-secret",
|
||||
Usage: "Amazon LWA OAuth client secret",
|
||||
EnvVars: []string{"AMAZON_CLIENT_SECRET"},
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "amazon-redirect-uri",
|
||||
Usage: "Amazon LWA OAuth redirect URI (defaults to <server-url>/mgmt/amazon/callback)",
|
||||
EnvVars: []string{"AMAZON_REDIRECT_URI"},
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "amazon-token-url",
|
||||
Usage: "Amazon LWA token URL (for testing)",
|
||||
EnvVars: []string{"AMAZON_TOKEN_URL"},
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "amazon-profile-url",
|
||||
Usage: "Amazon LWA profile URL (for testing)",
|
||||
EnvVars: []string{"AMAZON_PROFILE_URL"},
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "mgmt-username",
|
||||
Usage: "Management API username for HTTP Basic Auth",
|
||||
@@ -310,7 +393,7 @@ func main() {
|
||||
|
||||
config.domains = getDomains(config.serverURL, config.httpsServerURL, hostname)
|
||||
|
||||
cm := initCertificateManager(config.dataDir)
|
||||
cm := initCertificateManager(config.dataDir, config.hostname)
|
||||
sm := setup.NewManager(config.serverURL, ds, cm)
|
||||
sm.MgmtUsername = config.mgmtUsername
|
||||
sm.MgmtPassword = config.mgmtPassword
|
||||
@@ -318,37 +401,15 @@ func main() {
|
||||
sm.GetDNSRunning = server.GetDNSRunning
|
||||
server.SetHTTPServerURL(config.httpsServerURL)
|
||||
server.SetVersionInfo(version, commit, date, repoURL)
|
||||
server.SetDiscoverySettings(config.discoveryInterval, persisted.DiscoveryEnabled)
|
||||
server.SetDiscoverySettings(config.discoveryInterval, config.discoveryEnabled)
|
||||
server.SetDNSSettings(persisted.DNSEnabled, strings.Join(persisted.DNSUpstream, ","), persisted.DNSBindAddr)
|
||||
server.SetMirrorSettings(persisted.MirrorEnabled, persisted.MirrorEndpoints, persisted.SkipMirrorEndpoints, persisted.PreferredSource)
|
||||
server.SetInternalPaths(persisted.InternalPaths)
|
||||
server.SetSpotifyConfig(config.spotifyClientID, config.spotifyClientSecret, config.spotifyRedirectURI)
|
||||
server.SetAmazonConfig(config.amazonClientID, config.amazonClientSecret, config.amazonRedirectURI)
|
||||
server.SetMgmtConfig(config.mgmtUsername, config.mgmtPassword)
|
||||
|
||||
if config.spotifyClientID != "" {
|
||||
spotifyService := spotify.NewSpotifyService(
|
||||
config.spotifyClientID,
|
||||
config.spotifyClientSecret,
|
||||
config.spotifyRedirectURI,
|
||||
config.dataDir,
|
||||
)
|
||||
if config.spotifyTokenURL != "" || config.spotifyAPIBase != "" {
|
||||
spotifyService.SetEndpoints(config.spotifyTokenURL, config.spotifyAPIBase)
|
||||
}
|
||||
|
||||
if err := spotifyService.Load(); err != nil {
|
||||
log.Printf("[Spotify] Failed to load accounts: %v", err)
|
||||
}
|
||||
|
||||
server.SetSpotifyService(spotifyService)
|
||||
|
||||
clientIDPrefix := config.spotifyClientID
|
||||
if len(clientIDPrefix) > 8 {
|
||||
clientIDPrefix = clientIDPrefix[:8]
|
||||
}
|
||||
|
||||
log.Printf("Spotify service initialized (client ID: %s...)", clientIDPrefix)
|
||||
}
|
||||
initMusicServices(config, server)
|
||||
|
||||
// Load and set initial DNS discoveries
|
||||
dnsDiscoveries, err := ds.LoadDNSDiscoveries()
|
||||
@@ -405,20 +466,25 @@ func main() {
|
||||
|
||||
initializeDefaultSources(ds)
|
||||
|
||||
tlsConfig, err := cm.GetServerTLSConfig(config.domains)
|
||||
if err != nil {
|
||||
log.Printf("Warning: Failed to setup TLS: %v", err)
|
||||
}
|
||||
|
||||
startDeviceDiscovery(server)
|
||||
|
||||
r := setupRouter(server)
|
||||
|
||||
log.Printf("Go service starting on %s", config.serverURL)
|
||||
|
||||
if tlsConfig != nil {
|
||||
// TLS cert generation can be slow on constrained hardware; run it in the
|
||||
// background so the HTTP server is available immediately.
|
||||
log.Printf("HTTPS setup running in background; %s will be available shortly", config.httpsServerURL)
|
||||
|
||||
go func() {
|
||||
tlsConfig, err := cm.GetServerTLSConfig(config.domains)
|
||||
if err != nil {
|
||||
log.Printf("Warning: Failed to setup TLS: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
startHTTPSServer(config.httpsAddr, r, tlsConfig, config.httpsServerURL)
|
||||
}
|
||||
}()
|
||||
|
||||
return http.ListenAndServe(config.addr, r)
|
||||
},
|
||||
@@ -452,6 +518,7 @@ type serviceConfig struct {
|
||||
bindAddr string
|
||||
addr string
|
||||
dataDir string
|
||||
hostname string
|
||||
serverURL string
|
||||
httpsServerURL string
|
||||
httpsAddr string
|
||||
@@ -465,6 +532,7 @@ type serviceConfig struct {
|
||||
mirrorEndpoints []string
|
||||
skipMirrorEndpoints []string
|
||||
internalPaths []string
|
||||
discoveryEnabled bool
|
||||
discoveryInterval time.Duration
|
||||
domains []string
|
||||
spotifyClientID string
|
||||
@@ -472,6 +540,11 @@ type serviceConfig struct {
|
||||
spotifyRedirectURI string
|
||||
spotifyTokenURL string
|
||||
spotifyAPIBase string
|
||||
amazonClientID string
|
||||
amazonClientSecret string
|
||||
amazonRedirectURI string
|
||||
amazonTokenURL string
|
||||
amazonProfileURL string
|
||||
mgmtUsername string
|
||||
mgmtPassword string
|
||||
migrationEnabled bool
|
||||
@@ -524,6 +597,7 @@ func loadConfig(c *cli.Context) serviceConfig {
|
||||
dnsUpstream := c.String("dns-upstream")
|
||||
dnsBind := c.String("dns-bind")
|
||||
|
||||
discoveryEnabled := c.Bool("discovery-enabled")
|
||||
discoveryIntervalStr := c.String("discovery-interval")
|
||||
|
||||
discoveryInterval, err := time.ParseDuration(discoveryIntervalStr)
|
||||
@@ -538,6 +612,11 @@ func loadConfig(c *cli.Context) serviceConfig {
|
||||
spotifyRedirectURI := c.String("spotify-redirect-uri")
|
||||
spotifyTokenURL := c.String("spotify-token-url")
|
||||
spotifyAPIBase := c.String("spotify-api-base")
|
||||
amazonClientID := c.String("amazon-client-id")
|
||||
amazonClientSecret := c.String("amazon-client-secret")
|
||||
amazonRedirectURI := c.String("amazon-redirect-uri")
|
||||
amazonTokenURL := c.String("amazon-token-url")
|
||||
amazonProfileURL := c.String("amazon-profile-url")
|
||||
mgmtUsername := c.String("mgmt-username")
|
||||
mgmtPassword := c.String("mgmt-password")
|
||||
mirrorEnabled := c.Bool("mirror-enabled")
|
||||
@@ -553,6 +632,7 @@ func loadConfig(c *cli.Context) serviceConfig {
|
||||
bindAddr: bindAddr,
|
||||
addr: addr,
|
||||
dataDir: dataDir,
|
||||
hostname: hostname,
|
||||
serverURL: serverURL,
|
||||
httpsServerURL: httpsServerURL,
|
||||
httpsAddr: httpsAddr,
|
||||
@@ -566,6 +646,7 @@ func loadConfig(c *cli.Context) serviceConfig {
|
||||
mirrorEndpoints: mirrorEndpoints,
|
||||
skipMirrorEndpoints: skipMirrorEndpoints,
|
||||
internalPaths: internalPaths,
|
||||
discoveryEnabled: discoveryEnabled,
|
||||
discoveryInterval: discoveryInterval,
|
||||
domains: domains,
|
||||
spotifyClientID: spotifyClientID,
|
||||
@@ -573,6 +654,11 @@ func loadConfig(c *cli.Context) serviceConfig {
|
||||
spotifyRedirectURI: spotifyRedirectURI,
|
||||
spotifyTokenURL: spotifyTokenURL,
|
||||
spotifyAPIBase: spotifyAPIBase,
|
||||
amazonClientID: amazonClientID,
|
||||
amazonClientSecret: amazonClientSecret,
|
||||
amazonRedirectURI: amazonRedirectURI,
|
||||
amazonTokenURL: amazonTokenURL,
|
||||
amazonProfileURL: amazonProfileURL,
|
||||
mgmtUsername: mgmtUsername,
|
||||
mgmtPassword: mgmtPassword,
|
||||
migrationEnabled: migrationEnabled,
|
||||
@@ -598,6 +684,7 @@ func getDomains(serverURL, httpsServerURL, hostname string) []string {
|
||||
"bose.io": true,
|
||||
"bose-prod.apigee.net": true,
|
||||
"bose-test.apigee.net": true,
|
||||
"downloads.bose.com": true,
|
||||
// Local service domains
|
||||
setup.TestDomain: true,
|
||||
hostname: true,
|
||||
@@ -642,6 +729,7 @@ func applyPersistedSettings(ds *datastore.DataStore, config *serviceConfig) data
|
||||
config.httpsServerURL = persisted.HTTPServerURL
|
||||
}
|
||||
|
||||
config.discoveryEnabled = persisted.DiscoveryEnabled
|
||||
if persisted.DiscoveryInterval != "" {
|
||||
if d, durErr := time.ParseDuration(persisted.DiscoveryInterval); durErr == nil {
|
||||
config.discoveryInterval = d
|
||||
@@ -667,9 +755,40 @@ func applyPersistedSettings(ds *datastore.DataStore, config *serviceConfig) data
|
||||
config.preferredSource = persisted.PreferredSource
|
||||
config.internalPaths = persisted.InternalPaths
|
||||
|
||||
// CLI/env args take precedence; only apply persisted credentials when not set via CLI.
|
||||
applyPersistedMusicServiceCredentials(config, persisted)
|
||||
|
||||
return persisted
|
||||
}
|
||||
|
||||
// applyPersistedMusicServiceCredentials fills in music service credentials from persisted
|
||||
// settings when they have not been supplied via CLI flags or environment variables.
|
||||
func applyPersistedMusicServiceCredentials(config *serviceConfig, persisted datastore.Settings) {
|
||||
if config.spotifyClientID == "" {
|
||||
config.spotifyClientID = persisted.SpotifyClientID
|
||||
}
|
||||
|
||||
if config.spotifyClientSecret == "" {
|
||||
config.spotifyClientSecret = persisted.SpotifyClientSecret
|
||||
}
|
||||
|
||||
if config.spotifyRedirectURI == "" {
|
||||
config.spotifyRedirectURI = persisted.SpotifyRedirectURI
|
||||
}
|
||||
|
||||
if config.amazonClientID == "" {
|
||||
config.amazonClientID = persisted.AmazonClientID
|
||||
}
|
||||
|
||||
if config.amazonClientSecret == "" {
|
||||
config.amazonClientSecret = persisted.AmazonClientSecret
|
||||
}
|
||||
|
||||
if config.amazonRedirectURI == "" {
|
||||
config.amazonRedirectURI = persisted.AmazonRedirectURI
|
||||
}
|
||||
}
|
||||
|
||||
func createDefaultSettings(ds *datastore.DataStore, config serviceConfig) datastore.Settings {
|
||||
settings := datastore.Settings{
|
||||
ServerURL: config.serverURL,
|
||||
@@ -677,8 +796,8 @@ func createDefaultSettings(ds *datastore.DataStore, config serviceConfig) datast
|
||||
RedactLogs: config.redact,
|
||||
LogBodies: config.logBody,
|
||||
RecordInteractions: config.record,
|
||||
DiscoveryEnabled: config.discoveryEnabled,
|
||||
DiscoveryInterval: config.discoveryInterval.String(),
|
||||
DiscoveryEnabled: true,
|
||||
DNSEnabled: config.dnsEnabled,
|
||||
DNSUpstream: strings.Split(config.dnsUpstream, ","),
|
||||
DNSBindAddr: config.dnsBind,
|
||||
@@ -707,8 +826,10 @@ func initDataStore(dataDir string) *datastore.DataStore {
|
||||
return ds
|
||||
}
|
||||
|
||||
func initCertificateManager(dataDir string) *certmanager.CertificateManager {
|
||||
func initCertificateManager(dataDir, hostname string) *certmanager.CertificateManager {
|
||||
cm := certmanager.NewCertificateManager(filepath.Join(dataDir, "certs"))
|
||||
|
||||
cm.CommonName = hostname
|
||||
if err := cm.EnsureCA(); err != nil {
|
||||
log.Printf("Warning: Failed to ensure CA: %v", err)
|
||||
}
|
||||
@@ -746,7 +867,10 @@ func setupRouter(server *handlers.Server) *chi.Mux {
|
||||
})
|
||||
|
||||
r.Get("/media/*", server.HandleMedia())
|
||||
r.Get("/bmx-icons/*", server.HandleBmxIcons())
|
||||
r.Get("/ced/*", server.HandleCedStatic())
|
||||
r.Get("/web/*", server.HandleWeb())
|
||||
r.Post("/alexa/certificate", server.HandleAlexaCertificate)
|
||||
r.Get("/docs/*", server.HandleDocs)
|
||||
|
||||
r.Route("/bmx", func(r chi.Router) {
|
||||
@@ -762,9 +886,12 @@ func setupRouter(server *handlers.Server) *chi.Mux {
|
||||
r.Get("/v1/navigate", server.HandleTuneInNavigate)
|
||||
r.Get("/v1/navigate/*", server.HandleTuneInNavigate)
|
||||
r.Get("/v1/search", server.HandleTuneInSearch)
|
||||
r.Post("/v1/favorite/{stationID}", server.HandleTuneInFavorite)
|
||||
r.Delete("/v1/favorite/{stationID}", server.HandleTuneInDeleteFavorite)
|
||||
})
|
||||
|
||||
r.Post("/orion/v1/playback/station/{data}", server.HandleOrionPlayback)
|
||||
r.Post("/core02/svc-bmx-adapter-orion/prod/orion/token", server.HandleOrionToken)
|
||||
})
|
||||
|
||||
r.Get("/custom/v1/playback/{encodedURL}", server.HandleCustomPlayback)
|
||||
@@ -804,6 +931,10 @@ func setupRouter(server *handlers.Server) *chi.Mux {
|
||||
r.Get("/group/member", server.HandleMargeDeviceGroupMember)
|
||||
})
|
||||
|
||||
r.Post("/group", server.HandleMargeAddGroup)
|
||||
r.Post("/group/{groupId}", server.HandleMargeModifyGroup)
|
||||
r.Delete("/group/{groupId}", server.HandleMargeDeleteGroup)
|
||||
|
||||
r.Delete("/device/{device}", server.HandleMargeRemoveDevice)
|
||||
})
|
||||
|
||||
@@ -827,6 +958,7 @@ func setupRouter(server *handlers.Server) *chi.Mux {
|
||||
r.Route("/music", func(r chi.Router) {
|
||||
r.Route("/musicprovider/{providerID}", func(r chi.Router) {
|
||||
r.Post("/is_eligible", server.HandleMusicProviderIsEligible)
|
||||
r.Post("/trial/is_eligible", server.HandleMusicProviderIsEligible)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -846,6 +978,10 @@ func setupRouter(server *handlers.Server) *chi.Mux {
|
||||
r.Get("/devices/{device}/group/", server.HandleMargeDeviceGroup)
|
||||
r.Get("/devices/{device}/group/server", server.HandleMargeDeviceGroupServer)
|
||||
r.Get("/devices/{device}/group/member", server.HandleMargeDeviceGroupMember)
|
||||
|
||||
r.Post("/group", server.HandleMargeAddGroup)
|
||||
r.Post("/group/{groupId}", server.HandleMargeModifyGroup)
|
||||
r.Delete("/group/{groupId}", server.HandleMargeDeleteGroup)
|
||||
r.Get("/devices/{device}/presets", server.HandleMargePresets)
|
||||
r.Get("/devices/{device}/recents", server.HandleMargeRecents)
|
||||
|
||||
@@ -863,9 +999,10 @@ func setupRouter(server *handlers.Server) *chi.Mux {
|
||||
})
|
||||
|
||||
r.Route("/oauth", func(r chi.Router) {
|
||||
r.Post("/device/{deviceID}/music/musicprovider/{sourceID}/token/cs3", server.HandleBoseToken)
|
||||
r.Post("/device/{deviceID}/music/musicprovider/{sourceID}/token", server.HandleBoseLegacyToken)
|
||||
r.Post("/account/{account}/music/musicprovider/{sourceID}/token/cs", server.HandleBoseAccountToken)
|
||||
r.Post("/device/{deviceID}/music/musicprovider/{sourceID}/token/cs1", server.HandleBoseToken)
|
||||
r.Post("/device/{deviceID}/music/musicprovider/{sourceID}/token/cs3", server.HandleBoseToken)
|
||||
r.HandleFunc("/*", server.HandleBoseProxy)
|
||||
})
|
||||
|
||||
@@ -879,10 +1016,11 @@ func setupRouter(server *handlers.Server) *chi.Mux {
|
||||
})
|
||||
|
||||
r.Route("/mgmt", func(r chi.Router) {
|
||||
// Browser OAuth callback — no auth required (Spotify redirects the
|
||||
// Browser OAuth callbacks — no auth required (provider redirects the
|
||||
// user's browser here directly). The authorization code is single-use,
|
||||
// short-lived, and useless without the client_secret.
|
||||
r.Get("/spotify/callback", server.HandleMgmtSpotifyCallback)
|
||||
r.Get("/amazon/callback", server.HandleMgmtAmazonCallback)
|
||||
|
||||
// All other management endpoints require Basic Auth.
|
||||
r.Group(func(r chi.Router) {
|
||||
@@ -905,6 +1043,14 @@ func setupRouter(server *handlers.Server) *chi.Mux {
|
||||
r.Post("/prime", server.HandleMgmtPrimeDevice)
|
||||
})
|
||||
|
||||
r.Route("/amazon", func(r chi.Router) {
|
||||
r.Post("/init", server.HandleMgmtAmazonInit)
|
||||
r.Post("/confirm", server.HandleMgmtAmazonConfirm)
|
||||
r.Get("/accounts", server.HandleMgmtAmazonAccounts)
|
||||
r.Get("/token", server.HandleMgmtAmazonToken)
|
||||
r.Post("/prime", server.HandleMgmtPrimeDeviceAmazon)
|
||||
})
|
||||
|
||||
r.Get("/devices/{deviceId}/events", server.HandleMgmtDeviceEvents)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
CONNECT /oauth/* handlers.(*Server).HandleBoseProxy-fm
|
||||
DELETE /accounts/{account}/devices/{device} handlers.(*Server).HandleMargeRemoveDevice-fm
|
||||
DELETE /accounts/{account}/group/{groupId} handlers.(*Server).HandleMargeDeleteGroup-fm
|
||||
DELETE /bmx/tunein/v1/favorite/{stationID} handlers.(*Server).HandleTuneInDeleteFavorite-fm
|
||||
DELETE /oauth/* handlers.(*Server).HandleBoseProxy-fm
|
||||
DELETE /setup/devices/{deviceId} handlers.(*Server).HandleRemoveDevice-fm
|
||||
DELETE /setup/dns-discoveries handlers.(*Server).HandleClearDNSDiscoveries-fm
|
||||
@@ -7,6 +9,7 @@ DELETE /setup/interactions/sessions handlers.(
|
||||
DELETE /setup/interactions/sessions/{session} handlers.(*Server).HandleDeleteSession-fm
|
||||
DELETE /setup/parity-mismatches handlers.(*Server).HandleClearParityMismatches-fm
|
||||
DELETE /streaming/account/{account}/device/{device}/preset/{presetNumber} handlers.(*Server).HandleMargeRemovePreset-fm
|
||||
DELETE /streaming/account/{account}/group/{groupId} handlers.(*Server).HandleMargeDeleteGroup-fm
|
||||
GET / handlers.(*Server).HandleRoot-fm
|
||||
GET /accounts/{account}/devices handlers.(*Server).HandleMargeAccountDevices-fm
|
||||
GET /accounts/{account}/devices/{device}/group handlers.(*Server).HandleMargeDeviceGroup-fm
|
||||
@@ -17,6 +20,7 @@ GET /accounts/{account}/devices/{device}/presets handlers.(
|
||||
GET /accounts/{account}/devices/{device}/recents handlers.(*Server).HandleMargeRecents-fm
|
||||
GET /accounts/{account}/full handlers.(*Server).HandleMargeAccountFull-fm
|
||||
GET /accounts/{account}/sources handlers.(*Server).HandleMargeAccountSources-fm
|
||||
GET /bmx-icons/* handlers.(*Server).HandleBmxIcons
|
||||
GET /bmx/registry/v1/services handlers.(*Server).HandleBMXRegistry-fm
|
||||
GET /bmx/registry/v1/servicesAvailability handlers.(*Server).HandleBMXServicesAvailability-fm
|
||||
GET /bmx/tunein/v1/navigate handlers.(*Server).HandleTuneInNavigate-fm
|
||||
@@ -25,6 +29,7 @@ GET /bmx/tunein/v1/playback/episode/{podcastID} handlers.(
|
||||
GET /bmx/tunein/v1/playback/episodes/{podcastID} handlers.(*Server).HandleTuneInPodcastInfo-fm
|
||||
GET /bmx/tunein/v1/playback/station/{stationID} handlers.(*Server).HandleTuneInPlayback-fm
|
||||
GET /bmx/tunein/v1/search handlers.(*Server).HandleTuneInSearch-fm
|
||||
GET /ced/* handlers.(*Server).HandleCedStatic
|
||||
GET /custom/v1/playback/{encodedURL} handlers.(*Server).HandleCustomPlayback-fm
|
||||
GET /customer/account/{account} handlers.(*Server).HandleMargeAccountProfile-fm
|
||||
GET /docs/* handlers.(*Server).HandleDocs-fm
|
||||
@@ -34,6 +39,9 @@ GET /media/* handlers.(
|
||||
GET /mgmt/accounts/ handlers.(*Server).HandleMgmtListAccounts-fm
|
||||
GET /mgmt/accounts/{accountId} handlers.(*Server).HandleMgmtAccountDetails-fm
|
||||
GET /mgmt/accounts/{accountId}/speakers handlers.(*Server).HandleMgmtListSpeakers-fm
|
||||
GET /mgmt/amazon/accounts handlers.(*Server).HandleMgmtAmazonAccounts-fm
|
||||
GET /mgmt/amazon/callback handlers.(*Server).HandleMgmtAmazonCallback-fm
|
||||
GET /mgmt/amazon/token handlers.(*Server).HandleMgmtAmazonToken-fm
|
||||
GET /mgmt/devices/{deviceId}/events handlers.(*Server).HandleMgmtDeviceEvents-fm
|
||||
GET /mgmt/spotify/accounts handlers.(*Server).HandleMgmtSpotifyAccounts-fm
|
||||
GET /mgmt/spotify/callback handlers.(*Server).HandleMgmtSpotifyCallback-fm
|
||||
@@ -84,13 +92,21 @@ PATCH /oauth/* handlers.(
|
||||
POST /accounts/{account}/devices handlers.(*Server).HandleMargeAddDevice-fm
|
||||
POST /accounts/{account}/devices/{device}/presets/{presetNumber} handlers.(*Server).HandleMargeUpdatePreset-fm
|
||||
POST /accounts/{account}/devices/{device}/recents handlers.(*Server).HandleMargeAddRecent-fm
|
||||
POST /accounts/{account}/group handlers.(*Server).HandleMargeAddGroup-fm
|
||||
POST /accounts/{account}/group/{groupId} handlers.(*Server).HandleMargeModifyGroup-fm
|
||||
POST /alexa/certificate handlers.(*Server).HandleAlexaCertificate-fm
|
||||
POST /bmx/core02/svc-bmx-adapter-orion/prod/orion/token handlers.(*Server).HandleOrionToken-fm
|
||||
POST /bmx/orion/v1/playback/station/{data} handlers.(*Server).HandleOrionPlayback-fm
|
||||
POST /bmx/tunein/v1/favorite/{stationID} handlers.(*Server).HandleTuneInFavorite-fm
|
||||
POST /bmx/tunein/v1/report handlers.(*Server).HandleTuneInReport-fm
|
||||
POST /bmx/tunein/v1/token handlers.(*Server).HandleTuneInToken-fm
|
||||
POST /customer/account/{account} handlers.(*Server).HandleMargeUpdateAccountProfile-fm
|
||||
POST /customer/account/{account}/password handlers.(*Server).HandleMargeChangePassword-fm
|
||||
POST /mgmt/accounts/{accountId}/language handlers.(*Server).HandleMgmtUpdateAccountLanguage-fm
|
||||
POST /mgmt/accounts/{accountId}/provider-settings handlers.(*Server).HandleMgmtUpdateAccountProviderSetting-fm
|
||||
POST /mgmt/amazon/confirm handlers.(*Server).HandleMgmtAmazonConfirm-fm
|
||||
POST /mgmt/amazon/init handlers.(*Server).HandleMgmtAmazonInit-fm
|
||||
POST /mgmt/amazon/prime handlers.(*Server).HandleMgmtPrimeDeviceAmazon-fm
|
||||
POST /mgmt/spotify/confirm handlers.(*Server).HandleMgmtSpotifyConfirm-fm
|
||||
POST /mgmt/spotify/entity handlers.(*Server).HandleMgmtSpotifyEntity-fm
|
||||
POST /mgmt/spotify/init handlers.(*Server).HandleMgmtSpotifyInit-fm
|
||||
@@ -98,6 +114,7 @@ POST /mgmt/spotify/prime handlers.(
|
||||
POST /oauth/* handlers.(*Server).HandleBoseProxy-fm
|
||||
POST /oauth/account/{account}/music/musicprovider/{sourceID}/token/cs handlers.(*Server).HandleBoseAccountToken-fm
|
||||
POST /oauth/device/{deviceID}/music/musicprovider/{sourceID}/token handlers.(*Server).HandleBoseLegacyToken-fm
|
||||
POST /oauth/device/{deviceID}/music/musicprovider/{sourceID}/token/cs1 handlers.(*Server).HandleBoseToken-fm
|
||||
POST /oauth/device/{deviceID}/music/musicprovider/{sourceID}/token/cs3 handlers.(*Server).HandleBoseToken-fm
|
||||
POST /setup/backup/{deviceId} handlers.(*Server).HandleBackupConfig-fm
|
||||
POST /setup/devices handlers.(*Server).HandleAddManualDevice-fm
|
||||
@@ -120,9 +137,12 @@ POST /streaming/account/{account}/device/ handlers.(
|
||||
POST /streaming/account/{account}/device/{device} handlers.(*Server).HandleMargeAddDevice-fm
|
||||
POST /streaming/account/{account}/device/{device}/presets/{presetNumber} handlers.(*Server).HandleMargeUpdatePreset-fm
|
||||
POST /streaming/account/{account}/device/{device}/recent handlers.(*Server).HandleMargeAddRecent-fm
|
||||
POST /streaming/account/{account}/group handlers.(*Server).HandleMargeAddGroup-fm
|
||||
POST /streaming/account/{account}/group/{groupId} handlers.(*Server).HandleMargeModifyGroup-fm
|
||||
POST /streaming/account/{account}/source handlers.(*Server).HandleMargeAddSource-fm
|
||||
POST /streaming/device_setting/account/{account}/device/{device}/device_settings handlers.(*Server).HandleMargeUpdateDeviceSettings-fm
|
||||
POST /streaming/music/musicprovider/{providerID}/is_eligible handlers.(*Server).HandleMusicProviderIsEligible-fm
|
||||
POST /streaming/music/musicprovider/{providerID}/trial/is_eligible handlers.(*Server).HandleMusicProviderIsEligible-fm
|
||||
POST /streaming/stats/error handlers.(*Server).HandleErrorStats-fm
|
||||
POST /streaming/stats/usage handlers.(*Server).HandleUsageStats-fm
|
||||
POST /streaming/support/customersupport handlers.(*Server).HandleMargeCustomerSupport-fm
|
||||
|
||||
@@ -1,648 +0,0 @@
|
||||
// Package handlers contains HTTP handlers for the SoundTouch web UI.
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/cmd/soundtouch-web/webtypes"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
bmxpkg "github.com/gesellix/bose-soundtouch/pkg/service/bmx"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// WebApp holds the application state and dependencies
|
||||
type WebApp struct {
|
||||
Devices map[string]*webtypes.DeviceConnection
|
||||
Upgrader websocket.Upgrader
|
||||
WSClients map[*websocket.Conn]bool
|
||||
WSMutex sync.RWMutex
|
||||
}
|
||||
|
||||
// NewWebApp creates a new WebApp instance for SPA mode
|
||||
func NewWebApp() *WebApp {
|
||||
return &WebApp{
|
||||
Devices: make(map[string]*webtypes.DeviceConnection),
|
||||
WSClients: make(map[*websocket.Conn]bool),
|
||||
Upgrader: websocket.Upgrader{
|
||||
CheckOrigin: func(_ *http.Request) bool { return true },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// HandleAPIDevices returns all devices as JSON
|
||||
func (app *WebApp) HandleAPIDevices(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
// Return all devices as JSON
|
||||
devices := make(map[string]interface{})
|
||||
for id, device := range app.Devices {
|
||||
devices[id] = map[string]interface{}{
|
||||
"info": device.DeviceInfo,
|
||||
"status": device.Status,
|
||||
"lastSeen": device.LastSeen,
|
||||
}
|
||||
}
|
||||
|
||||
response := webtypes.APIResponse{
|
||||
Success: true,
|
||||
Data: devices,
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(response); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleAPIDevice returns a specific device as JSON
|
||||
func (app *WebApp) HandleAPIDevice(w http.ResponseWriter, r *http.Request) {
|
||||
deviceID := chi.URLParam(r, "id")
|
||||
if deviceID == "" {
|
||||
app.sendError(w, "Device ID required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
device, exists := app.Devices[deviceID]
|
||||
if !exists {
|
||||
app.sendError(w, "Device not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
// Update device status to get fresh power state
|
||||
app.UpdateDeviceStatus(deviceID, device)
|
||||
|
||||
// Connect WebSocket for real-time updates if not already connected
|
||||
if device.WebSocket == nil {
|
||||
go app.ConnectDeviceWebSocket(deviceID, device)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
response := webtypes.APIResponse{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"info": device.DeviceInfo,
|
||||
"status": device.Status,
|
||||
},
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(response); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleAPIControl handles device control commands
|
||||
func (app *WebApp) HandleAPIControl(w http.ResponseWriter, r *http.Request) {
|
||||
deviceID := chi.URLParam(r, "id")
|
||||
action := chi.URLParam(r, "action")
|
||||
|
||||
if deviceID == "" {
|
||||
app.sendError(w, "Device ID required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
device, exists := app.Devices[deviceID]
|
||||
if !exists {
|
||||
app.sendError(w, "Device not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
// Connect WebSocket for real-time updates if not already connected
|
||||
if device.WebSocket == nil {
|
||||
go app.ConnectDeviceWebSocket(deviceID, device)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
app.handleControlAction(w, r, action, device)
|
||||
}
|
||||
|
||||
// handleControlAction processes different control actions
|
||||
func (app *WebApp) handleControlAction(w http.ResponseWriter, r *http.Request, action string, device *webtypes.DeviceConnection) {
|
||||
switch action {
|
||||
case "play":
|
||||
if device.Client == nil {
|
||||
app.sendError(w, "Device client not available", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
err := device.Client.Play()
|
||||
app.sendControlResponse(w, err, "Started playback")
|
||||
case "pause":
|
||||
if device.Client == nil {
|
||||
app.sendError(w, "Device client not available", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
err := device.Client.Pause()
|
||||
app.sendControlResponse(w, err, "Paused playback")
|
||||
case "stop":
|
||||
if device.Client == nil {
|
||||
app.sendError(w, "Device client not available", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
err := device.Client.Stop()
|
||||
app.sendControlResponse(w, err, "Stopped playback")
|
||||
case "next":
|
||||
if device.Client == nil {
|
||||
app.sendError(w, "Device client not available", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
err := device.Client.NextTrack()
|
||||
app.sendControlResponse(w, err, "Next track")
|
||||
case "previous":
|
||||
if device.Client == nil {
|
||||
app.sendError(w, "Device client not available", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
err := device.Client.PrevTrack()
|
||||
app.sendControlResponse(w, err, "Previous track")
|
||||
case "volume":
|
||||
app.handleVolumeControl(w, r, device)
|
||||
case "mute":
|
||||
if device.Client == nil {
|
||||
app.sendError(w, "Device client not available", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
err := device.Client.SendKey(models.KeyMute)
|
||||
app.sendControlResponse(w, err, "Toggled mute")
|
||||
case "preset":
|
||||
app.handlePresetControl(w, r, device)
|
||||
case "bass":
|
||||
app.handleBassControl(w, r, device)
|
||||
case "source":
|
||||
app.handleSourceControl(w, r, device)
|
||||
default:
|
||||
app.sendError(w, "Unknown action", http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
// handleVolumeControl processes volume control requests
|
||||
func (app *WebApp) handleVolumeControl(w http.ResponseWriter, r *http.Request, device *webtypes.DeviceConnection) {
|
||||
if r.Method != http.MethodPost {
|
||||
app.sendError(w, "POST required for volume control", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var volumeReq webtypes.VolumeRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&volumeReq); err != nil {
|
||||
app.sendError(w, "Invalid volume data", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if volumeReq.Level < 0 || volumeReq.Level > 100 {
|
||||
app.sendError(w, "Volume must be between 0 and 100", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if device.Client == nil {
|
||||
app.sendError(w, "Device client not available", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
err := device.Client.SetVolume(volumeReq.Level)
|
||||
app.sendControlResponse(w, err, fmt.Sprintf("Volume set to %d", volumeReq.Level))
|
||||
}
|
||||
|
||||
// handlePresetControl processes preset control requests
|
||||
func (app *WebApp) handlePresetControl(w http.ResponseWriter, r *http.Request, device *webtypes.DeviceConnection) {
|
||||
presetParam := r.URL.Query().Get("id")
|
||||
if presetParam == "" {
|
||||
app.sendError(w, "Preset ID required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
presetID, err := strconv.Atoi(presetParam)
|
||||
if err != nil {
|
||||
app.sendError(w, "Invalid preset ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if device.Client == nil {
|
||||
app.sendError(w, "Device client not available", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
err = device.Client.SelectPreset(presetID)
|
||||
app.sendControlResponse(w, err, fmt.Sprintf("Selected preset %d", presetID))
|
||||
}
|
||||
|
||||
// handleBassControl processes bass control requests
|
||||
func (app *WebApp) handleBassControl(w http.ResponseWriter, r *http.Request, device *webtypes.DeviceConnection) {
|
||||
if r.Method != http.MethodPost {
|
||||
app.sendError(w, "POST required for bass control", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var bassReq webtypes.BassRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&bassReq); err != nil {
|
||||
app.sendError(w, "Invalid bass data", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if bassReq.Level < -9 || bassReq.Level > 9 {
|
||||
app.sendError(w, "Bass must be between -9 and 9", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if device.Client == nil {
|
||||
app.sendError(w, "Device client not available", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
err := device.Client.SetBass(bassReq.Level)
|
||||
app.sendControlResponse(w, err, fmt.Sprintf("Bass set to %d", bassReq.Level))
|
||||
}
|
||||
|
||||
// handleSourceControl processes source control requests
|
||||
func (app *WebApp) handleSourceControl(w http.ResponseWriter, r *http.Request, device *webtypes.DeviceConnection) {
|
||||
sourceParam := r.URL.Query().Get("name")
|
||||
if sourceParam == "" {
|
||||
app.sendError(w, "Source name required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if device.Client == nil {
|
||||
app.sendError(w, "Device client not available", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
err := device.Client.SelectSource(sourceParam, "")
|
||||
app.sendControlResponse(w, err, fmt.Sprintf("Selected source %s", sourceParam))
|
||||
}
|
||||
|
||||
// sendControlResponse sends a control command response
|
||||
func (app *WebApp) sendControlResponse(w http.ResponseWriter, err error, successMessage string) {
|
||||
if err != nil {
|
||||
app.sendError(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
response := webtypes.APIResponse{
|
||||
Success: true,
|
||||
Data: map[string]string{"message": successMessage},
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(response); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// sendError sends an error response
|
||||
func (app *WebApp) sendError(w http.ResponseWriter, message string, statusCode int) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(statusCode)
|
||||
|
||||
response := webtypes.APIResponse{
|
||||
Success: false,
|
||||
Error: message,
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(response); err != nil {
|
||||
http.Error(w, "Failed to encode error response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleDeviceKey handles sending key commands to devices
|
||||
func (app *WebApp) HandleDeviceKey(w http.ResponseWriter, r *http.Request) {
|
||||
deviceID := chi.URLParam(r, "id")
|
||||
key := chi.URLParam(r, "key")
|
||||
|
||||
device, exists := app.Devices[deviceID]
|
||||
if !exists {
|
||||
app.sendError(w, "Device not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
// Connect WebSocket for real-time updates if not already connected
|
||||
if device.WebSocket == nil {
|
||||
go app.ConnectDeviceWebSocket(deviceID, device)
|
||||
}
|
||||
|
||||
if device.Client == nil {
|
||||
app.sendError(w, "Device client not available", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
err := device.Client.SendKey(key)
|
||||
app.sendControlResponse(w, err, fmt.Sprintf("Sent key command: %s", key))
|
||||
}
|
||||
|
||||
// HandleDirectVolumeControl handles direct volume setting via URL parameter
|
||||
func (app *WebApp) HandleDirectVolumeControl(w http.ResponseWriter, r *http.Request) {
|
||||
deviceID := chi.URLParam(r, "id")
|
||||
|
||||
volumeLevel, err := strconv.Atoi(chi.URLParam(r, "volume"))
|
||||
if err != nil || volumeLevel < 0 || volumeLevel > 100 {
|
||||
app.sendError(w, "Invalid volume level (0-100)", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
device, exists := app.Devices[deviceID]
|
||||
if !exists {
|
||||
app.sendError(w, "Device not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
// Connect WebSocket for real-time updates if not already connected
|
||||
if device.WebSocket == nil {
|
||||
go app.ConnectDeviceWebSocket(deviceID, device)
|
||||
}
|
||||
|
||||
if device.Client == nil {
|
||||
app.sendError(w, "Device client not available", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
err = device.Client.SetVolume(volumeLevel)
|
||||
app.sendControlResponse(w, err, fmt.Sprintf("Volume set to %d", volumeLevel))
|
||||
}
|
||||
|
||||
// HandleDevicePower handles power toggle commands for devices
|
||||
func (app *WebApp) HandleDevicePower(w http.ResponseWriter, r *http.Request) {
|
||||
deviceID := chi.URLParam(r, "id")
|
||||
|
||||
device, exists := app.Devices[deviceID]
|
||||
if !exists {
|
||||
app.sendError(w, "Device not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
// Connect WebSocket for real-time updates if not already connected
|
||||
if device.WebSocket == nil {
|
||||
go app.ConnectDeviceWebSocket(deviceID, device)
|
||||
}
|
||||
|
||||
if device.Client == nil {
|
||||
app.sendError(w, "Device client not available", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
// Send POWER key command to toggle device power
|
||||
err := device.Client.SendKey("POWER")
|
||||
app.sendControlResponse(w, err, "Power toggle command sent")
|
||||
}
|
||||
|
||||
// HandleDevicePowerStatus handles lightweight power status check
|
||||
func (app *WebApp) HandleDevicePowerStatus(w http.ResponseWriter, r *http.Request) {
|
||||
deviceID := chi.URLParam(r, "id")
|
||||
|
||||
device, exists := app.Devices[deviceID]
|
||||
if !exists {
|
||||
app.sendError(w, "Device not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
if device.Client == nil {
|
||||
app.sendError(w, "Device client not available", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
// Quick power status check by getting now playing
|
||||
nowPlaying, err := device.Client.GetNowPlaying()
|
||||
if err != nil {
|
||||
app.sendControlResponse(w, err, "Failed to get power status")
|
||||
return
|
||||
}
|
||||
|
||||
isPoweredOn := nowPlaying != nil && nowPlaying.Source != "STANDBY"
|
||||
|
||||
response := webtypes.APIResponse{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"deviceId": deviceID,
|
||||
"isPoweredOn": isPoweredOn,
|
||||
"source": nowPlaying.Source,
|
||||
},
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(response); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// BroadcastDeviceList sends updated device list to all connected WebSocket clients
|
||||
func (app *WebApp) BroadcastDeviceList() {
|
||||
app.WSMutex.RLock()
|
||||
defer app.WSMutex.RUnlock()
|
||||
|
||||
devices := make(map[string]interface{})
|
||||
for id, device := range app.Devices {
|
||||
devices[id] = map[string]interface{}{
|
||||
"info": device.DeviceInfo,
|
||||
"status": device.Status,
|
||||
"lastSeen": device.LastSeen,
|
||||
}
|
||||
}
|
||||
|
||||
message := webtypes.WebSocketMessage{
|
||||
Type: "devices",
|
||||
Data: devices,
|
||||
}
|
||||
|
||||
// Send to all connected clients
|
||||
var failedClients []*websocket.Conn
|
||||
|
||||
for client := range app.WSClients {
|
||||
if err := client.WriteJSON(message); err != nil {
|
||||
log.Printf("Failed to send device update to WebSocket client: %v", err)
|
||||
// Mark for removal to avoid modifying map during iteration
|
||||
failedClients = append(failedClients, client)
|
||||
}
|
||||
}
|
||||
|
||||
// Remove failed clients
|
||||
for _, client := range failedClients {
|
||||
delete(app.WSClients, client)
|
||||
client.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// BroadcastDiscoveryStatus sends discovery progress updates to all connected WebSocket clients
|
||||
func (app *WebApp) BroadcastDiscoveryStatus(status string, deviceCount int) {
|
||||
app.WSMutex.RLock()
|
||||
defer app.WSMutex.RUnlock()
|
||||
|
||||
message := webtypes.WebSocketMessage{
|
||||
Type: "discovery_status",
|
||||
Data: map[string]interface{}{
|
||||
"status": status,
|
||||
"deviceCount": deviceCount,
|
||||
},
|
||||
}
|
||||
|
||||
// Send to all connected clients
|
||||
var failedClients []*websocket.Conn
|
||||
|
||||
for client := range app.WSClients {
|
||||
if err := client.WriteJSON(message); err != nil {
|
||||
log.Printf("Failed to send discovery status to WebSocket client: %v", err)
|
||||
// Mark for removal to avoid modifying map during iteration
|
||||
failedClients = append(failedClients, client)
|
||||
}
|
||||
}
|
||||
|
||||
// Remove failed clients
|
||||
for _, client := range failedClients {
|
||||
delete(app.WSClients, client)
|
||||
client.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// HandleTuneInSearch handles TuneIn search requests, proxying directly to the bmx package.
|
||||
func (app *WebApp) HandleTuneInSearch(w http.ResponseWriter, r *http.Request) {
|
||||
query := r.URL.Query().Get("q")
|
||||
if query == "" {
|
||||
app.sendError(w, "query parameter 'q' is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := bmxpkg.TuneInSearch(query)
|
||||
if err != nil {
|
||||
app.sendError(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if encErr := json.NewEncoder(w).Encode(webtypes.APIResponse{Success: true, Data: resp}); encErr != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleTuneInNavigate handles TuneIn browse/navigate requests, proxying directly to the bmx package.
|
||||
// Supported path suffixes (relative to /api/tunein/navigate):
|
||||
// - (empty) → top-level browse
|
||||
// - /{encodedURI} → browse the given TuneIn URI
|
||||
// - /sub/{n}/{encodedURI} → single subsection
|
||||
// - /profiles/{type}/{id}/{encodedURI} → artist/program profile
|
||||
func (app *WebApp) HandleTuneInNavigate(w http.ResponseWriter, r *http.Request) {
|
||||
wildcard := chi.URLParam(r, "*")
|
||||
|
||||
var (
|
||||
resp interface{}
|
||||
err error
|
||||
)
|
||||
|
||||
if wildcard == "" {
|
||||
resp, err = bmxpkg.TuneInNavigate("", nil)
|
||||
} else {
|
||||
firstSlash := strings.Index(wildcard, "/")
|
||||
if firstSlash == -1 {
|
||||
resp, err = bmxpkg.TuneInNavigate(wildcard, nil)
|
||||
} else {
|
||||
pfx := wildcard[:firstSlash]
|
||||
rest := wildcard[firstSlash+1:]
|
||||
|
||||
switch pfx {
|
||||
case "sub":
|
||||
secondSlash := strings.Index(rest, "/")
|
||||
if secondSlash == -1 {
|
||||
resp, err = bmxpkg.TuneInNavigate(rest, nil)
|
||||
} else {
|
||||
n, parseErr := strconv.Atoi(rest[:secondSlash])
|
||||
if parseErr != nil {
|
||||
resp, err = bmxpkg.TuneInNavigate(wildcard, nil)
|
||||
} else {
|
||||
resp, err = bmxpkg.TuneInNavigate(rest[secondSlash+1:], &n)
|
||||
}
|
||||
}
|
||||
case "profiles":
|
||||
parts := strings.SplitN(rest, "/", 3)
|
||||
if len(parts) < 3 {
|
||||
resp, err = bmxpkg.TuneInNavigate(wildcard, nil)
|
||||
} else {
|
||||
resp, err = bmxpkg.TuneInNavigateProfile(parts[2])
|
||||
}
|
||||
default:
|
||||
resp, err = bmxpkg.TuneInNavigate(wildcard, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
app.sendError(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if encErr := json.NewEncoder(w).Encode(webtypes.APIResponse{Success: true, Data: resp}); encErr != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// HandlePlayTuneIn plays a TuneIn content item on a specific device via POST /select.
|
||||
func (app *WebApp) HandlePlayTuneIn(w http.ResponseWriter, r *http.Request) {
|
||||
deviceID := chi.URLParam(r, "id")
|
||||
if deviceID == "" {
|
||||
app.sendError(w, "Device ID required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
device, exists := app.Devices[deviceID]
|
||||
if !exists {
|
||||
app.sendError(w, fmt.Sprintf("Device '%s' not found", deviceID), http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Location string `json:"location"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
ContainerArt string `json:"containerArt"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
app.sendError(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if req.Location == "" {
|
||||
app.sendError(w, "location is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
itemType := req.Type
|
||||
if itemType == "" {
|
||||
itemType = "stationurl"
|
||||
}
|
||||
|
||||
contentItem := &models.ContentItem{
|
||||
Source: "TUNEIN",
|
||||
Type: itemType,
|
||||
Location: req.Location,
|
||||
ItemName: req.Name,
|
||||
IsPresetable: true,
|
||||
ContainerArt: req.ContainerArt,
|
||||
}
|
||||
|
||||
if err := device.Client.SelectContentItem(contentItem); err != nil {
|
||||
app.sendError(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if encErr := json.NewEncoder(w).Encode(webtypes.APIResponse{Success: true, Data: map[string]string{"message": "Playing " + req.Name}}); encErr != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
@@ -2,191 +2,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"flag"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
"os"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/cmd/soundtouch-web/handlers"
|
||||
"github.com/gesellix/bose-soundtouch/cmd/soundtouch-web/webtypes"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/client"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/config"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/discovery"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/soundtouchweb"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
//go:embed static
|
||||
var staticFS embed.FS
|
||||
|
||||
var (
|
||||
port = flag.String("port", "8080", "Web server port")
|
||||
_ = flag.String("host", "", "Specific SoundTouch device host (optional)")
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
// Create web app without templates (SPA mode)
|
||||
app := handlers.NewWebApp()
|
||||
|
||||
// Initialize discovery service
|
||||
cfg, err := config.LoadFromEnv()
|
||||
if err != nil {
|
||||
log.Printf("Failed to load config: %v, using defaults", err)
|
||||
|
||||
cfg = config.DefaultConfig()
|
||||
}
|
||||
|
||||
cfg.DiscoveryTimeout = 10 * time.Second
|
||||
cfg.CacheEnabled = true
|
||||
|
||||
discoveryService := discovery.NewUnifiedDiscoveryService(cfg)
|
||||
|
||||
// Discover devices on startup
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Broadcast discovery start
|
||||
app.BroadcastDiscoveryStatus("starting", len(app.Devices))
|
||||
|
||||
discoverDevices(ctx, app, discoveryService)
|
||||
|
||||
// Broadcast discovery completion and updated device list
|
||||
app.BroadcastDiscoveryStatus("completed", len(app.Devices))
|
||||
app.BroadcastDeviceList()
|
||||
}()
|
||||
|
||||
// Setup HTTP routes
|
||||
r := setupRoutes(app, discoveryService)
|
||||
|
||||
// Start web server
|
||||
log.Printf("SoundTouch Web UI starting on http://0.0.0.0:%s", *port)
|
||||
log.Fatal(http.ListenAndServe(":"+*port, r))
|
||||
}
|
||||
|
||||
func setupRoutes(app *handlers.WebApp, discoveryService *discovery.UnifiedDiscoveryService) *chi.Mux {
|
||||
r := chi.NewRouter()
|
||||
|
||||
// Static assets (embedded in binary)
|
||||
subFS, _ := fs.Sub(staticFS, "static")
|
||||
r.Get("/static/*", http.StripPrefix("/static", http.FileServer(http.FS(subFS))).ServeHTTP)
|
||||
|
||||
// Serve index.html for SPA routes
|
||||
serveIndex := func(w http.ResponseWriter, _ *http.Request) {
|
||||
data, _ := staticFS.ReadFile("static/index.html")
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
// WebSocket endpoint
|
||||
r.Get("/ws", app.HandleWebSocket)
|
||||
|
||||
// API endpoints
|
||||
r.Get("/api/devices", app.HandleAPIDevices)
|
||||
r.Get("/api/device/{id}", app.HandleAPIDevice)
|
||||
r.Post("/api/discover", func(w http.ResponseWriter, r *http.Request) {
|
||||
app.HandleAPIDiscover(w, r)
|
||||
// Trigger discovery
|
||||
//nolint:contextcheck // Context is created within goroutine
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Broadcast discovery start
|
||||
app.BroadcastDiscoveryStatus("starting", len(app.Devices))
|
||||
|
||||
discoverDevices(ctx, app, discoveryService)
|
||||
|
||||
// Broadcast discovery completion and updated device list
|
||||
app.BroadcastDiscoveryStatus("completed", len(app.Devices))
|
||||
app.BroadcastDeviceList()
|
||||
}()
|
||||
})
|
||||
|
||||
// Device control endpoints (GET for most actions, POST for volume/bass)
|
||||
r.Get("/api/control/{id}/{action}", app.HandleAPIControl)
|
||||
r.Post("/api/control/{id}/{action}", app.HandleAPIControl)
|
||||
|
||||
// TuneIn browse, search, and playback
|
||||
r.Get("/api/tunein/search", app.HandleTuneInSearch)
|
||||
r.Get("/api/tunein/navigate", app.HandleTuneInNavigate)
|
||||
r.Get("/api/tunein/navigate/*", app.HandleTuneInNavigate)
|
||||
r.Post("/api/tunein/play/{id}", app.HandlePlayTuneIn)
|
||||
|
||||
// Enhanced device control endpoints
|
||||
r.Post("/api/device-key/{id}/{key}", app.HandleDeviceKey)
|
||||
r.Post("/api/device-volume/{id}/{volume}", app.HandleDirectVolumeControl)
|
||||
r.Post("/api/device-power/{id}", app.HandleDevicePower)
|
||||
r.Get("/api/device-power-status/{id}", app.HandleDevicePowerStatus)
|
||||
r.Get("/api/device-ws/{id}", app.HandleDeviceWebSocket)
|
||||
|
||||
// SPA routes - serve index.html for client-side routing
|
||||
r.Get("/", serveIndex)
|
||||
r.Get("/devices", serveIndex)
|
||||
r.Get("/device/*", serveIndex)
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
func discoverDevices(ctx context.Context, app *handlers.WebApp, discoveryService *discovery.UnifiedDiscoveryService) {
|
||||
log.Println("Starting device discovery...")
|
||||
|
||||
devices, err := discoveryService.DiscoverDevices(ctx)
|
||||
if err != nil {
|
||||
log.Printf("Discovery failed: %v", err)
|
||||
app.BroadcastDiscoveryStatus("failed", len(app.Devices))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Found %d devices", len(devices))
|
||||
|
||||
for _, device := range devices {
|
||||
deviceID := device.Host // Use host as unique ID for now
|
||||
|
||||
// Skip if we already have this device
|
||||
if _, exists := app.Devices[deviceID]; exists {
|
||||
app.Devices[deviceID].LastSeen = time.Now()
|
||||
continue
|
||||
}
|
||||
|
||||
// Create new device connection
|
||||
clientConfig := &client.Config{
|
||||
Host: device.Host,
|
||||
Port: device.Port,
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
soundTouchClient := client.NewClient(clientConfig)
|
||||
|
||||
// Get device info
|
||||
deviceInfo, err := soundTouchClient.GetDeviceInfo()
|
||||
if err != nil {
|
||||
log.Printf("Failed to get device info for %s: %v", device.Host, err)
|
||||
continue
|
||||
}
|
||||
|
||||
// Create device connection
|
||||
conn := &webtypes.DeviceConnection{
|
||||
Client: soundTouchClient,
|
||||
DeviceInfo: deviceInfo,
|
||||
LastSeen: time.Now(),
|
||||
Status: webtypes.DeviceStatus{
|
||||
IsConnected: false,
|
||||
LastActivity: time.Now(),
|
||||
app := &cli.App{
|
||||
Name: "soundtouch-web",
|
||||
Usage: "Web UI for controlling Bose SoundTouch devices",
|
||||
Flags: []cli.Flag{
|
||||
&cli.StringFlag{
|
||||
Name: "port",
|
||||
Aliases: []string{"p"},
|
||||
Usage: "HTTP port to listen on",
|
||||
Value: "8080",
|
||||
EnvVars: []string{"PORT"},
|
||||
},
|
||||
}
|
||||
&cli.StringFlag{
|
||||
Name: "bind",
|
||||
Usage: "Network interface to bind to",
|
||||
EnvVars: []string{"BIND_ADDR"},
|
||||
},
|
||||
},
|
||||
Action: func(c *cli.Context) error {
|
||||
port := c.String("port")
|
||||
bindAddr := c.String("bind")
|
||||
|
||||
// Initial status fetch asynchronously to avoid blocking discovery
|
||||
go app.UpdateDeviceStatus(deviceID, conn)
|
||||
addr := ":" + port
|
||||
if bindAddr != "" {
|
||||
addr = bindAddr + ":" + port
|
||||
}
|
||||
|
||||
app.Devices[deviceID] = conn
|
||||
webApp := soundtouchweb.New()
|
||||
|
||||
log.Printf("Added device: %s (%s) at %s", deviceInfo.Name, deviceInfo.Type, device.Host)
|
||||
r := chi.NewRouter()
|
||||
webApp.Mount(r)
|
||||
|
||||
log.Printf("SoundTouch Web UI starting on http://%s", addr)
|
||||
|
||||
return http.ListenAndServe(addr, r)
|
||||
},
|
||||
}
|
||||
|
||||
if err := app.Run(os.Args); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,9 +9,9 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/cmd/soundtouch-web/handlers"
|
||||
"github.com/gesellix/bose-soundtouch/cmd/soundtouch-web/webtypes"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/soundtouchweb"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/soundtouchweb/webtypes"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
@@ -55,22 +55,19 @@ func TestSPARouting(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", tt.path, nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
// Simulate SPA routing handler
|
||||
spaHandler := func(w http.ResponseWriter, r *http.Request) {
|
||||
// If it's an API route, let it pass through
|
||||
if strings.HasPrefix(r.URL.Path, "/api/") || strings.HasPrefix(r.URL.Path, "/static/") || strings.HasPrefix(r.URL.Path, "/ws") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// Serve the SPA index.html content (simulated)
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>SoundTouch Control Center</title>
|
||||
<title>SoundTouch Web</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">SPA Content</div>
|
||||
@@ -100,7 +97,7 @@ func TestSPARouting(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAPIEndpoints(t *testing.T) {
|
||||
app := handlers.NewWebApp()
|
||||
app := soundtouchweb.NewWebApp()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -127,7 +124,7 @@ func TestAPIEndpoints(t *testing.T) {
|
||||
name: "device API with ID",
|
||||
path: "/api/device/test-device",
|
||||
method: "GET",
|
||||
expectedStatus: http.StatusNotFound, // Device won't exist in test
|
||||
expectedStatus: http.StatusNotFound,
|
||||
expectedJSON: true,
|
||||
},
|
||||
}
|
||||
@@ -160,7 +157,6 @@ func TestAPIEndpoints(t *testing.T) {
|
||||
t.Errorf("Expected JSON content type, got %s", contentType)
|
||||
}
|
||||
|
||||
// Validate JSON response structure
|
||||
var response webtypes.APIResponse
|
||||
if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
|
||||
t.Errorf("Invalid JSON response: %v", err)
|
||||
@@ -171,7 +167,7 @@ func TestAPIEndpoints(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAPIResponseFormat(t *testing.T) {
|
||||
app := handlers.NewWebApp()
|
||||
app := soundtouchweb.NewWebApp()
|
||||
|
||||
req := httptest.NewRequest("GET", "/api/devices", nil)
|
||||
w := httptest.NewRecorder()
|
||||
@@ -183,7 +179,6 @@ func TestAPIResponseFormat(t *testing.T) {
|
||||
t.Fatalf("Failed to decode JSON response: %v", err)
|
||||
}
|
||||
|
||||
// Check API response structure
|
||||
if !response.Success {
|
||||
t.Errorf("Expected success=true, got success=%v", response.Success)
|
||||
}
|
||||
@@ -192,7 +187,6 @@ func TestAPIResponseFormat(t *testing.T) {
|
||||
t.Errorf("Expected data field to be present")
|
||||
}
|
||||
|
||||
// Data should be an empty map for no devices
|
||||
dataMap, ok := response.Data.(map[string]interface{})
|
||||
if !ok {
|
||||
t.Errorf("Expected data to be a map, got %T", response.Data)
|
||||
@@ -204,7 +198,7 @@ func TestAPIResponseFormat(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestControlAPIValidation(t *testing.T) {
|
||||
app := handlers.NewWebApp()
|
||||
app := soundtouchweb.NewWebApp()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -249,7 +243,6 @@ func TestControlAPIValidation(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
// Add a mock device for testing unknown action validation
|
||||
mockDevice := &webtypes.DeviceConnection{
|
||||
Client: nil,
|
||||
DeviceInfo: &models.DeviceInfo{Name: "Test Device"},
|
||||
@@ -278,7 +271,6 @@ func TestControlAPIValidation(t *testing.T) {
|
||||
t.Errorf("Test %s: Expected status %d, got %d. Response: %s", tt.name, tt.expectedStatus, w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
// Validate error response format
|
||||
contentType := w.Header().Get("Content-Type")
|
||||
if !strings.Contains(contentType, "application/json") {
|
||||
t.Errorf("Expected JSON content type, got %s", contentType)
|
||||
@@ -301,9 +293,8 @@ func TestControlAPIValidation(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestWebSocketUpgrade(t *testing.T) {
|
||||
app := handlers.NewWebApp()
|
||||
app := soundtouchweb.NewWebApp()
|
||||
|
||||
// Test WebSocket upgrade request
|
||||
req := httptest.NewRequest("GET", "/ws", nil)
|
||||
req.Header.Set("Connection", "upgrade")
|
||||
req.Header.Set("Upgrade", "websocket")
|
||||
@@ -312,16 +303,11 @@ func TestWebSocketUpgrade(t *testing.T) {
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
// The actual WebSocket upgrade will fail in test environment,
|
||||
// but we can check that the handler exists and accepts the request
|
||||
app.HandleWebSocket(w, req)
|
||||
|
||||
// In a real test environment, this would fail with a websocket upgrade error
|
||||
// We're just checking the handler doesn't panic and processes the request
|
||||
}
|
||||
|
||||
func TestJSONAPIConsistency(t *testing.T) {
|
||||
app := handlers.NewWebApp()
|
||||
app := soundtouchweb.NewWebApp()
|
||||
|
||||
endpoints := []string{
|
||||
"/api/devices",
|
||||
@@ -344,19 +330,16 @@ func TestJSONAPIConsistency(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// All API endpoints should return JSON
|
||||
contentType := w.Header().Get("Content-Type")
|
||||
if !strings.Contains(contentType, "application/json") {
|
||||
t.Errorf("Endpoint %s should return JSON, got %s", endpoint, contentType)
|
||||
}
|
||||
|
||||
// All responses should follow APIResponse structure
|
||||
var response webtypes.APIResponse
|
||||
if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
|
||||
t.Errorf("Endpoint %s returned invalid JSON: %v", endpoint, err)
|
||||
}
|
||||
|
||||
// Response should have either data or error
|
||||
if response.Success && response.Data == nil {
|
||||
t.Errorf("Endpoint %s: success response should have data", endpoint)
|
||||
}
|
||||
|
||||
@@ -1,200 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>SoundTouch Control Center</title>
|
||||
<link
|
||||
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link
|
||||
href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link href="/static/css/app.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<nav class="navbar navbar-expand-lg navbar-dark">
|
||||
<div class="container">
|
||||
<a class="navbar-brand" href="#" onclick="showPage('devices')">
|
||||
<i class="bi bi-speaker"></i>
|
||||
SoundTouch Control
|
||||
</a>
|
||||
<div class="navbar-nav ms-auto">
|
||||
<a
|
||||
class="nav-link"
|
||||
href="#"
|
||||
onclick="showPage('devices')"
|
||||
title="Home"
|
||||
>
|
||||
<i class="bi bi-house"></i>
|
||||
</a>
|
||||
<a
|
||||
class="nav-link tunein-nav-link"
|
||||
href="#"
|
||||
onclick="showPage('tunein')"
|
||||
title="TuneIn Browse"
|
||||
>
|
||||
<img
|
||||
src="/static/img/tunein-mono.svg"
|
||||
alt="TuneIn"
|
||||
class="tunein-nav-icon"
|
||||
/>
|
||||
</a>
|
||||
<a
|
||||
class="nav-link"
|
||||
href="#"
|
||||
onclick="discoverDevices()"
|
||||
title="Discover Devices"
|
||||
>
|
||||
<i class="bi bi-search"></i>
|
||||
</a>
|
||||
<button
|
||||
class="theme-toggle nav-link"
|
||||
onclick="toggleTheme()"
|
||||
title="Toggle Dark Mode"
|
||||
>
|
||||
<i id="theme-icon" class="bi bi-moon"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="container mt-4">
|
||||
<!-- Device List Page -->
|
||||
<div id="devices-page" class="page active">
|
||||
<div
|
||||
class="d-flex justify-content-between align-items-center mb-4"
|
||||
>
|
||||
<h2>Your SoundTouch Devices</h2>
|
||||
<button class="btn btn-primary" onclick="discoverDevices()">
|
||||
<i class="bi bi-search"></i>
|
||||
Discover Devices
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="devices-loading" class="loading-spinner"></div>
|
||||
|
||||
<div id="devices-list" class="row">
|
||||
<!-- Device cards will be inserted here by JavaScript -->
|
||||
</div>
|
||||
|
||||
<div
|
||||
id="no-devices"
|
||||
style="display: none"
|
||||
class="text-center py-5"
|
||||
>
|
||||
<i class="bi bi-speaker display-1 text-muted"></i>
|
||||
<h4 class="mt-3">No Devices Found</h4>
|
||||
<p class="text-muted">
|
||||
Click "Discover Devices" to search for SoundTouch
|
||||
speakers on your network.
|
||||
</p>
|
||||
<button class="btn btn-primary" onclick="discoverDevices()">
|
||||
<i class="bi bi-search"></i>
|
||||
Start Discovery
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- TuneIn Browse Page -->
|
||||
<div id="tunein-page" class="page">
|
||||
<div class="d-flex justify-content-between align-items-center mb-3">
|
||||
<h2><img src="/static/img/tunein-dark.svg" alt="TuneIn" class="tunein-heading-icon me-2" />TuneIn Browse</h2>
|
||||
</div>
|
||||
|
||||
<div class="tunein-search-bar mb-3">
|
||||
<div class="input-group">
|
||||
<input
|
||||
type="text"
|
||||
id="tunein-search-input"
|
||||
class="form-control"
|
||||
placeholder="Search stations, podcasts..."
|
||||
/>
|
||||
<button
|
||||
class="btn btn-primary"
|
||||
onclick="tuneInSearch(document.getElementById('tunein-search-input').value)"
|
||||
>
|
||||
<i class="bi bi-search"></i>
|
||||
Search
|
||||
</button>
|
||||
<button
|
||||
class="btn btn-outline-secondary"
|
||||
onclick="tuneInBrowse()"
|
||||
title="Browse top level"
|
||||
>
|
||||
<i class="bi bi-house"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav id="tunein-breadcrumb" class="mb-3" style="display: none">
|
||||
<!-- filled by JavaScript -->
|
||||
</nav>
|
||||
|
||||
<div id="tunein-results">
|
||||
<!-- filled by JavaScript -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Device Control Page -->
|
||||
<div id="device-page" class="page">
|
||||
<div class="back-button">
|
||||
<button
|
||||
class="btn btn-outline-secondary"
|
||||
onclick="showPage('devices')"
|
||||
>
|
||||
<i class="bi bi-arrow-left"></i>
|
||||
Back to Devices
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="device-content">
|
||||
<!-- Device control content will be inserted here by JavaScript -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer class="footer">
|
||||
<div class="container text-center">
|
||||
<small>
|
||||
SoundTouch Web Control Interface -
|
||||
<a
|
||||
href="https://github.com/gesellix/Bose-SoundTouch"
|
||||
target="_blank"
|
||||
class="text-decoration-none"
|
||||
>
|
||||
Open Source Project
|
||||
</a>
|
||||
</small>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<!-- Toast container for notifications -->
|
||||
<div class="toast-container"></div>
|
||||
|
||||
<!-- Device picker for TuneIn playback -->
|
||||
<div class="modal fade" id="devicePickerModal" tabindex="-1" aria-labelledby="devicePickerLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-sm">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header py-2">
|
||||
<h6 class="modal-title" id="devicePickerLabel">
|
||||
<i class="bi bi-speaker me-2"></i>Play on device
|
||||
</h6>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body p-2" id="devicePickerList">
|
||||
<!-- device buttons filled by JavaScript -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bootstrap JS -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
||||
|
||||
<!-- Application JavaScript -->
|
||||
<script src="/static/js/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,4 +1,5 @@
|
||||
accounts/
|
||||
backend/
|
||||
certs/
|
||||
default/
|
||||
dns/
|
||||
|
||||
@@ -3,6 +3,8 @@ services:
|
||||
build:
|
||||
context: .
|
||||
target: soundtouch-service
|
||||
networks:
|
||||
- soundtouch-test-net
|
||||
volumes:
|
||||
- ./tests/integration/testdata:/app/data
|
||||
environment:
|
||||
@@ -10,3 +12,35 @@ services:
|
||||
- SPOTIFY_CLIENT_SECRET=mock-secret
|
||||
- SPOTIFY_TOKEN_URL=http://spotify-mock:8080/api/token
|
||||
- SPOTIFY_API_BASE=http://spotify-mock:8080
|
||||
- AMAZON_CLIENT_ID=mock-amazon-id
|
||||
- AMAZON_CLIENT_SECRET=mock-amazon-secret
|
||||
- AMAZON_TOKEN_URL=http://amazon-mock:8080/auth/o2/token
|
||||
- AMAZON_PROFILE_URL=http://amazon-mock:8080/user/profile
|
||||
|
||||
spotify-mock:
|
||||
image: golang:1.26.3-alpine
|
||||
container_name: spotify-mock
|
||||
working_dir: /app
|
||||
volumes:
|
||||
- .:/app
|
||||
command: go run ./cmd/mock-spotify/main.go -port 8080
|
||||
ports:
|
||||
- "8081:8080"
|
||||
networks:
|
||||
- soundtouch-test-net
|
||||
|
||||
amazon-mock:
|
||||
image: golang:1.26.3-alpine
|
||||
container_name: amazon-mock
|
||||
working_dir: /app
|
||||
volumes:
|
||||
- .:/app
|
||||
command: go run ./cmd/mock-amazon/main.go -port 8080
|
||||
ports:
|
||||
- "8082:8080"
|
||||
networks:
|
||||
- soundtouch-test-net
|
||||
|
||||
networks:
|
||||
soundtouch-test-net:
|
||||
name: soundtouch-test-net
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
services:
|
||||
soundtouch-service:
|
||||
image: ghcr.io/gesellix/bose-soundtouch:latest
|
||||
image: ghcr.io/gesellix/bose-soundtouch:${SOUNDTOUCH_VERSION:-latest}
|
||||
# build: .
|
||||
container_name: soundtouch-service
|
||||
# Linux only, required for discovery. Swarm requires host network at the task level.
|
||||
@@ -8,8 +8,6 @@ services:
|
||||
ports:
|
||||
- "8000:8000"
|
||||
- "8443:8443"
|
||||
networks:
|
||||
- soundtouch-test-net
|
||||
environment:
|
||||
- PORT=8000
|
||||
- HTTPS_PORT=8443
|
||||
@@ -37,22 +35,6 @@ services:
|
||||
cpus: '0.25'
|
||||
memory: 128M
|
||||
|
||||
spotify-mock:
|
||||
image: golang:1.26.2-alpine
|
||||
container_name: spotify-mock
|
||||
working_dir: /app
|
||||
volumes:
|
||||
- .:/app
|
||||
command: go run ./cmd/mock-spotify/main.go -port 8080
|
||||
ports:
|
||||
- "8081:8080"
|
||||
networks:
|
||||
- soundtouch-test-net
|
||||
|
||||
networks:
|
||||
soundtouch-test-net:
|
||||
name: soundtouch-test-net
|
||||
|
||||
volumes:
|
||||
soundtouch-data:
|
||||
# Named volumes are preferred in Swarm. For multi-node persistence,
|
||||
|
||||
@@ -8,34 +8,50 @@ This document provides a comparative analysis of the current Go implementation a
|
||||
|
||||
## 2. Functional Comparison
|
||||
|
||||
| Feature | Bose-SoundTouch (Go) | SoundCork (Python) |
|
||||
|:---------------------|:-------------------------------------------------|:----------------------------------------------------------------------------------------|
|
||||
| **Group Management** | Placeholder handlers (return `<group/>` or 404). | Active group management (`groups.py`), supporting `/addGroup` and stereo pairing logic. |
|
||||
| **BMX Services** | Supports TuneIn, Orion, and custom streams. | More modular `bmx_services.json` registry with broader mock support. |
|
||||
| **Persistence** | Mixed JSON/XML datastore. | Pure XML-based persistence per device/account. |
|
||||
| **Admin UI** | CLI-based (`soundtouch-cli`) or API-driven. | Draft Web UI for device discovery and account management (`admin.py`). |
|
||||
| **Discovery** | Integrated setup tools and SSDP/MDNS awareness. | Leverages `bosesoundtouchapi` Python library for active discovery. |
|
||||
| Feature | Bose-SoundTouch (Go) | SoundCork (Python) |
|
||||
|:---------------------|:----------------------------------------------------------------------------------------------------------------------|:----------------------------------------------------------------------------------------|
|
||||
| **Group Management** | Full CRUD: `POST /group`, `POST /group/{id}`, `DELETE /group/{id}` with XML datastore persistence (`Group_{id}.xml`). | Active group management (`groups.py`), supporting `/addGroup` and stereo pairing logic. |
|
||||
| **ZeroConf Priming** | Full DH key exchange + encrypted blob; fallback to `tokenType=accesstoken` for older firmware. | Simple `tokenType=accesstoken` push only; token expires after ~60 minutes. |
|
||||
| **BMX Services** | Supports TuneIn, Orion, and custom streams. | More modular `bmx_services.json` registry with broader mock support. |
|
||||
| **Persistence** | Mixed JSON/XML datastore. | Pure XML-based persistence per device/account. |
|
||||
| **Admin UI** | CLI-based (`soundtouch-cli`) or API-driven. | Draft Web UI for device discovery and account management (`admin.py`). |
|
||||
| **Discovery** | Integrated setup tools and SSDP/MDNS awareness. | Leverages `bosesoundtouchapi` Python library for active discovery. |
|
||||
|
||||
## 3. Key Strengths of SoundCork
|
||||
- **Group Pairing Logic**: Includes logic to manage master/slave relationships for SoundTouch 10 stereo pairs.
|
||||
- **Service Extensibility**: JSON-based registry for BMX services makes it easier to mock multiple providers (SiriusXM, Spotify) without code changes.
|
||||
- **Mock Coverage**: Better coverage of "dummy" endpoints that respond with plausible XML (e.g., `customerSupport`).
|
||||
- ~~**Mock Coverage**: Better coverage of "dummy" endpoints that respond with plausible XML (e.g., `customerSupport`).~~ **Addressed**: AfterTouch's `HandleNotFound` (registered via `r.NotFound`) logs every unimplemented endpoint as `[UNHANDLED]` and forwards the request to the Bose upstream via `HandleBoseProxy`. This provides at least the same coverage as static dummy responses, while also aiding discovery of new endpoints.
|
||||
|
||||
## 4. Suggested Implementation Steps for Bose-SoundTouch
|
||||
|
||||
### A. Implement Full Group Support (High Priority)
|
||||
- Add logic to `pkg/service/marge` to handle `/addGroup` and `/updateGroup`.
|
||||
- Persist group memberships in the datastore to allow speakers to function as stereo pairs or multi-room zones.
|
||||
### ✅ A. Implement Full Group Support (Completed)
|
||||
- `POST /group`, `POST /group/{id}`, `DELETE /group/{id}` implemented in `pkg/service/handlers/handlers_marge.go`.
|
||||
- Group CRUD persisted in XML datastore (`Group_{id}.xml`) via `pkg/service/datastore/datastore.go`.
|
||||
- `GET /group` on device registration reads the group the device belongs to.
|
||||
|
||||
### B. Modularize BMX Registry (Medium Priority)
|
||||
### ✅ B. Proper ZeroConf Spotify Blob (Completed)
|
||||
- Full Spotify Connect ZeroConf protocol implemented in `pkg/service/spotify/zeroconf.go`.
|
||||
- Flow: `getInfo` (fetch speaker DH public key) → 768-bit DH key exchange → AES-128-CTR encrypted `LoginCredentials` protobuf blob → `addUser`.
|
||||
- Speaker can self-refresh credentials independently; no periodic re-priming needed for token expiry.
|
||||
- Automatic fallback to `tokenType=accesstoken` if `getInfo` fails (older firmware without DH support).
|
||||
- See `docs/concepts/spotify-priming-strategy.md` for full protocol details.
|
||||
- **Remaining gap**: Background watchdog to re-prime devices that lose their session (reboot / power loss). Not required for token expiry on modern firmware; only needed for the "speaker rebooted and lost state" recovery path and for older firmware on the fallback path (~45 min token expiry).
|
||||
|
||||
### C. Modularize BMX Registry (Medium Priority)
|
||||
- Extract the hardcoded service list in `HandleBMXRegistry` into an external `bmx-services.json` file.
|
||||
- Allow users to customize which mocked services are advertised to the speaker.
|
||||
|
||||
### C. Enhanced Source Management (Medium Priority)
|
||||
### D. Enhanced Source Management (Medium Priority)
|
||||
- Refine source learning logic to ensure all `sourceAccount` and `sourceName` metadata is correctly captured during synchronization, using patterns from `soundcork`'s `learnSource`.
|
||||
|
||||
### D. Basic Admin Web UI (Low Priority)
|
||||
### E. Basic Admin Web UI (Low Priority)
|
||||
- Develop a minimal internal status page to list active accounts and connected devices, improving usability over raw API calls.
|
||||
|
||||
## 5. Summary
|
||||
While our Go implementation is structurally more consistent with recent reference recordings (e.g., `buttonNumber`, detailed `components`), SoundCork provides better coverage of multi-device coordination (Groups) and service emulation (BMX) that we should adopt for a more complete offline experience.
|
||||
|
||||
Group support and ZeroConf Spotify priming are now feature-complete in AfterTouch. The Go implementation is structurally more consistent with recent reference recordings (e.g., `buttonNumber`, detailed `components`). SoundCork's remaining functional advantages are:
|
||||
|
||||
- **BMX service extensibility**: the `bmx_services.json` registry makes it trivial to add or mock new streaming providers without code changes (step C above).
|
||||
- **Group pairing logic**: master/slave relationship management for SoundTouch 10 stereo pairs goes beyond the CRUD AfterTouch implements.
|
||||
|
||||
For the broader ecosystem context (feature matrix across all community projects, AfterTouch open tasks, and cross-project observations) see [docs/analysis/bose-soundtouch-community-tools.md](analysis/bose-soundtouch-community-tools.md).
|
||||
|
||||
@@ -10,6 +10,7 @@ Welcome to the documentation for the Bose SoundTouch Toolkit. This comprehensive
|
||||
|
||||
### For Existing Users
|
||||
- **[Cloud Shutdown Survival Guide](guides/SURVIVAL-GUIDE.md)** - Prepare for the May 2026 shutdown
|
||||
- **[Backup Tool](../cmd/soundtouch-backup/README.md)** - Back up your cloud account and speaker data before shutdown
|
||||
- **[SoundTouch Service Guide](guides/SOUNDTOUCH-SERVICE.md)** - Advanced service configuration
|
||||
|
||||
## 📋 Essential Documentation
|
||||
@@ -40,6 +41,7 @@ The documentation is organized into three main categories:
|
||||
### Advanced Features
|
||||
- [MAC Address Mapping](guides/MAC-ADDRESS-MAPPING.md) - Device identification
|
||||
- [CLI Reference](guides/CLI-REFERENCE.md) - Command-line tools
|
||||
- [Backup Tool](../cmd/soundtouch-backup/README.md) - Cloud account and speaker data backup
|
||||
- [IoT Implementation Guide](guides/IOT-IMPLEMENTATION-GUIDE.md) - IoT integrations
|
||||
- [MQTT Integration Design](guides/MQTT-INTEGRATION-DESIGN.md) - MQTT setup
|
||||
|
||||
|
||||
@@ -4,11 +4,16 @@
|
||||
|
||||
## User Guides
|
||||
* [Cloud Shutdown Survival Guide](guides/SURVIVAL-GUIDE.md)
|
||||
* [Self-Hosting AfterTouch](guides/SELF-HOSTING.md)
|
||||
* [Connecting Music Services](guides/MUSIC-SERVICES.md)
|
||||
* [Migration & Safety Guide](guides/MIGRATION-SAFETY.md)
|
||||
* [CLI Reference](guides/CLI-REFERENCE.md)
|
||||
* [Backup Tool](../cmd/soundtouch-backup/README.md)
|
||||
* [Getting Started](guides/GETTING-STARTED.md)
|
||||
* [SoundTouch Service](guides/SOUNDTOUCH-SERVICE.md)
|
||||
* [Initial Device Setup](guides/DEVICE-INITIAL-SETUP.md)
|
||||
* [Capture Device Pairing Traffic](guides/CAPTURE-DEVICE-PAIRING.md)
|
||||
* [Capture Migration Traffic](guides/CAPTURE-MIGRATION-TRAFFIC.md)
|
||||
* [Device Setup Flow](DEVICE-SETUP.md)
|
||||
* [MAC Address Mapping](guides/MAC-ADDRESS-MAPPING.md)
|
||||
* [HTTPS Setup](guides/HTTPS-SETUP.md)
|
||||
@@ -34,6 +39,7 @@
|
||||
* [System Endpoints](reference/SYSTEM-ENDPOINTS.md)
|
||||
* [Speaker Endpoint](reference/SPEAKER-ENDPOINT.md)
|
||||
* [WebSocket Events](reference/WEBSOCKET-EVENTS.md)
|
||||
* [Device Pairing Flow](reference/DEVICE-PAIRING-FLOW.md)
|
||||
* [Discovery](reference/DISCOVERY.md)
|
||||
* [Zone Management](reference/ZONE-MANAGEMENT.md)
|
||||
* [Preset Management](reference/PRESET-MANAGEMENT.md)
|
||||
@@ -61,6 +67,7 @@
|
||||
* [Bose Lab Runbook](analysis/BOSE-LAB-RUNBOOK.md)
|
||||
* [Missing Routes Spotify](analysis/MISSING-ROUTES-SPOTIFY.md)
|
||||
* [Bose App ADB Emulator](analysis/BOSE-APP-ADB-Emulator.md)
|
||||
* [Community Tools](analysis/bose-soundtouch-community-tools.md)
|
||||
|
||||
## Parity Analysis
|
||||
* [Parity Improvements](PARITY-IMPROVEMENTS.md)
|
||||
|
||||
@@ -2,6 +2,21 @@
|
||||
|
||||
Intercept HTTPS/WebSocket traffic from the Bose SoundTouch Android app using an Android emulator, mitmproxy, and Frida. Tested on Apple Silicon (ARM64) Mac.
|
||||
|
||||
## Automated Setup
|
||||
|
||||
The steps in this document are scripted for reproducibility:
|
||||
|
||||
```bash
|
||||
scripts/android/setup-mitm-avd.sh # one-time: create AVD, install cert & APK, save snapshot
|
||||
scripts/android/start-mitm-session.sh # per-session: restore snapshot, refresh proxy, start frida-server
|
||||
```
|
||||
|
||||
Read on for the full manual walkthrough and the rationale behind each step.
|
||||
|
||||
> **Note:** The manual steps below use `/tmp/` for intermediate files and reflect the original approach. The automated scripts supersede them — use the scripts for day-to-day use and refer here only to understand how things work.
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Android Studio installed (for SDK tools and emulator)
|
||||
@@ -9,6 +24,10 @@ Intercept HTTPS/WebSocket traffic from the Bose SoundTouch Android app using an
|
||||
- mitmproxy installed (`pip install mitmproxy` or via your preferred method)
|
||||
- The Bose SoundTouch APK (extracted from a real device, see below)
|
||||
|
||||
> **BLE limitation**: Android emulators do not expose Bluetooth hardware. The Bose app's default setup path (BLE Wi-Fi provisioning) therefore cannot be used to configure a factory-reset speaker from the emulator. Use **AP mode** instead: provision the speaker's Wi-Fi credentials via the Mac command line first (see [DEVICE-INITIAL-SETUP.md § 6](../guides/DEVICE-INITIAL-SETUP.md)), then the app can discover the already-networked speaker via mDNS/SSDP without BLE.
|
||||
|
||||
> **Emulator ↔ local network**: The emulator routes all traffic through the Mac's active network interface. Once the speaker is on the same LAN as the Mac, the emulator can reach it at its normal LAN IP (e.g. `192.168.1.50`) — no extra routing is needed. Use `adb shell ping 192.168.1.50` to confirm reachability.
|
||||
|
||||
Add Android SDK tools to your PATH (add to `~/.zshrc`):
|
||||
|
||||
```bash
|
||||
@@ -89,7 +108,8 @@ adb -s emulator-5554 install bose.apk
|
||||
|
||||
```bash
|
||||
# Start mitmproxy (generates CA cert on first run)
|
||||
mitmweb --port 8080 --mode regular -w bose_traffic.mitm
|
||||
# Use the native macOS app — Docker mitmproxy does not work (NAT blocks emulator traffic)
|
||||
mitmweb --listen-port 8080 --mode regular -w bose_traffic.mitm
|
||||
```
|
||||
|
||||
Extract the CA certificate (without private key):
|
||||
@@ -214,16 +234,19 @@ grep -A3 "CERT_PEM" /tmp/config.js | head -5
|
||||
Make sure mitmweb is running, then:
|
||||
|
||||
```bash
|
||||
/tmp/frida-venv/bin/frida \
|
||||
scripts/android/frida-venv/bin/frida \
|
||||
-U \
|
||||
-f com.bose.soundtouch \
|
||||
-l /tmp/config.js \
|
||||
-l /tmp/android-system-certificate-injection.js \
|
||||
-l /tmp/android-proxy-override.js \
|
||||
-l /tmp/android-certificate-unpinning.js \
|
||||
-l /tmp/android-certificate-unpinning-fallback.js
|
||||
-l scripts/android/frida/config.js \
|
||||
-l scripts/android/frida/native-connect-hook.js \
|
||||
-l scripts/android/frida/android/android-system-certificate-injection.js \
|
||||
-l scripts/android/frida/android/android-proxy-override.js \
|
||||
-l scripts/android/frida/android/android-certificate-unpinning.js \
|
||||
-l scripts/android/frida/android/android-certificate-unpinning-fallback.js
|
||||
```
|
||||
|
||||
> `native-connect-hook.js` is required — the Bose app uses native networking that bypasses Java proxy settings.
|
||||
|
||||
Expected output in the Frida REPL:
|
||||
|
||||
```
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
# Bose SoundTouch — Community Tools for Post-EOL Preservation
|
||||
|
||||
> **Context:** Bose announced the shutdown of SoundTouch cloud services, extended to **May 6, 2026**. On that date the official SoundTouch app will update to a local-only version. Bose has released the [SoundTouch Web API documentation](https://assets.bosecreative.com/m/496577402d128874/original/SoundTouch-Web-API.pdf) as open-source to enable community-driven development. This document surveys the active community projects, their feature coverage, and open development opportunities.
|
||||
|
||||
---
|
||||
|
||||
## What Bose Is Doing
|
||||
|
||||
After the May 6, 2026 shutdown, the following will **continue to work**:
|
||||
|
||||
- Streaming via Bluetooth, AirPlay, Spotify Connect, and AUX
|
||||
- Local device control and grouping via an updated SoundTouch app
|
||||
- Remote control features (play, pause, skip, volume)
|
||||
- HDMI/optical connections on soundbars
|
||||
|
||||
The following will **stop working**:
|
||||
|
||||
- Physical and app-based presets
|
||||
- In-app music service browsing (TuneIn, Pandora, etc.)
|
||||
- Stereo pairing for SoundTouch 10
|
||||
- Security and firmware updates
|
||||
|
||||
---
|
||||
|
||||
## Community Projects
|
||||
|
||||
### 1. soundcork
|
||||
**[github.com/deborahgu/soundcork](https://github.com/deborahgu/soundcork)**
|
||||
| | |
|
||||
|---|---|
|
||||
| Language | Python |
|
||||
| License | MIT |
|
||||
| Stars | 111 |
|
||||
| Contributors | 8 |
|
||||
| Commits | 287 |
|
||||
| Status | Pre-alpha, actively developed |
|
||||
|
||||
A reverse-engineered intercept API that replaces the Bose cloud servers locally. Works by redirecting the speaker's internal `SoundTouchSdkPrivateCfg.xml` to a self-hosted FastAPI server, emulating the `marge` server (required for basic network functionality) and the `bmx` server (required for TuneIn). Deployable as a Docker container or systemd daemon. The most community-engaged project, with a dedicated discussion thread tracking Bose cloud service status.
|
||||
|
||||
---
|
||||
|
||||
### 2. Überböse API
|
||||
**[github.com/julius-d/ueberboese-api](https://github.com/julius-d/ueberboese-api)**
|
||||
| | |
|
||||
|---|---|
|
||||
| Language | Java (Spring Boot) |
|
||||
| License | MIT |
|
||||
| Stars | 10 |
|
||||
| Contributors | 1 |
|
||||
| Commits | 224 |
|
||||
| Tags/Releases | 163 |
|
||||
| Documentation | [julius-d.github.io/ueberboese-api](https://julius-d.github.io/ueberboese-api/) |
|
||||
|
||||
Reverse-engineers and rebuilds the Bose streaming HTTP API. Unique in publishing a machine-readable OpenAPI specification (`ueberboese-api.yaml`) and comprehensive request logging — making it the best research instrument for understanding what speakers actually call upstream. Implements Spotify OAuth integration and TuneIn. Companion to the Überböse App.
|
||||
|
||||
---
|
||||
|
||||
### 3. Überböse App
|
||||
**[github.com/julius-d/ueberboese-app](https://github.com/julius-d/ueberboese-app)**
|
||||
| | |
|
||||
|---|---|
|
||||
| Language | Flutter (Dart) |
|
||||
| License | MIT |
|
||||
| Latest version | 0.26.0 (March 2026) |
|
||||
| Distribution | [F-Droid](https://f-droid.org/en/packages/io.github.juliusd.ueberboese.app/) |
|
||||
| Platform | Android |
|
||||
|
||||
The only native installable phone app in the ecosystem. Pairs with the Überböse API server. Features: preset view/play/reprogram, multi-room zone management, volume control, now-playing display, Spotify authentication setup. Controls speakers directly via the local SoundTouch WebServices API (no server required for basic control).
|
||||
|
||||
---
|
||||
|
||||
### 4. SoundTouch Hybrid 2026
|
||||
**[github.com/TJGigs/Bose-SoundTouch-Hybrid-2026](https://github.com/TJGigs/Bose-SoundTouch-Hybrid-2026)**
|
||||
| | |
|
||||
|---|---|
|
||||
| Language | Node.js (JavaScript) |
|
||||
| License | — |
|
||||
| Stars | 1 |
|
||||
| Commits | 3 (V1) / 12 (V3) |
|
||||
| Status | Experimental / testing |
|
||||
|
||||
A self-hosted private cloud that emulates and replaces the Bose Cloud Service. Runs locally on a NAS or PC, intercepts the complex server handshakes needed to keep the SoundTouch infrastructure functional. Relies on **Music Assistant** for backend audio routing and provider aggregation. Features a setup wizard including USB config generation (`OverrideSdkPrivateCfg.xml`) and an on-screen Bose Cloud Emulation Setup guide. Targets users who want the broadest streaming provider support via Music Assistant's ecosystem.
|
||||
|
||||
---
|
||||
|
||||
### 5. OpenCloudTouch (OCT)
|
||||
**[github.com/scheilch/opencloudtouch](https://github.com/scheilch/opencloudtouch)**
|
||||
| | |
|
||||
|---|---|
|
||||
| Language | Python (FastAPI) + TypeScript (React) |
|
||||
| License | Apache 2.0 |
|
||||
| Stars | 9 |
|
||||
| Commits | 313 |
|
||||
| Latest release | v1.1.1 (April 12, 2026) |
|
||||
| Documentation | GitHub Wiki (EN/DE) |
|
||||
|
||||
A single Docker container combining a FastAPI backend and React frontend. The most production-ready project in the ecosystem in terms of release discipline and deployment accessibility. Features: internet radio with full hardware preset support (buttons 1–6), responsive web UI, device discovery via SSDP/UPnP, multi-room zone management, BMX-compatible endpoints, TuneIn stream resolver, RadioBrowser as a built-in first-class search provider, and pre-built Raspberry Pi SD card images for Pi 3/4/5. Deployable on amd64, arm64, and arm/v7. Documented in English and German. Spotify and Music Assistant integration are on the roadmap.
|
||||
|
||||
---
|
||||
|
||||
### 6. AfterTouch
|
||||
**[github.com/gesellix/Bose-SoundTouch](https://github.com/gesellix/Bose-SoundTouch)** by gesellix
|
||||
| | |
|
||||
|---|---|
|
||||
| Language | Go |
|
||||
| License | MIT |
|
||||
| Stars | 16 |
|
||||
| Contributors | 2 |
|
||||
| Commits | 217 |
|
||||
| Releases | 51 (latest: v0.28.0, Feb 15, 2026) |
|
||||
| Documentation | [gesellix.github.io/Bose-SoundTouch](https://gesellix.github.io/Bose-SoundTouch/) |
|
||||
|
||||
The most comprehensive single toolkit in the ecosystem. Comprises three components: a Go library (importable package), a CLI (`soundtouch-cli`), and a local cloud emulation service (`soundtouch-service`). Covers the widest range of dimensions of any single project. Implements the complete Bose Spotify OAuth relay including surrogate secret generation and token refresh proxy. Includes a built-in DNS server for device redirection without SSH, HTTPS/custom CA injection, HTTP session recording, traffic proxy/logging, and a web management UI. Tested on real SoundTouch 10 and 20 hardware. Has a Patreon for ongoing support.
|
||||
|
||||
---
|
||||
|
||||
### 7. soundcork-stockholm-app
|
||||
**[github.com/krahl/soundcork-stockholm-app](https://github.com/krahl/soundcork-stockholm-app)**
|
||||
| | |
|
||||
|---|---|
|
||||
| Language | Java |
|
||||
| License | — |
|
||||
| Stars | 2 |
|
||||
| Commits | 21 |
|
||||
| Status | Active development, bugs expected |
|
||||
|
||||
A Java-based middleware that hosts the original Bose Stockholm frontend (extracted from the APK) in a local web browser at `http://127.0.0.1:8088/`. Bridges the Stockholm UI to local speakers via an HTTP proxy that resolves cross-origin issues, with SSDP-based device discovery and JSON state persistence. Unlike every other tool in the ecosystem, it runs the **official Bose UI** rather than a custom replacement — preserving the familiar Bose UX at the cost of requiring the Stockholm APK. Notable limitations: OAuth flows are unreliable, and WebSocket connections to speakers over HTTPS have blocking issues. Works alongside soundcork's backend for full cloud emulation.
|
||||
|
||||
---
|
||||
|
||||
### 8. jaas666/bose-soundtouch-web-api (Reference)
|
||||
**[github.com/jaas666/bose-soundtouch-web-api](https://github.com/jaas666/bose-soundtouch-web-api)**
|
||||
|
||||
Community-maintained Markdown conversion of the official Bose SoundTouch Web API PDF (v1.0, January 7, 2026). Useful as a developer reference. Not a deployable tool.
|
||||
|
||||
---
|
||||
|
||||
## Feature Coverage Matrix
|
||||
|
||||
Legend: ● Yes/complete · ◑ Partial/planned · ○ No
|
||||
|
||||
| Dimension | soundcork | Überböse API | Überböse App | ST Hybrid 2026 | OpenCloudTouch | AfterTouch | Stockholm App |
|
||||
|----------------------------------------------------|:---------:|:------------:|:------------:|:--------------:|:--------------:|:----------:|:-------------:|
|
||||
| **① App layer — local HTTP/WS control** | | | | | | | |
|
||||
| Playback control (play/pause/vol) | ○ | ○ | ● | ● | ● | ● | ● |
|
||||
| Preset view & trigger | ○ | ○ | ● | ● | ● | ● | ● |
|
||||
| Preset write / reprogram | ○ | ○ | ● | ● | ◑ | ● | ● |
|
||||
| Multi-room zone management | ○ | ○ | ● | ● | ● | ● | ● |
|
||||
| Now playing / status display | ○ | ○ | ● | ● | ● | ● | ● |
|
||||
| Device discovery (SSDP/mDNS) | ○ | ○ | ● | ○ | ● | ● | ● |
|
||||
| WebSocket real-time events | ○ | ○ | ◑ | ● | ◑ | ● | ◑ |
|
||||
| **② Cloud/service layer — replaces Bose upstream** | | | | | | | |
|
||||
| Marge server emulation | ● | ● | ○ | ● | ○ | ● | ○ |
|
||||
| BMX / content registry | ◑ | ◑ | ○ | ● | ● | ● | ○ |
|
||||
| Account / OAuth token relay | ○ | ● | ○ | ◑ | ○ | ● | ◑ |
|
||||
| Preset sync (cloud-side) | ● | ● | ○ | ● | ○ | ● | ○ |
|
||||
| Recents sync | ● | ◑ | ○ | ◑ | ○ | ● | ○ |
|
||||
| Sources / device info persistence | ● | ● | ○ | ● | ○ | ● | ○ |
|
||||
| Stereo group CRUD (ST10 pairs) | ● | ○ | ○ | ○ | ○ | ● | ○ |
|
||||
| **③ Device redirection — USB/SSH setup** | | | | | | | |
|
||||
| Setup wizard / guided redirect | ◑ | ◑ | ○ | ● | ● | ● | ○ |
|
||||
| USB image / config generation | ○ | ○ | ○ | ● | ○ | ◑ | ○ |
|
||||
| HTTPS / custom CA support | ○ | ○ | ○ | ○ | ○ | ● | ○ |
|
||||
| **④ Streaming provider integration** | | | | | | | |
|
||||
| Internet radio (RadioBrowser) | ○ | ◑ | ◑ | ◑ | ● | ◑ | ○ |
|
||||
| TuneIn stream resolver | ● | ● | ● | ● | ● | ● | ● |
|
||||
| Spotify OAuth / Connect | ○ | ● | ● | ◑ | ◑ | ● | ◑ |
|
||||
| Pandora | ○ | ○ | ○ | ○ | ○ | ● | ◑ |
|
||||
| Music Assistant backend | ○ | ○ | ○ | ● | ◑ | ○ | ○ |
|
||||
| **⑤ Mobile / native app** | | | | | | | |
|
||||
| Android app (installable) | ○ | ○ | ● | ○ | ○ | ○ | ○ |
|
||||
| iOS app | ○ | ○ | ○ | ○ | ○ | ○ | ○ |
|
||||
| Mobile-responsive web UI | ○ | ○ | ○ | ● | ● | ● | ● |
|
||||
| **⑥ Smart home / ecosystem integration** | | | | | | | |
|
||||
| Home Assistant integration | ○ | ○ | ○ | ○ | ○ | ◑ | ○ |
|
||||
| Music Assistant integration | ○ | ○ | ○ | ● | ◑ | ○ | ○ |
|
||||
| **⑦ CLI / automation tools** | | | | | | | |
|
||||
| CLI for scripting / automation | ○ | ○ | ○ | ○ | ○ | ● | ○ |
|
||||
| Traffic proxy / API logging | ◑ | ● | ○ | ○ | ○ | ● | ◑ |
|
||||
| HTTP session recording | ○ | ○ | ○ | ○ | ○ | ● | ○ |
|
||||
| **⑧ Library / SDK** | | | | | | | |
|
||||
| Importable library / package | ○ | ○ | ○ | ○ | ○ | ● | ○ |
|
||||
| Published API spec / docs | ○ | ● | ○ | ○ | ○ | ● | ○ |
|
||||
| Docker deployment | ● | ● | ○ | ● | ● | ● | ● |
|
||||
| Raspberry Pi SD card image | ○ | ○ | ○ | ○ | ● | ○ | ○ |
|
||||
|
||||
---
|
||||
|
||||
## Making AfterTouch the One-Stop Solution — Open Tasks
|
||||
|
||||
AfterTouch is the strongest single project across the service and developer layers. Its remaining gaps are on the consumer-facing and ecosystem-integration sides.
|
||||
|
||||
### Priority 1 — PWA installability
|
||||
|
||||
The web UI is already fully responsive — it has Bootstrap grid columns, `@media (max-width: 768px)` and `@media (max-width: 576px)` breakpoints, and a proper viewport meta tag. It works on iPhone and Android browsers today. What's missing is **installability**: no `manifest.json` and no service worker, so it cannot be added to the home screen as a standalone app. Adding these would close the iOS app gap ecosystem-wide (no project has an iOS app) at minimal effort.
|
||||
|
||||
### Priority 2 — RadioBrowser as a first-class provider
|
||||
|
||||
AfterTouch can proxy and play any stream URL, but there is no built-in station search. OpenCloudTouch's RadioBrowser integration is the reference. Tasks:
|
||||
- Wire the [RadioBrowser API](https://www.radio-browser.info/) into the `soundtouch-web` web UI as a browsable/searchable source.
|
||||
- Make discovered stations directly presetable to hardware buttons.
|
||||
- This is the most common replacement for TuneIn for users who listened to internet radio via presets.
|
||||
|
||||
### Priority 3 — Raspberry Pi SD card image
|
||||
|
||||
OpenCloudTouch ships a flashable Pi image and it dramatically lowers the barrier for the most common "always-on local server" deployment. AfterTouch already has Docker and a web management UI; this is largely a CI/packaging task:
|
||||
- Build a Pi image (using e.g. `pi-gen` or `rpi-imager`-compatible tooling) that boots directly into `soundtouch-service`.
|
||||
- Auto-starts on boot, auto-discovers devices, opens the web UI on a known port.
|
||||
- Target Pi 3/4/5 with amd64/arm64/arm/v7 variants (mirroring OCT's approach).
|
||||
|
||||
### Priority 4 — USB config generation in the web UI
|
||||
|
||||
AfterTouch modifies `SoundTouchSdkPrivateCfg.xml` via SSH (`pkg/service/setup/setup.go`) and documents the redirect process thoroughly, but does not yet generate the USB stick content for users without SSH access. A "prepare USB stick" button in the web UI would remove the last manual step:
|
||||
- Generate `OverrideSdkPrivateCfg.xml` pre-populated with the running server's URL.
|
||||
- Optionally include the custom CA certificate for HTTPS-capable devices.
|
||||
- Surface alongside the existing guided migration wizard.
|
||||
|
||||
### Priority 5 — Music Assistant integration
|
||||
|
||||
SoundTouch Hybrid 2026 uses Music Assistant as its streaming backend, giving access to Apple Music, Deezer, local libraries, and many other providers. A formal Music Assistant **player provider** for AfterTouch would give power users a path to sources beyond Spotify, TuneIn, Pandora, and RadioBrowser. The Music Assistant community has an open discussion thread on this ([#4766](https://github.com/orgs/music-assistant/discussions/4766)).
|
||||
|
||||
### Priority 6 — DNS-based migration documentation
|
||||
|
||||
AfterTouch includes a built-in DNS server (`ENABLE_DNS_DISCOVERY`, `DNS_BIND_ADDR`, `DNS_UPSTREAM`) that intercepts `*.bose.com` queries and forwards everything else upstream — no Pi-hole, AdGuard, or any other external tool required. The ResolvConf migration path already treats DNS as a first-class option. The remaining gap is awareness: users unfamiliar with the project may not realise no external DNS infrastructure is needed. Tasks:
|
||||
- Surface the built-in DNS server more prominently in the getting-started documentation.
|
||||
- Document Pi-hole / AdGuard Home as an *alternative* for users who already run those, not a requirement.
|
||||
|
||||
### Priority 7 — MQTT integration
|
||||
|
||||
A design document exists (`docs/guides/MQTT-INTEGRATION-DESIGN.md`) but no code has been written. Implementing it would unlock home automation use cases without requiring the full Home Assistant stack — enabling triggers like "play preset 1 when front door opens" via any MQTT-capable automation platform.
|
||||
|
||||
---
|
||||
|
||||
## soundcork ↔ AfterTouch
|
||||
|
||||
soundcork and AfterTouch share the most functional overlap of any two projects in the ecosystem. For the implementation-level parity analysis and remaining tasks see [docs/PARITY-SOUNDCORK.md](../PARITY-SOUNDCORK.md).
|
||||
|
||||
### Architectural differences (not gaps)
|
||||
|
||||
These exist in soundcork but are deliberate architectural choices in AfterTouch, not missing features:
|
||||
|
||||
| Area | soundcork | AfterTouch |
|
||||
|--------------------------|---------------------------------------|-----------------------------------------------------------|
|
||||
| Web UI | FastAPI + Jinja2 miniapp and admin UI | Separate `soundtouch-web` component (Go + plain HTML/JS) |
|
||||
| Direct device management | SSH/SCP access into speakers | HTTP API only; no SSH |
|
||||
| Device discovery client | Python `upnpclient` library | mDNS + UPnP in Go, with dedicated DNS interception server |
|
||||
| Token delivery | Push (ZeroConf priming to port 8200) | Pull (device calls back to fetch) |
|
||||
| Persistence format | Flat files | XML flat files + atomic writes |
|
||||
|
||||
### AfterTouch capabilities soundcork lacks
|
||||
|
||||
| Feature | Notes |
|
||||
|-------------------------------------------|-----------------------------------------------------------------|
|
||||
| DNS server for device redirect | Intercepts Bose domain queries; no Pi-hole required |
|
||||
| HTTPS / custom CA injection | Full TLS with certificate generation and trust workflow |
|
||||
| HTTP interaction recording & replay | Captures real device traffic for debugging and regression tests |
|
||||
| Device migration (serial → MAC path) | Handles legacy device ID formats automatically |
|
||||
| Transparent proxy mode with upstream sync | Can mirror to real Bose cloud while running locally |
|
||||
| CLI (`soundtouch-cli`) | Scriptable control of speakers |
|
||||
| Importable Go library | `github.com/gesellix/bose-soundtouch/pkg/client` |
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
### Ecosystem fragmentation vs. convergence
|
||||
|
||||
The community is currently covering different parts of the problem in parallel rather than converging. AfterTouch explicitly credits soundcork, Überböse, and SoundTouch Plus in its README and describes its `soundtouch-service` as "heavily inspired by SoundCork". There is an opportunity — and arguably a need — for these projects to formally coordinate: shared test fixtures, a common compatibility matrix against specific firmware versions, and agreed-on API contracts would all reduce duplicated effort.
|
||||
|
||||
### Firmware version sensitivity
|
||||
|
||||
The SoundTouch 10 is most dependent on Marge for basic network functionality; the 20 and 30 are somewhat more tolerant. Compatibility across firmware versions is not systematically documented anywhere. A community firmware compatibility matrix (model × firmware version × which emulation features work) would be high value and is currently missing.
|
||||
|
||||
### Security posture
|
||||
|
||||
All projects warn that speakers should only be used on a private, firewalled network after cloud shutdown. AfterTouch is the only project to implement HTTPS/custom CA, which matters if devices are ever on a network where traffic could be inspected. soundcork's SECURITY.md explicitly warns against running on open networks.
|
||||
|
||||
### No iOS app — a structural gap
|
||||
|
||||
The original SoundTouch app was iOS-first. Every community replacement is Android-only (Überböse App) or browser-based. This is the largest unaddressed user segment in the ecosystem.
|
||||
|
||||
### Bose's open-source move as a precedent
|
||||
|
||||
Bose's decision to release API documentation rather than simply shutting down is notable — it mirrors what Pebble users did themselves with Rebble after that shutdown, but here the manufacturer initiated it. This sets a useful precedent and gives the community a solid legal and technical foundation to build on.
|
||||
|
||||
### Related community resources
|
||||
|
||||
- [Bose SoundTouch Plus (Home Assistant component)](https://github.com/thlucas1/homeassistantcomponent_soundtouchplus) — comprehensive HA integration by Todd Lucas, extensive API wiki
|
||||
- [Bose SoundTouch Hook](https://github.com/CodeFinder2/bose-soundtouch-hook) — `LD_PRELOAD`-based reverse engineering framework used by AfterTouch for protocol research
|
||||
- [Bose SoundTouch Web API (community Markdown)](https://github.com/jaas666/bose-soundtouch-web-api) — official API PDF converted to Markdown
|
||||
- [Bose Wiki — SoundTouch App Alternatives](https://bose.fandom.com/wiki/SoundTouch_app_alternatives) — community-maintained living list of workarounds and projects
|
||||
- [Reddit megathread — Bose alternatives](https://www.reddit.com/r/bose) — ongoing community discussion
|
||||
- [Radio Browser](https://www.radio-browser.info/) — the free, community-maintained internet radio directory used as a TuneIn replacement
|
||||
|
||||
---
|
||||
|
||||
*Document compiled April 2026. Project details sourced directly from GitHub repositories and official documentation. Star counts, commit counts, and release dates reflect the state at time of writing and will change as projects evolve. soundcork-stockholm-app added April 2026.*
|
||||
@@ -0,0 +1,369 @@
|
||||
# Amazon Music OAuth Integration
|
||||
|
||||
This document describes the plan and specification for adding Amazon Music OAuth support to the SoundTouch service, enabling continued Amazon Music playback after the Bose cloud shutdown (May 2026).
|
||||
|
||||
The implementation mirrors the [Spotify OAuth integration](spotify-oauth.md) closely. Read that document first — this one calls out only the differences.
|
||||
|
||||
## Status
|
||||
|
||||
**Infrastructure complete — streaming blocked by API access.**
|
||||
|
||||
All eight implementation steps are done. The OAuth flow (account linking, token storage, token refresh) works end-to-end with a standard Login with Amazon app. Token exchange (`/oauth/device/.../token/cs1`) succeeds and the speaker receives a valid `Atza|` access token.
|
||||
|
||||
However, real-world testing shows that the speaker then calls `https://music-api.amazon.com/` with that token and receives a `401 Unauthorized` (no redirect to a regional endpoint). This means the token does not carry the scopes required to access the Amazon Music streaming API.
|
||||
|
||||
**Root cause (confirmed):** Amazon Music streaming requires the `amazon_music:access` scope, which is only available to **device client IDs** — a separate credential type obtained through Amazon's Music partner programme. Standard Login with Amazon application client IDs (`amzn1.application-oa2-client.*`) cannot request this scope: attempting to include it in the authorization URL returns `lwa-invalid-parameter-bad-scope` (HTTP 400) from the LWA authorization endpoint. Bose would have held a device client ID as a registered Amazon Music partner.
|
||||
|
||||
**What still works:**
|
||||
- Account linking and token storage
|
||||
- Token refresh (the service correctly exchanges the refresh token for a fresh access token)
|
||||
- Marge source registration (the speaker sees Amazon Music as a configured source)
|
||||
|
||||
**What does not work:**
|
||||
- Actual music playback — the speaker's `AmazonClient` cannot authenticate to `music-api.amazon.com` with a standard LWA token
|
||||
|
||||
**Path forward:** Obtaining a device client ID requires registering with Amazon's Music partner programme. If such a credential is obtained, the only code change needed is swapping the `client_id`/`client_secret` for the device credentials and adding `amazon_music:access` to `AmazonScopes` in `pkg/service/amazon/service.go` — everything else is already in place. The `site_id` field is a secondary open question that may also affect regional routing once the scope issue is resolved.
|
||||
|
||||
---
|
||||
|
||||
## Secret Format (confirmed from a live Bose system)
|
||||
|
||||
A real Amazon source entry from a migrated device's `Sources.xml`:
|
||||
|
||||
```xml
|
||||
<source secretType="token">
|
||||
<credential type="token">{"AmazonSecret":{"refresh_token":"Atzr|...","site_id":"1464855981"}}</credential>
|
||||
<sourceKey type="AMAZON" account="user@example.com"/>
|
||||
</source>
|
||||
```
|
||||
|
||||
Key observations:
|
||||
|
||||
- **Secret envelope**: `{"AmazonSecret":{"refresh_token":"...","site_id":"..."}}` — JSON-encoded, HTML-entity-escaped in XML attributes, stored as the credential value.
|
||||
- **`Atzr|` prefix**: This is the standard Amazon LWA (Login with Amazon) refresh token prefix from the **authorization code grant** — confirming that Web OAuth is the correct flow, not CBL.
|
||||
- **`site_id`**: A numeric string (`"1464855981"`). Origin is not yet fully confirmed; candidates are:
|
||||
- A static Bose partner identifier baked into the Bose app/firmware (same value for all users), or
|
||||
- A per-user Amazon Music identifier returned by a Music API device registration call.
|
||||
- Needs verification — possibly obtained by calling the Amazon Music API after initial authentication.
|
||||
- **`account` field**: The user's Amazon email address (obtained from the LWA `/user/profile` endpoint).
|
||||
|
||||
When `HandleBoseAmazonToken` receives a refresh request from the speaker, it must:
|
||||
1. Parse the `AmazonSecret` JSON from the stored credential to extract `refresh_token`.
|
||||
2. Call the LWA token endpoint with a `refresh_token` grant.
|
||||
3. Return the fresh `access_token` to the speaker.
|
||||
4. Persist the rotated `refresh_token` back into the `AmazonSecret` envelope.
|
||||
|
||||
---
|
||||
|
||||
## How the Speaker Uses This
|
||||
|
||||
When the SoundTouch firmware tries to play Amazon Music after migration, it sends a token refresh request to the local service:
|
||||
|
||||
```
|
||||
POST /oauth/device/{deviceID}/music/musicprovider/20/token/cs1
|
||||
```
|
||||
|
||||
The service must respond with a fresh Amazon access token. The speaker then uses that token directly with Amazon's playback infrastructure.
|
||||
|
||||
The `cs1` suffix (credential schema 1) is Amazon-specific; Spotify uses `cs3`. This route is already registered.
|
||||
|
||||
> **DNS note:** The speaker constructs the OAuth hostname by appending `oauth` to the streaming service subdomain. If the service is reachable at `myhost.local`, the speaker will call `myhostoauth.local`. A DNS alias pointing `myhostoauth.<domain>` to the same IP as the service is required.
|
||||
|
||||
---
|
||||
|
||||
## OAuth Flows
|
||||
|
||||
### 1. Browser-based Flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Client as Client (curl/app)
|
||||
participant Service as Service
|
||||
participant Amazon as Amazon Auth Server (LWA)
|
||||
participant Browser as User's Browser
|
||||
|
||||
Client->>Service: POST /mgmt/amazon/init [Basic Auth]
|
||||
Service-->>Client: {"redirectUrl": "https://www.amazon.com/ap/oa?..."}
|
||||
|
||||
Client->>Browser: User opens URL
|
||||
Browser->>Amazon: User logs in & grants access
|
||||
Amazon-->>Browser: Redirect to /mgmt/amazon/callback?code=abc
|
||||
|
||||
Browser->>Service: GET /mgmt/amazon/callback?code=abc
|
||||
Note over Service: No auth needed for callback
|
||||
|
||||
Service->>Amazon: POST /auth/o2/token (exchange code)
|
||||
Amazon-->>Service: {access_token, refresh_token}
|
||||
|
||||
Service->>Amazon: GET /user/profile (fetch profile)
|
||||
Amazon-->>Service: {user_id, name, email}
|
||||
|
||||
Note over Service: Store account to disk
|
||||
|
||||
Service-->>Browser: HTML: "Amazon Music Connected. You can close this window."
|
||||
```
|
||||
|
||||
### 2. Mobile App Flow (ueberboese)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant App as ueberboese Flutter App
|
||||
participant Service as Service
|
||||
participant Amazon as Amazon Auth Server (LWA)
|
||||
|
||||
App->>Service: POST /mgmt/amazon/init [Basic Auth]
|
||||
Service-->>App: {"redirectUrl": "https://www.amazon.com/ap/oa?..."}
|
||||
|
||||
App->>Amazon: Open in-app browser (User authorizes)
|
||||
Amazon-->>App: Deep link redirect: ueberboese-login://amazon?code=abc
|
||||
|
||||
App->>Service: POST /mgmt/amazon/confirm?code=abc [Basic Auth]
|
||||
|
||||
Service->>Amazon: POST /auth/o2/token (exchange code)
|
||||
Amazon-->>Service: {access_token, refresh_token}
|
||||
|
||||
Service->>Amazon: GET /user/profile (fetch profile)
|
||||
Amazon-->>Service: {profile}
|
||||
|
||||
Service-->>App: {"ok": true}
|
||||
```
|
||||
|
||||
### 3. Token Retrieval (Speaker Token Refresh)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Speaker as SoundTouch Speaker
|
||||
participant Service as Service
|
||||
participant Amazon as Amazon Token API (LWA)
|
||||
|
||||
Speaker->>Service: POST /oauth/device/{deviceID}/music/musicprovider/20/token/cs1
|
||||
Note over Service: Body contains stored AmazonSecret JSON;<br/>extract refresh_token from {"AmazonSecret":{...}}
|
||||
|
||||
alt Token expired or near expiry
|
||||
Service->>Amazon: POST /auth/o2/token (refresh_token grant, body credentials)
|
||||
Amazon-->>Service: {access_token, refresh_token, expires_in}
|
||||
Note over Service: Persist rotated refresh_token back into AmazonSecret envelope
|
||||
end
|
||||
|
||||
Service-->>Speaker: {"access_token": "...", "token_type": "Bearer", "expires_in": 3600}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1 — Extract ZeroConf into a shared package
|
||||
|
||||
**Why first:** The DH-blob encryption in `pkg/service/spotify/zeroconf.go` is entirely provider-agnostic. Extracting it to `pkg/service/zeroconf/` before adding Amazon avoids duplicating ~200 lines of crypto code.
|
||||
|
||||
**What changes:**
|
||||
- Create `pkg/service/zeroconf/zeroconf.go` — move `generateDHKeyPair`, `computeSharedSecret`, `deriveKeys`, `buildCredentialsBlob`, `encryptBlob` and helpers. Expose `authType` as a parameter (Spotify and Amazon both use `AuthTypeOAuthToken = 4`, but this makes it explicit).
|
||||
- Update `pkg/service/spotify/zeroconf.go` — delete moved code; `PushSpotifyCredentials` becomes a one-line wrapper calling `zeroconf.PushCredentials(...)`.
|
||||
|
||||
### Step 2 — Create `pkg/service/amazon/service.go`
|
||||
|
||||
Mirror `pkg/service/spotify/service.go`. The `Account` struct is identical; copy it unchanged.
|
||||
|
||||
**Amazon-specific differences:**
|
||||
|
||||
| Item | Spotify | Amazon |
|
||||
|---------------------------|------------------------------------------|-------------------------------------------------|
|
||||
| Authorization URL | `https://accounts.spotify.com/authorize` | `https://www.amazon.com/ap/oa` |
|
||||
| Token endpoint | `https://accounts.spotify.com/api/token` | `https://api.amazon.com/auth/o2/token` |
|
||||
| Profile endpoint | `https://api.spotify.com/v1/me` | `https://api.amazon.com/user/profile` |
|
||||
| Token request credentials | HTTP Basic Auth (clientID:clientSecret) | POST body fields `client_id` / `client_secret` |
|
||||
| Profile fields | `id`, `display_name`, `email` | `user_id`, `name`, `email` |
|
||||
| Scopes | `streaming user-read-private ...` | `profile` (expand to `music::*` when available) |
|
||||
| Entity resolution | `ResolveEntity()` via Spotify API | Not implemented (API in closed beta) |
|
||||
|
||||
Accounts persist to `{dataDir}/amazon/accounts.json`.
|
||||
|
||||
The token request credential difference (body vs. Basic Auth) is the most important implementation detail.
|
||||
|
||||
### Step 3 — Create `pkg/service/amazon/zeroconf.go`
|
||||
|
||||
A single exported function `PushAmazonCredentials(zcBaseURL, username, accessToken string) error` delegating to the shared `zeroconf.PushCredentials(...)`.
|
||||
|
||||
### Step 4 — Implement `HandleBoseAmazonToken`
|
||||
|
||||
Replace the 501 stub in `pkg/service/handlers/handlers_oauth.go` with the full mirror of `HandleBoseSpotifyToken`:
|
||||
- Parse body for `refresh_token` / `code`
|
||||
- Look up account by BoseSecret; refresh and return token
|
||||
- Fall back to first account via `GetFreshToken()` if no matching account
|
||||
- Fall back to `HandleBoseProxy` if no Amazon service is configured
|
||||
- **Omit `scope` from the response** — Amazon Music scopes are undocumented; sending invented values risks firmware rejection
|
||||
|
||||
### Step 5 — Add Amazon fields to `Server`
|
||||
|
||||
In `pkg/service/handlers/server.go`, add alongside the Spotify fields:
|
||||
|
||||
```go
|
||||
amazonClientID string
|
||||
amazonClientSecret string
|
||||
amazonRedirectURI string
|
||||
amazonService *amazon.Service
|
||||
```
|
||||
|
||||
Add methods: `SetAmazonConfig`, `SetAmazonService`, `IsAmazonConfigured`, `PrimeDeviceWithAmazon`.
|
||||
|
||||
### Step 6 — Add management handlers
|
||||
|
||||
In `pkg/service/handlers/handlers_mgmt.go`, add six handlers mirroring Spotify:
|
||||
|
||||
| Handler | Notes |
|
||||
|-------------------------------|-----------------------------------------|
|
||||
| `HandleMgmtAmazonInit` | Returns LWA authorize URL |
|
||||
| `HandleMgmtAmazonCallback` | No auth; calls `bridgeAmazonToMarge` |
|
||||
| `HandleMgmtAmazonConfirm` | Basic Auth; calls `bridgeAmazonToMarge` |
|
||||
| `HandleMgmtAmazonAccounts` | Returns account list (tokens stripped) |
|
||||
| `HandleMgmtAmazonToken` | Returns fresh access token |
|
||||
| `HandleMgmtPrimeDeviceAmazon` | Pushes token to speaker via ZeroConf |
|
||||
|
||||
`bridgeAmazonToMarge` must encode the stored secret as `{"AmazonSecret":{"refresh_token":"<token>","site_id":"<id>"}}` and use `CredentialTypeToken` ("token") — **not** `CredentialTypeTokenV3`. Amazon uses `cs1` semantics.
|
||||
|
||||
### Step 7 — Wire CLI flags and router
|
||||
|
||||
**`main.go` flags** (env vars in parentheses):
|
||||
- `--amazon-client-id` (`AMAZON_CLIENT_ID`)
|
||||
- `--amazon-client-secret` (`AMAZON_CLIENT_SECRET`)
|
||||
- `--amazon-redirect-uri` (`AMAZON_REDIRECT_URI`, default: `ueberboese-login://amazon`)
|
||||
- `--amazon-token-url` (`AMAZON_TOKEN_URL`, for testing overrides)
|
||||
- `--amazon-profile-url` (`AMAZON_PROFILE_URL`, for testing overrides)
|
||||
|
||||
**Router** (`setupRouter`): Add `/mgmt/amazon/*` sub-routes next to the Spotify block. The `/oauth/.../token/cs1` route is already registered and dispatches to `HandleBoseAmazonToken`.
|
||||
|
||||
**`pkg/service/marge/marge.go`**: Extend the `AddSource` provider-label branch to map `AmazonProviderID (20) → "AMAZON"` so stored sources carry the correct type string rather than the raw numeric ID.
|
||||
|
||||
**`pkg/models/account.go`**: Add `NewAmazonOAuthCredentials` with `Source: "AMAZON"`, `Version: "token"`.
|
||||
|
||||
### Step 8 — Tests
|
||||
|
||||
Mirror the Spotify test suite for the Amazon package:
|
||||
|
||||
- `TestBuildAuthorizeURL` — verify LWA URL structure
|
||||
- `TestExchangeCodeAndStore` — mock token + profile servers; assert POST body credentials (not Basic Auth)
|
||||
- `TestRefreshAccessToken` — verify body credentials, token rotation
|
||||
- `TestGetFreshToken*` — copy Spotify variants verbatim
|
||||
- `TestSaveAndLoad` — verify persistence under `amazon/accounts.json`
|
||||
|
||||
Add `pkg/testutils/amazon/handlers.go` and `tests/integration/mocks/amazon.go` mock servers mirroring the Spotify equivalents.
|
||||
|
||||
Update `cmd/soundtouch-service/testdata/router_routes.txt` snapshot after wiring.
|
||||
|
||||
---
|
||||
|
||||
## Trying It Out
|
||||
|
||||
### 1. Create a Login with Amazon (LWA) app
|
||||
|
||||
Go to [developer.amazon.com](https://developer.amazon.com) → **Login with Amazon** → **Create a New Security Profile**.
|
||||
|
||||
You will receive a **Client ID** and **Client Secret**. Under *Web Settings*, add an **Allowed Return URL** that matches `--amazon-redirect-uri`:
|
||||
|
||||
- **Browser flow** (easiest to test): `http://<your-host>:8000/mgmt/amazon/callback`
|
||||
- **Mobile deep-link flow**: `ueberboese-login://amazon` (the default)
|
||||
|
||||
The `profile` scope is sufficient — `music::` scopes are in closed beta and not required. The service only brokers tokens; the speaker communicates with Amazon's playback infrastructure directly.
|
||||
|
||||
### 2. Start the service
|
||||
|
||||
```bash
|
||||
./soundtouch-service \
|
||||
--amazon-client-id amzn1.application-oa2-client.xxx \
|
||||
--amazon-client-secret yyy \
|
||||
--amazon-redirect-uri http://<your-host>:8000/mgmt/amazon/callback
|
||||
```
|
||||
|
||||
Or set the equivalent environment variables: `AMAZON_CLIENT_ID`, `AMAZON_CLIENT_SECRET`, `AMAZON_REDIRECT_URI`.
|
||||
|
||||
### 3. Trigger the OAuth flow
|
||||
|
||||
```bash
|
||||
# Get the LWA authorization URL
|
||||
curl -u admin:change_me! -X POST http://localhost:8000/mgmt/amazon/init
|
||||
# → {"redirectUrl":"https://www.amazon.com/ap/oa?client_id=...&scope=profile&..."}
|
||||
```
|
||||
|
||||
Open the `redirectUrl` in a browser, log in with your Amazon account, and authorize the app. Amazon redirects back to `/mgmt/amazon/callback`, which responds with an HTML page saying "Amazon Music Connected".
|
||||
|
||||
### 4. Verify the account is linked
|
||||
|
||||
```bash
|
||||
curl -u admin:change_me! http://localhost:8000/mgmt/amazon/accounts
|
||||
# → {"accounts":[{"user_id":"amzn1.account.xxx","display_name":"Your Name","email":"you@example.com",...}]}
|
||||
```
|
||||
|
||||
### 5. Prime a speaker
|
||||
|
||||
```bash
|
||||
# Discover device IDs first
|
||||
curl -u admin:change_me! http://localhost:8000/mgmt/accounts/default/speakers
|
||||
|
||||
# Push the token to a specific speaker via ZeroConf
|
||||
curl -u admin:change_me! -X POST \
|
||||
"http://localhost:8000/mgmt/amazon/prime?deviceId=<deviceId>"
|
||||
# → {"status":"Priming triggered"}
|
||||
```
|
||||
|
||||
### 6. Verify token refresh from the speaker
|
||||
|
||||
Once a speaker has Amazon Music as a source, it will periodically POST to:
|
||||
|
||||
```
|
||||
POST /oauth/device/{deviceID}/music/musicprovider/20/token/cs1
|
||||
```
|
||||
|
||||
The service looks up the account by refresh token, refreshes it via LWA, and returns a fresh `access_token`. Check the service logs for `[Amazon]` entries confirming this flow.
|
||||
|
||||
### DNS requirement
|
||||
|
||||
The speaker derives the OAuth hostname by appending `oauth` to its configured streaming subdomain. If the service is at `myhost.local`, the speaker calls `myhostoauth.local`. A DNS alias pointing `myhostoauth.<domain>` to the same IP is required — the built-in DNS discovery server handles this automatically when `--dns-discovery` is enabled.
|
||||
|
||||
### Open question: `site_id`
|
||||
|
||||
The `AmazonSecret` credential envelope contains a `site_id` field (e.g. `"1464855981"` seen in a real migrated device). Its origin is unconfirmed — it may be a static Bose partner ID or a per-user Amazon Music identifier. The service currently stores an empty string.
|
||||
|
||||
Real-world testing shows the device's `AmazonClient` calls `CheckBaseUrlRedirect` with empty `data` (the `site_id`) and then tries `https://music-api.amazon.com/` directly, receiving a 401 with no redirect to a regional endpoint (e.g. `music-api.amazon.de` for a German account). This suggests that:
|
||||
|
||||
1. A correct `site_id` might cause the device to use the right regional endpoint instead of the US default.
|
||||
2. Even so, the token scope issue (see Status above) would still block playback — resolving `site_id` alone is not sufficient.
|
||||
|
||||
`site_id` is likely secondary to the partner scope problem. It remains an open question for the post-scope-resolution phase.
|
||||
|
||||
---
|
||||
|
||||
## Endpoints
|
||||
|
||||
| Method | Path | Auth | Purpose |
|
||||
|--------|-------------------------------------------------------------|-------|----------------------------------------------------|
|
||||
| `POST` | `/oauth/device/{deviceID}/music/musicprovider/20/token/cs1` | None | Token refresh from speaker |
|
||||
| `GET` | `/mgmt/amazon/callback` | None | Browser OAuth callback (redirect from Amazon LWA) |
|
||||
| `POST` | `/mgmt/amazon/init` | Basic | Start OAuth flow, returns authorization URL |
|
||||
| `POST` | `/mgmt/amazon/confirm` | Basic | Mobile app confirm (deep link delivers code) |
|
||||
| `GET` | `/mgmt/amazon/accounts` | Basic | List linked Amazon accounts (tokens stripped) |
|
||||
| `GET` | `/mgmt/amazon/token` | Basic | Get fresh access token (auto-refreshes if expired) |
|
||||
| `POST` | `/mgmt/amazon/prime` | Basic | Push token to speaker via ZeroConf |
|
||||
|
||||
## Security
|
||||
|
||||
Same model as Spotify:
|
||||
- `/mgmt/amazon/callback` is intentionally outside Basic Auth to allow direct redirects from Amazon's authorization server.
|
||||
- All other `/mgmt/*` endpoints require Basic Auth.
|
||||
- Accounts persist to `{dataDir}/amazon/accounts.json` with `0600` permissions.
|
||||
- `GetAccounts` strips `AccessToken` and `RefreshToken` from responses.
|
||||
|
||||
## Key Design Decisions
|
||||
|
||||
**Secret is a JSON envelope, not a bare token.** The stored credential is `{"AmazonSecret":{"refresh_token":"Atzr|...","site_id":"..."}}`, HTML-entity-escaped when written to XML attributes. This was confirmed from a real migrated device's `Sources.xml`. `HandleBoseAmazonToken` must parse this structure to extract the `refresh_token`, and `bridgeAmazonToMarge` must produce it when storing after OAuth.
|
||||
|
||||
**`site_id` origin is unconfirmed.** It may be a static Bose partner ID or a per-user Amazon Music identifier. Needs verification — likely obtained by calling the Amazon Music API or the LWA profile endpoint post-authentication.
|
||||
|
||||
**Credential type is `token`, not `token_version_3`.** `CredentialTypeTokenV3` is Spotify-specific (`cs3`). Amazon uses `cs1`, which maps to the plain `CredentialTypeToken` ("token") constant. Do not upgrade Amazon credentials to v3 in `marge.go`.
|
||||
|
||||
**POST body credentials, not Basic Auth.** The Amazon LWA token endpoint (`/auth/o2/token`) expects `client_id` and `client_secret` as POST body fields, not as an HTTP Basic Auth header. This is the single most important difference from the Spotify implementation.
|
||||
|
||||
**No entity resolution.** `ResolveEntity()` is not implemented for Amazon — the Amazon Music API is in closed beta. Return HTTP 501 if an entity endpoint is ever requested.
|
||||
|
||||
**`scope` omitted from token response.** The Spotify handler returns a hardcoded scope string. Amazon Music scopes for playback are undocumented; returning an empty or absent `scope` is safer than inventing values.
|
||||
|
||||
**ZeroConf extraction is a prerequisite.** The DH-blob crypto in `spotify/zeroconf.go` should be extracted to a shared package before Amazon is added to avoid duplicating cryptographic code.
|
||||
@@ -4,7 +4,31 @@ This document outlines the strategy for ensuring Bose SoundTouch devices are cor
|
||||
|
||||
## Overview
|
||||
|
||||
To enable Spotify Connect for SoundTouch devices, especially for remote availability outside the local network, the speaker must be associated with a Spotify account via a process called "priming." This involves sending an `addUser` command to the speaker's ZeroConf API (port 8200) containing a valid Spotify username and OAuth access token.
|
||||
To enable Spotify Connect for SoundTouch devices, especially for remote availability outside the local network, the speaker must be associated with a Spotify account via a process called "priming." This involves a two-step exchange with the speaker's ZeroConf API (port 8200):
|
||||
|
||||
1. **`getInfo`** — retrieve the speaker's Diffie-Hellman public key and device metadata.
|
||||
2. **`addUser`** — push encrypted Spotify credentials using the shared DH secret.
|
||||
|
||||
This is the standard Spotify Connect ZeroConf protocol. Once the speaker holds a properly encrypted credential blob it can independently authenticate with Spotify's servers and refresh its own session without any further involvement from AfterTouch.
|
||||
|
||||
### ZeroConf Protocol
|
||||
|
||||
The current implementation follows the full Spotify Connect ZeroConf protocol (`pkg/service/spotify/zeroconf.go`):
|
||||
|
||||
1. `GET http://{ip}:8200/zc?action=getInfo` → parse `publicKey` (base64 DH key, 768-bit Oakley Group 1 prime) from the response.
|
||||
2. Generate a client DH key pair using the same group parameters.
|
||||
3. Compute `sharedSecret = DH(clientPrivate, speakerPublicKey)`.
|
||||
4. Derive keys: `baseKey = SHA1(sharedSecret)[:16]`, then HMAC-SHA1 with labels `"encryption"` and `"checksum"`.
|
||||
5. Encrypt a protobuf-encoded `LoginCredentials` blob (username, `AUTHENTICATION_SPOTIFY_TOKEN=4`, access token) using AES-128-CTR + HMAC-SHA1 checksum.
|
||||
6. `POST http://{ip}:8200/zc?action=addUser` with `blob={encryptedBlob}`, `clientKey={clientPublicKeyBase64}`.
|
||||
|
||||
The speaker decrypts the blob, stores long-lived credentials, and can handle token refresh with Spotify independently. No periodic re-priming is required for token expiry.
|
||||
|
||||
The algorithm is based on [librespot](https://github.com/librespot-org/librespot) (Rust reference implementation).
|
||||
|
||||
### Fallback for Older Firmware
|
||||
|
||||
If `getInfo` fails (e.g. firmware that does not implement the DH exchange), `PushSpotifyCredentials` automatically falls back to the simplified `tokenType=accesstoken` approach: the raw OAuth access token is sent as the `blob` with an empty `clientKey`. This token expires after ~60 minutes and the speaker cannot self-refresh, so periodic re-priming is required in that case.
|
||||
|
||||
AfterTouch adopts a **Server-Centric Hybrid Model** that prioritizes device cleanliness and user intent while providing automated self-healing.
|
||||
|
||||
@@ -14,7 +38,7 @@ AfterTouch adopts a **Server-Centric Hybrid Model** that prioritizes device clea
|
||||
AfterTouch replicates the native Bose "Add Source" experience. No Spotify priming occurs until a user explicitly links their Spotify account through the AfterTouch Management Dashboard. This ensures privacy and respects users who do not wish to use Spotify.
|
||||
|
||||
### 2. Device Cleanliness (Minimalist Footprint)
|
||||
We avoid invasive modifications to the speaker's filesystem.
|
||||
We avoid invasive modifications to the speaker's filesystem.
|
||||
- **No On-Device Scripts:** We deprecate the use of internal boot-primer scripts.
|
||||
- **Native Communication:** We rely on the speaker's native ability to talk to Bose services, which are intercepted via DNS to point to the AfterTouch server.
|
||||
|
||||
@@ -53,6 +77,8 @@ The logic for account management and device interaction remains decoupled:
|
||||
4. AfterTouch pushes a fresh token from the Spotify Service.
|
||||
5. UI reflects that the device is "Managed by AfterTouch" and healthy.
|
||||
|
||||
> **Note:** With the proper encrypted-blob flow now in place, the watchdog is only needed for the "speaker reboots and loses state" case — not for token expiry. Speakers running older firmware that trigger the `tokenType=accesstoken` fallback still require periodic re-priming (~45 min) because the raw access token expires.
|
||||
|
||||
### Manual Override
|
||||
Users can manually trigger a "Re-prime" or "Refresh Link" from the device list in the UI if they suspect the automated self-healing is delayed or if they want to force a specific account onto a device.
|
||||
|
||||
@@ -76,9 +102,11 @@ As AfterTouch moves to the Server-Centric model, we will:
|
||||
2. **Consolidated Directory:** We maintain the `/mnt/nv/soundtouch-service/` base directory for other configuration needs (e.g., `aftertouch.resolv.conf`), but it will no longer contain Spotify-specific credentials or scripts.
|
||||
3. **No On-Device Credentials:** The `/mnt/nv/soundtouch-service/spotify-primer.conf` will be removed, ensuring that no sensitive AfterTouch login details are stored on the speaker in plain text.
|
||||
|
||||
## Implementation Roadmap (Conceptual)
|
||||
## Implementation Roadmap
|
||||
|
||||
1. **Revert On-Device Migration:** Update the Setup Manager to remove legacy scripts and `rc.local` hooks.
|
||||
2. **Server-Side Priming Logic:** Implement a `PrimeDevice(ip)` method in the server that fetches a fresh token and calls the ZeroConf API.
|
||||
3. **Discovery Hook:** Integrate `PrimeDevice` into the discovery handler (`handleDiscoveredDevice`) with a check for unprimed state.
|
||||
4. **UI Enhancements:** Update the Speaker List to show "Spotify Linked" status and provide manual refresh buttons.
|
||||
1. ✅ **Server-Side Priming Logic:** `PrimeDeviceWithSpotify(ip)` and `pushSpotifyTokenToDevice` in `pkg/service/handlers/server.go`. Triggered on device registration (marge handlers) and via the manual `HandleMgmtPrimeDevice` endpoint.
|
||||
2. ✅ **Discovery Hook:** `handleDiscoveredDevice` calls `PrimeDeviceWithSpotify` when a speaker is found.
|
||||
3. ✅ **Proper ZeroConf Blob:** Full DH key exchange + AES-128-CTR encrypted `LoginCredentials` blob implemented in `pkg/service/spotify/zeroconf.go`. Automatically falls back to `tokenType=accesstoken` if `getInfo` fails (older firmware).
|
||||
4. ⬜ **Watchdog / Session Refresh:** Background timer to re-prime all known devices on a schedule. Only strictly needed for older firmware (fallback path) or "speaker lost state" recovery; not required for token expiry on modern firmware.
|
||||
5. ⬜ **Revert On-Device Migration:** Update the Setup Manager to remove legacy `spotify-boot-primer` scripts and `rc.local` hooks from the speakers.
|
||||
6. ⬜ **UI Enhancements:** Update the Speaker List to show "Spotify Linked" status and provide manual refresh buttons.
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
# Capture Device Pairing Traffic
|
||||
|
||||
Step-by-step runbook for factory-resetting a SoundTouch speaker, pairing it to a Bose cloud account, and capturing every cloud request via mitmproxy. Tested on Apple Silicon Mac.
|
||||
|
||||
**Goal:** obtain a full `.mitm` recording of the account-pairing flow (streaming.bose.com) triggered by the official Android app.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
```
|
||||
Phase 0 Pre-flight checks
|
||||
Phase 1 Factory reset speaker
|
||||
Phase 2 Provision speaker Wi-Fi (AP mode, console)
|
||||
Phase 3 Start mitmproxy + emulator + Frida
|
||||
Phase 4 Pair speaker via Bose app (adb-driven)
|
||||
Phase 5 Save & inspect recording
|
||||
```
|
||||
|
||||
The Android emulator does not have Bluetooth, so the standard BLE setup path is unavailable. Instead:
|
||||
|
||||
1. Provision Wi-Fi directly over the speaker's AP web server (Phase 2).
|
||||
2. Once the speaker is on the LAN, the Bose app discovers it via mDNS — no BLE needed.
|
||||
|
||||
---
|
||||
|
||||
## Phase 0 — Pre-flight
|
||||
|
||||
The emulator setup is fully scripted. Run once per machine:
|
||||
|
||||
```bash
|
||||
# Place the Bose APK at scripts/android/bose.apk first (see BOSE-APP-ADB-Emulator.md § 1)
|
||||
# Run mitmweb once to generate the CA: mitmweb --listen-port 8080 (Ctrl-C after it starts)
|
||||
|
||||
scripts/android/setup-mitm-avd.sh
|
||||
```
|
||||
|
||||
This installs the system image, creates an AVD named `bose-mitm`, installs the
|
||||
mitmproxy cert and Bose APK, and saves an emulator snapshot `mitm-ready` — so
|
||||
subsequent sessions never repeat the cert/reboot cycle.
|
||||
|
||||
For subsequent sessions, Phase 3 below is replaced by a single command:
|
||||
|
||||
```bash
|
||||
scripts/android/start-mitm-session.sh
|
||||
```
|
||||
|
||||
Manual steps are only needed if you want to understand the internals; see
|
||||
[BOSE-APP-ADB-Emulator.md](../analysis/BOSE-APP-ADB-Emulator.md) for the
|
||||
full manual walkthrough.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — Factory Reset Speaker
|
||||
|
||||
Perform the reset for your model (see
|
||||
[DEVICE-INITIAL-SETUP.md § 5](DEVICE-INITIAL-SETUP.md) for full table):
|
||||
|
||||
| Model | Sequence |
|
||||
|-----------------------------|-------------------------------------------------------------------------|
|
||||
| SoundTouch 10 | Power on; hold **Preset 1** + **Vol −** ~10 s → solid amber Wi-Fi LED |
|
||||
| SoundTouch 20 | Power on; hold **Preset 1** + **Vol −** ~10 s → lights blink L→R, amber |
|
||||
| SoundTouch 20/30 Series III | Hold **Preset 1** + **Preset 6** ~10 s |
|
||||
| SoundTouch 300 | Hold **Vol −** ~15 s until light bar blinks |
|
||||
|
||||
Wait until the white LED sweep / restart animation completes (~30 s). The speaker
|
||||
is now in setup mode and broadcasting its own Wi-Fi AP.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — Provision Speaker Wi-Fi (AP Mode)
|
||||
|
||||
### 2.1 Connect Mac to Speaker AP
|
||||
|
||||
```bash
|
||||
# Find the SSID — use System Settings → Wi-Fi or:
|
||||
# sudo wdutil info (macOS Sequoia+, airport command removed)
|
||||
|
||||
# Connect (replace SSID with actual value)
|
||||
SPEAKER_SSID="Bose SoundTouch XXXX"
|
||||
networksetup -setairportnetwork en0 "$SPEAKER_SSID"
|
||||
|
||||
# Confirm: speaker web UI reachable at 192.0.2.1 (client gets 192.0.2.2)
|
||||
curl -s --connect-timeout 5 http://192.0.2.1/ | head -3
|
||||
```
|
||||
|
||||
### 2.2 Push Home Wi-Fi Credentials
|
||||
|
||||
The setup UI at `http://192.0.2.1/` uses the SoundTouch API on **port 8090**. Push credentials directly:
|
||||
|
||||
```bash
|
||||
HOME_SSID="MyHomeNetwork"
|
||||
HOME_PASS="MyPassword"
|
||||
|
||||
# Optional: trigger a site survey first so the speaker finds your SSID
|
||||
curl -s -X POST http://192.0.2.1:8090/performWirelessSiteSurvey \
|
||||
-H 'Content-Type: text/xml' \
|
||||
--data-raw '<PerformWirelessSiteSurvey timeout="5"/>'
|
||||
|
||||
curl -s -X POST http://192.0.2.1:8090/addWirelessProfile \
|
||||
-H 'Content-Type: text/xml' \
|
||||
--data-raw "<AddWirelessProfile><profile ssid=\"${HOME_SSID}\" password=\"${HOME_PASS}\" securityType=\"wpa_or_wpa2\" /></AddWirelessProfile>"
|
||||
```
|
||||
|
||||
Expected response: `<AddWirelessProfileResponse />`
|
||||
|
||||
### 2.3 Reconnect Mac to Home Network
|
||||
|
||||
```bash
|
||||
HOME_SSID="MyHomeNetwork"
|
||||
HOME_PASS="MyPassword"
|
||||
|
||||
networksetup -setairportnetwork en0 "$HOME_SSID" "$HOME_PASS"
|
||||
```
|
||||
|
||||
### 2.4 Wait for Speaker to Join LAN
|
||||
|
||||
```bash
|
||||
# Poll mDNS until the speaker appears (~15-30 s)
|
||||
echo "Waiting for speaker on LAN..."
|
||||
until dns-sd -B _soundtouch._tcp local 2>&1 | grep -m1 "Add"; do sleep 2; done
|
||||
echo "Speaker is online"
|
||||
|
||||
# Resolve its IP
|
||||
dns-sd -L "$(dns-sd -B _soundtouch._tcp local 2>&1 | grep Add | awk '{print $7}')" \
|
||||
_soundtouch._tcp local 2>&1 | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'
|
||||
```
|
||||
|
||||
Or just scan for open port 8090:
|
||||
|
||||
```bash
|
||||
# Quick scan of your /24 subnet for port 8090
|
||||
SUBNET="192.168.1" # adjust to your local subnet
|
||||
for i in $(seq 1 254); do
|
||||
(ping -c1 -W1 ${SUBNET}.$i &>/dev/null && \
|
||||
nc -z -w1 ${SUBNET}.$i 8090 2>/dev/null && \
|
||||
echo "${SUBNET}.$i") &
|
||||
done
|
||||
wait
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Start mitmproxy, Emulator, Frida
|
||||
|
||||
Run each block in a separate terminal tab.
|
||||
|
||||
### 3.1 Start mitmweb (native macOS app)
|
||||
|
||||
> **Note:** Docker mitmproxy does not work here — its NAT layer prevents the emulator from reaching it. Use the native macOS app instead (download: `https://downloads.mitmproxy.org/12.2.2/mitmproxy-12.2.2-macos-arm64.tar.gz`).
|
||||
|
||||
```bash
|
||||
CAPTURE="bose-pairing-$(date +%Y%m%d-%H%M%S).mitm"
|
||||
/Applications/mitmproxy.app/Contents/MacOS/mitmweb \
|
||||
--web-host 0.0.0.0 --listen-port 8080 --mode regular \
|
||||
--set web_password=bose \
|
||||
-w "scripts/android/captures/${CAPTURE}"
|
||||
# Captures → scripts/android/captures/
|
||||
# Web UI → http://127.0.0.1:8081/?token=bose
|
||||
```
|
||||
|
||||
### 3.2 Start Emulator
|
||||
|
||||
```bash
|
||||
~/Library/Android/sdk/emulator/emulator -avd Pixel_6_API33 -writable-system &
|
||||
echo "Waiting for emulator boot..."
|
||||
adb wait-for-device
|
||||
adb -s emulator-5554 wait-for-device shell 'while [[ -z $(getprop sys.boot_completed) ]]; do sleep 1; done'
|
||||
echo "Emulator ready"
|
||||
```
|
||||
|
||||
Enable root and install certificate (only needed once per emulator session):
|
||||
|
||||
```bash
|
||||
adb -s emulator-5554 root
|
||||
adb -s emulator-5554 shell avbctl disable-verification
|
||||
adb -s emulator-5554 reboot
|
||||
adb -s emulator-5554 wait-for-device
|
||||
adb -s emulator-5554 root
|
||||
|
||||
HASH=$(openssl x509 -inform PEM -subject_hash_old \
|
||||
-in ~/.mitmproxy/mitmproxy-ca-cert.pem | head -1)
|
||||
|
||||
adb -s emulator-5554 push ~/.mitmproxy/mitmproxy-ca-cert.pem /data/local/tmp/mitmproxy.pem
|
||||
adb -s emulator-5554 shell su 0 mkdir -p /data/misc/user/0/cacerts-added
|
||||
adb -s emulator-5554 shell su 0 \
|
||||
cp /data/local/tmp/mitmproxy.pem /data/misc/user/0/cacerts-added/${HASH}.0
|
||||
adb -s emulator-5554 shell su 0 \
|
||||
chmod 644 /data/misc/user/0/cacerts-added/${HASH}.0
|
||||
```
|
||||
|
||||
Set proxy to Mac IP:
|
||||
|
||||
```bash
|
||||
MAC_IP=$(ipconfig getifaddr en0)
|
||||
adb -s emulator-5554 shell settings put global http_proxy "${MAC_IP}:8080"
|
||||
echo "Proxy set to ${MAC_IP}:8080"
|
||||
```
|
||||
|
||||
Confirm emulator can reach the speaker:
|
||||
|
||||
```bash
|
||||
SPEAKER_IP=192.168.1.50 # adjust to your speaker's LAN IP
|
||||
adb -s emulator-5554 shell ping -c 3 "$SPEAKER_IP"
|
||||
```
|
||||
|
||||
### 3.3 Start frida-server
|
||||
|
||||
```bash
|
||||
adb -s emulator-5554 push scripts/android/frida-server /data/local/tmp/frida-server
|
||||
adb -s emulator-5554 shell su 0 chmod 755 /data/local/tmp/frida-server
|
||||
adb -s emulator-5554 shell su 0 "nohup /data/local/tmp/frida-server > /dev/null 2>&1 &"
|
||||
sleep 2
|
||||
echo "frida-server running"
|
||||
```
|
||||
|
||||
### 3.4 Configure config.js
|
||||
|
||||
`start-mitm-session.sh` patches `scripts/android/frida/config.js` automatically with the current Mac IP and mitmproxy cert. No manual step needed.
|
||||
|
||||
### 3.5 Launch App with SSL Unpinning
|
||||
|
||||
```bash
|
||||
scripts/android/frida-venv/bin/frida \
|
||||
-U \
|
||||
-f com.bose.soundtouch \
|
||||
-l scripts/android/frida/config.js \
|
||||
-l scripts/android/frida/native-connect-hook.js \
|
||||
-l scripts/android/frida/android/android-system-certificate-injection.js \
|
||||
-l scripts/android/frida/android/android-proxy-override.js \
|
||||
-l scripts/android/frida/android/android-certificate-unpinning.js \
|
||||
-l scripts/android/frida/android/android-certificate-unpinning-fallback.js
|
||||
```
|
||||
|
||||
> `native-connect-hook.js` is required — the Bose app uses native networking that bypasses Java proxy settings.
|
||||
|
||||
Expected Frida output:
|
||||
|
||||
```
|
||||
== System certificate trust injected ==
|
||||
== Proxy system configuration overridden to <IP>:8080 ==
|
||||
== Proxy configuration overridden to <IP>:8080 ==
|
||||
== Certificate unpinning completed ==
|
||||
== Unpinning fallback auto-patcher installed ==
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — Pair Speaker via App
|
||||
|
||||
The Bose app should now be running in the emulator with all traffic going through mitmproxy.
|
||||
|
||||
### 4.1 Inspect UI to Find Interactive Elements
|
||||
|
||||
```bash
|
||||
# Dump current screen
|
||||
adb -s emulator-5554 shell uiautomator dump /sdcard/ui.xml
|
||||
adb -s emulator-5554 pull /sdcard/ui.xml /tmp/ui.xml
|
||||
|
||||
# Helper: list all clickable elements with their text + bounds
|
||||
grep -o 'text="[^"]*" resource-id="[^"]*" \.\.\. clickable="true"[^/]*' /tmp/ui.xml \
|
||||
|| python3 -c "
|
||||
import xml.etree.ElementTree as ET
|
||||
tree = ET.parse('/tmp/ui.xml')
|
||||
for n in tree.iter('node'):
|
||||
if n.get('clickable') == 'true' and n.get('text'):
|
||||
print(n.get('bounds'), n.get('resource-id'), repr(n.get('text')))
|
||||
"
|
||||
```
|
||||
|
||||
### 4.2 Navigate Setup Flow (adb)
|
||||
|
||||
```bash
|
||||
# Take a screenshot at any point to see current state
|
||||
adb -s emulator-5554 shell screencap /sdcard/screen.png
|
||||
adb -s emulator-5554 pull /sdcard/screen.png /tmp/screen.png
|
||||
open /tmp/screen.png
|
||||
|
||||
# Tap by resource-id (find IDs from ui.xml dump)
|
||||
adb -s emulator-5554 shell uiautomator runtest ... # or input tap
|
||||
|
||||
# Tap by screen coordinates
|
||||
adb -s emulator-5554 shell input tap X Y
|
||||
|
||||
# Type into the focused field
|
||||
adb -s emulator-5554 shell input text "your@email.com"
|
||||
|
||||
# Press Enter / Next
|
||||
adb -s emulator-5554 shell input keyevent 66
|
||||
```
|
||||
|
||||
### 4.3 Expected Setup Steps in the App
|
||||
|
||||
Follow the on-screen flow; mitmproxy captures everything automatically.
|
||||
|
||||
1. **Sign in** — enter email + password → triggers `POST /streaming/account/login`
|
||||
2. **Add speaker** — tap "Set Up a New Speaker" or equivalent
|
||||
3. **App discovers speaker** via mDNS on LAN (no BLE required)
|
||||
4. **Wi-Fi already configured** — app skips the Wi-Fi step since speaker is online
|
||||
5. **Name speaker** — type a name → WebSocket `name` message to speaker port 8080
|
||||
6. **Pairing** — app sends `setMargeAccount` WebSocket to speaker → speaker POSTs to `streaming.bose.com/{accountId}/devices`
|
||||
|
||||
All cloud requests (steps 1, 6) will appear in mitmweb at `http://127.0.0.1:8081`.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5 — Save & Inspect Recording
|
||||
|
||||
```bash
|
||||
# Stop mitmweb (Ctrl-C in its terminal) — file is already written continuously
|
||||
|
||||
# Inspect offline in the web UI
|
||||
mitmweb -r "$CAPTURE"
|
||||
|
||||
# Filter to streaming.bose.com only
|
||||
mitmdump -r "$CAPTURE" --flow-filter '~u streaming.bose.com' -w bose-cloud-only.mitm
|
||||
|
||||
# Quick text summary
|
||||
mitmdump -r "$CAPTURE" --flow-filter '~u streaming.bose.com' 2>/dev/null \
|
||||
| grep -E "POST|GET" | head -30
|
||||
```
|
||||
|
||||
### Convert to .http files (IntelliJ-compatible)
|
||||
|
||||
Use `scripts/convert_mitm_script.py` to extract each flow as a `.http` file, organized by path:
|
||||
|
||||
```bash
|
||||
NAME=$(basename "$CAPTURE" .mitm)
|
||||
OUT="scripts/android/mitm/${NAME}"
|
||||
|
||||
/Applications/mitmproxy.app/Contents/MacOS/mitmdump \
|
||||
-n -r "$CAPTURE" \
|
||||
-s scripts/convert_mitm_script.py \
|
||||
--set out_dir="${OUT}"
|
||||
```
|
||||
|
||||
Output lands in `scripts/android/mitm/<name>/mirror/` as numbered `.http` files
|
||||
plus `*-websocket/` subdirectories for WebSocket frames. The directory is gitignored.
|
||||
|
||||
---
|
||||
|
||||
## Cleanup
|
||||
|
||||
```bash
|
||||
# Remove proxy from emulator
|
||||
adb -s emulator-5554 shell settings delete global http_proxy
|
||||
|
||||
# Kill emulator
|
||||
adb -s emulator-5554 emu kill
|
||||
```
|
||||
|
||||
Frida artefacts live in `scripts/android/` (gitignored) and persist between sessions — no cleanup needed unless you want to force a fresh setup.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Likely cause | Fix |
|
||||
|-------------------------------------|--------------------------------------------------|-----------------------------------------------------------------------------------|
|
||||
| `curl http://192.0.2.1` times out | Mac not on speaker AP | Re-run `networksetup -setairportnetwork`; speaker AP gateway is `192.0.2.1` |
|
||||
| `addWirelessProfile` returns error | Speaker not in AP mode or wrong IP | Confirm speaker AP is active; use `http://192.0.2.1:8090/addWirelessProfile` |
|
||||
| Speaker not found via mDNS | Speaker still on AP (not home LAN yet) | Wait ~30 s, retry; check router DHCP leases |
|
||||
| Emulator can't ping speaker | Different subnet or emulator proxy misconfigured | `adb shell ping` the Mac IP first; check proxy setting |
|
||||
| App shows "No speakers found" | App not detecting mDNS | Ensure emulator is on same `/24` as speaker; disable emulator Wi-Fi and re-enable |
|
||||
| No traffic in mitmweb | Frida not running or cert mismatch | Check Frida output for `== Certificate unpinning ==`; verify issuer in config.js |
|
||||
|
||||
## See Also
|
||||
|
||||
- [BOSE-APP-ADB-Emulator.md](../analysis/BOSE-APP-ADB-Emulator.md) — full MITM + Frida setup
|
||||
- [DEVICE-INITIAL-SETUP.md](DEVICE-INITIAL-SETUP.md) — factory reset sequences + AP mode detail
|
||||
- [DEVICE-SETUP.md](../DEVICE-SETUP.md) — WebSocket and cloud pairing protocol reference
|
||||
|
||||
---
|
||||
|
||||
## Session Trace (2026-05-02, ST10)
|
||||
|
||||
Raw log of the first interactive run. To be cleaned up into the runbook above.
|
||||
|
||||
### Setup
|
||||
- Ran `scripts/android/setup-mitm-avd.sh` — all 9 steps completed:
|
||||
- Steps 1–5 were already done from a prior session (idempotent skips)
|
||||
- Step 6: Docker image built, `frida-server` extracted to `scripts/android/frida-server`
|
||||
- Steps 7–9: Emulator started fresh (`-no-snapshot-load`), AVB disabled, rebooted, cert + APK + frida-server installed, snapshot `mitm-ready` saved
|
||||
- Emulator running at `emulator-5554`
|
||||
|
||||
### Factory Reset (ST10)
|
||||
- Correct sequence confirmed from official Bose guide (`firmware/FirmwareUpdateGuide/`):
|
||||
**Power on → hold Preset 1 + Volume − for 10 s → Wi-Fi LED glows solid amber**
|
||||
- Note: original docs said "Vol− + Mute" — corrected in DEVICE-INITIAL-SETUP.md and this file
|
||||
|
||||
### Pre-reset note
|
||||
- User inserted USB device containing `remote_services` before rebooting — device needs to be on home Wi-Fi before the USB config takes effect
|
||||
|
||||
### Wi-Fi Provisioning (AP mode)
|
||||
- `airport` command not available on this macOS version (removed in recent releases)
|
||||
- Connect Mac to speaker AP via **System Settings → Wi-Fi** (SSID: "Bose SoundTouch XXXX")
|
||||
- Speaker AP gateway confirmed: `192.0.2.1` (client gets `192.0.2.2`), not `192.168.1.1` as previously assumed
|
||||
- `/gabbo_wifi` endpoint was hallucinated — actual endpoint verified from browser network capture (`_/device-reset/wifi-setup.txt`):
|
||||
- Site survey: `POST http://192.0.2.1:8090/performWirelessSiteSurvey` with `<PerformWirelessSiteSurvey timeout="5"/>`
|
||||
- Add profile: `POST http://192.0.2.1:8090/addWirelessProfile` with XML body, `securityType="wpa_or_wpa2"`
|
||||
- Both use the standard SoundTouch API port 8090, same as normal device operation
|
||||
- Response: `<AddWirelessProfileResponse />`
|
||||
- Reconnect Mac to home Wi-Fi; emulator stays running throughout (routes through Mac interface)
|
||||
|
||||
### Wi-Fi Provisioning Result
|
||||
- `POST http://192.0.2.1:8090/addWirelessProfile` succeeded → `<AddWirelessProfileResponse />`
|
||||
- Speaker joined home LAN at `192.168.x.y`
|
||||
- SSH access confirmed: `ssh -oHostKeyAlgorithms=ssh-rsa root@192.168.x.y`
|
||||
- Device name: `Bose SoundTouch XXXXXX`
|
||||
- Network interfaces on device:
|
||||
- `wlan0` → `192.168.x.y` (home LAN)
|
||||
- `wlan1` → `192.0.2.1` (AP mode interface, stays up after provisioning)
|
||||
- `usb0` → `203.0.113.1` (USB gadget — remote_services USB device inserted before reboot)
|
||||
|
||||
### MITM Session Start
|
||||
- `start-mitm-session.sh` run: snapshot restored, proxy set, frida-server started, config.js patched
|
||||
- Issues encountered and fixed:
|
||||
- frida-server start command hung (`adb shell su 0 ... &`) → fixed with `nohup ... > /dev/null 2>&1 &`
|
||||
- Frida SSL scripts download via `curl` from GitHub timed out → moved to Dockerfile (extracted alongside frida-server)
|
||||
- Python heredoc cert injection syntax error (multiline cert in string) → fixed using env vars + single-quoted `'PYEOF'` heredoc
|
||||
- `mitmweb --port` deprecated → `--listen-port`
|
||||
- frida script paths missing `android/` subdirectory → fixed in session script
|
||||
- Docker mitmproxy (`-p 8080:8080`) received no traffic from emulator — Docker NAT layer prevented the emulator reaching it
|
||||
- **Fix: use native macOS mitmproxy app** (`/Users/gesellix/Downloads/mitmproxy.app`) — binds directly to Mac's real network interfaces, traffic flows immediately
|
||||
- Android system traffic visible (connectivity checks to gstatic.com, www.google.com) — TLS failures for system processes expected since only Bose app has Frida cert injection
|
||||
|
||||
### Capture Working
|
||||
- Full flow confirmed working with:
|
||||
- Native mitmproxy app (`~/Downloads/mitmproxy.app`, v12.2.2)
|
||||
- `native-connect-hook.js` added to Frida launch (required for Bose app's native networking)
|
||||
- All 5 Frida scripts loaded: config.js, native-connect-hook.js, android-system-certificate-injection.js, android-proxy-override.js, android-certificate-unpinning.js, android-certificate-unpinning-fallback.js
|
||||
- Bose app traffic visible in mitmweb — pairing flow captured successfully
|
||||
@@ -0,0 +1,378 @@
|
||||
# Capture Speaker Migration Traffic
|
||||
|
||||
Runbook for migrating a SoundTouch speaker to `soundtouch-service` and capturing
|
||||
all traffic (App→Service and Speaker→Service) to identify unimplemented endpoints.
|
||||
|
||||
**Goal:** obtain a complete picture of every cloud request a speaker and the Bose
|
||||
app make after migration, so missing endpoint implementations can be tracked down.
|
||||
|
||||
**Pre-requisites:** the MITM pipeline is already set up and working. See
|
||||
[CAPTURE-DEVICE-PAIRING.md](CAPTURE-DEVICE-PAIRING.md) for the one-time AVD setup
|
||||
and the pairing capture runbook.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
```
|
||||
Step 1 Start soundtouch-service locally (with interaction recording)
|
||||
Step 2 Start a fresh mitmproxy + Frida session (captures App traffic)
|
||||
Step 3 Discover or register the speaker in the service UI
|
||||
Step 4 Migrate the speaker (modifies SoundTouchSdkPrivateCfg.xml via SSH)
|
||||
Step 5 Operate the Bose app — everything now flows through local service
|
||||
Step 6 Inspect captured interactions for unimplemented endpoints
|
||||
Step 7 Revert (optional) / clean up
|
||||
```
|
||||
|
||||
Traffic sources:
|
||||
- **App → Service** — captured by mitmproxy + Frida (same as pairing capture)
|
||||
- **Speaker → Service** — captured by the service's built-in interaction recorder
|
||||
|
||||
---
|
||||
|
||||
## Step 1 — Start soundtouch-service
|
||||
|
||||
Build and start the service. Recording is on by default; add `--server-url` so the
|
||||
service knows its own public address (the speaker needs it for redirections).
|
||||
|
||||
```bash
|
||||
# Determine Mac LAN IP first
|
||||
MAC_IP=$(ipconfig getifaddr en0)
|
||||
echo "Mac IP: ${MAC_IP}"
|
||||
|
||||
# Build + run with explicit server-url so the service embeds the correct address
|
||||
make build-service
|
||||
./build/soundtouch-service \
|
||||
--server-url "http://${MAC_IP}:8000" \
|
||||
--record-interactions \
|
||||
--log-bodies
|
||||
```
|
||||
|
||||
Service listens on `:8000` by default. Web UI: `http://localhost:8000`
|
||||
|
||||
> To also enable mirror mode (forward unhandled requests to official Bose servers
|
||||
> for comparison), add: `--mirror-enabled --mirror-endpoints /streaming/`
|
||||
|
||||
---
|
||||
|
||||
## Step 2 — Start mitmproxy + Frida (new capture)
|
||||
|
||||
In a separate terminal:
|
||||
|
||||
```bash
|
||||
scripts/android/start-mitm-session.sh
|
||||
```
|
||||
|
||||
The script prints ready-to-run commands for mitmweb and Frida. Run each in its own
|
||||
terminal tab as instructed.
|
||||
|
||||
New capture file lands in `scripts/android/captures/`.
|
||||
|
||||
---
|
||||
|
||||
## Step 3 — Discover the Speaker
|
||||
|
||||
Open the service web UI at `http://localhost:8000`.
|
||||
|
||||
The service discovers speakers via mDNS automatically on startup. If the speaker
|
||||
does not appear within ~30 s, add it manually:
|
||||
|
||||
```bash
|
||||
# Via API (replace IP with speaker's current LAN IP)
|
||||
curl -s -X POST http://localhost:8000/setup/devices \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"ip": "192.168.x.y"}'
|
||||
|
||||
# Confirm it's registered
|
||||
curl -s http://localhost:8000/setup/devices | python3 -m json.tool
|
||||
```
|
||||
|
||||
Note the `device_id` from the response — you need it for migration.
|
||||
|
||||
```bash
|
||||
# List all known devices and their IDs
|
||||
curl -s http://localhost:8000/setup/devices | python3 -m json.tool
|
||||
|
||||
# Extract device_id for the speaker by matching its IP
|
||||
DEVICE_ID=$(curl -s http://localhost:8000/setup/devices \
|
||||
| python3 -c "import sys,json; devs=json.load(sys.stdin); \
|
||||
[print(d['device_id']) for d in devs if '35' in d.get('ip_address','')]")
|
||||
echo "Device ID: ${DEVICE_ID}"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 4 — Migrate the Speaker
|
||||
|
||||
The migration modifies `SoundTouchSdkPrivateCfg.xml` on the speaker via SSH,
|
||||
redirecting `margeServerUrl` (and optionally other service URLs) to the local
|
||||
service.
|
||||
|
||||
### 4.1 Review the Migration Plan
|
||||
|
||||
```bash
|
||||
# Dry-run: see what will be changed
|
||||
curl -s "http://localhost:8000/setup/summary/${DEVICE_ID}" | python3 -m json.tool
|
||||
```
|
||||
|
||||
Key fields to check:
|
||||
- `margeServerUrl` — should become `http://<MAC_IP>:8000/streaming`
|
||||
- `remoteServicesEnabled` — must be `true` for the speaker to make cloud calls
|
||||
- `is_migrated` — `false` before, `true` after
|
||||
|
||||
### 4.2 Run Migration
|
||||
|
||||
```bash
|
||||
MAC_IP=$(ipconfig getifaddr en0)
|
||||
TARGET_URL="http://${MAC_IP}:8000"
|
||||
|
||||
curl -s -X POST \
|
||||
"http://localhost:8000/setup/migrate/${DEVICE_ID}" \
|
||||
-G --data-urlencode "target_url=${TARGET_URL}" \
|
||||
| python3 -m json.tool
|
||||
```
|
||||
|
||||
Expected response: `{"ok": true, "message": "Migration started", "output": "..."}`.
|
||||
The output field contains the SSH transcript of the changes made.
|
||||
|
||||
### 4.3 Reboot the Speaker
|
||||
|
||||
A reboot applies the new config:
|
||||
|
||||
```bash
|
||||
curl -s -X POST "http://localhost:8000/setup/reboot/${DEVICE_ID}"
|
||||
```
|
||||
|
||||
Wait ~30 s for the speaker to come back online. Verify it's back:
|
||||
|
||||
```bash
|
||||
dns-sd -B _soundtouch._tcp local 2>&1 | grep Add
|
||||
# or
|
||||
curl -s http://192.168.x.y:8090/info | head -5
|
||||
```
|
||||
|
||||
### 4.4 Verify Migration
|
||||
|
||||
```bash
|
||||
# Check migration summary again — is_migrated should now be true
|
||||
curl -s "http://localhost:8000/setup/summary/${DEVICE_ID}" \
|
||||
| python3 -c "import sys,json; s=json.load(sys.stdin); print('migrated:', s.get('is_migrated'))"
|
||||
```
|
||||
|
||||
You should also see incoming connections from the speaker in the service logs once
|
||||
it resumes normal operation.
|
||||
|
||||
---
|
||||
|
||||
## Step 5 — Operate the Bose App
|
||||
|
||||
With the speaker migrated and Frida running, every app action triggers traffic
|
||||
through the service:
|
||||
|
||||
1. **Sign in** — `POST /streaming/account/login`
|
||||
2. **Speaker shows as linked** — speaker has called the service to register/sync
|
||||
3. **Play music** — BMX registry lookup, playback control
|
||||
4. **Set presets** — `POST /streaming/account/{id}/device/{id}/presets/{n}`
|
||||
5. **Adjust volume, switch source** — direct speaker API (port 8090, not cloud)
|
||||
6. **Check "Now Playing"** — speaker WebSocket events + marge sync
|
||||
|
||||
For each action, both mitmweb and the service's recorder capture the request.
|
||||
|
||||
---
|
||||
|
||||
## Step 6 — Inspect Captured Interactions
|
||||
|
||||
### 6.1 Service Interaction Recorder
|
||||
|
||||
The service records all incoming requests to `data/interactions/` (configurable via
|
||||
`--data-dir`). Browse them via:
|
||||
|
||||
```bash
|
||||
# List recorded sessions
|
||||
curl -s http://localhost:8000/setup/interactions | python3 -m json.tool
|
||||
|
||||
# Download a session as HAR
|
||||
curl -s "http://localhost:8000/setup/interactions/sessions/<session>/download" \
|
||||
-o session.har
|
||||
|
||||
# Find 404/500 responses (unimplemented endpoints)
|
||||
curl -s "http://localhost:8000/setup/interaction-content" \
|
||||
| python3 -c "
|
||||
import sys, json
|
||||
for entry in json.load(sys.stdin).get('entries', []):
|
||||
status = entry.get('response', {}).get('status', 0)
|
||||
if status >= 400:
|
||||
print(status, entry.get('request', {}).get('method'), entry.get('request', {}).get('url'))
|
||||
"
|
||||
```
|
||||
|
||||
### 6.2 mitmproxy Recording
|
||||
|
||||
```bash
|
||||
# Inspect app→service traffic offline
|
||||
CAPTURE="scripts/android/captures/<filename>.mitm"
|
||||
mitmweb -r "${CAPTURE}"
|
||||
|
||||
# Filter to local service only
|
||||
mitmdump -r "${CAPTURE}" \
|
||||
--flow-filter "~u ${MAC_IP}:8000" \
|
||||
2>/dev/null | grep -E "POST|GET"
|
||||
|
||||
# Convert to .http files (IntelliJ-compatible, organized by path)
|
||||
NAME=$(basename "${CAPTURE}" .mitm)
|
||||
OUT="scripts/android/mitm/${NAME}"
|
||||
|
||||
/Applications/mitmproxy.app/Contents/MacOS/mitmdump \
|
||||
-n -r "${CAPTURE}" \
|
||||
-s scripts/convert_mitm_script.py \
|
||||
--set out_dir="${OUT}"
|
||||
# Output → scripts/android/mitm/<name>/mirror/
|
||||
```
|
||||
|
||||
### 6.3 Identify Unimplemented Endpoints
|
||||
|
||||
Endpoints the service doesn't handle return `404 Not Found`. Check:
|
||||
|
||||
```bash
|
||||
# From service stats
|
||||
curl -s http://localhost:8000/setup/interaction-stats | python3 -m json.tool
|
||||
|
||||
# List parity mismatches (local vs upstream divergence, if mirror enabled)
|
||||
curl -s http://localhost:8000/setup/parity-mismatches | python3 -m json.tool
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 7 — Revert Migration (Optional)
|
||||
|
||||
To restore the speaker to its original config (pointing back to Bose cloud):
|
||||
|
||||
```bash
|
||||
curl -s -X POST "http://localhost:8000/setup/revert/${DEVICE_ID}" | python3 -m json.tool
|
||||
```
|
||||
|
||||
Then reboot the speaker:
|
||||
|
||||
```bash
|
||||
curl -s -X POST "http://localhost:8000/setup/reboot/${DEVICE_ID}"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Cleanup
|
||||
|
||||
```bash
|
||||
# Stop mitmweb (Ctrl-C in its terminal)
|
||||
# Stop Frida (Ctrl-C in its terminal)
|
||||
# Stop soundtouch-service (Ctrl-C in its terminal)
|
||||
|
||||
# Remove emulator proxy (if not running another session)
|
||||
adb -s emulator-5554 shell settings delete global http_proxy
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Cause | Fix |
|
||||
|-------------------------------------------|--------------------------------------------|---------------------------------------------------------------------------|
|
||||
| Speaker not in service device list | mDNS discovery hasn't fired yet | Trigger manually: `POST /setup/discover` or add via `POST /setup/devices` |
|
||||
| Migration fails with SSH error | Speaker SSH key not trusted | Run `POST /setup/trust-ca/{deviceId}` first, or check SSH connectivity |
|
||||
| Speaker can't reach service after reboot | Firewall blocking port 8000 from LAN | Allow inbound TCP 8000 on Mac firewall |
|
||||
| `is_migrated: false` after migration | Wrong `target_url` or config not written | Check SSH output in migration response; re-run with `--method xml` |
|
||||
| Service logs show no speaker requests | `remote_services` not enabled on speaker | Run `POST /setup/ensure-remote-services/{deviceId}` and reboot |
|
||||
| App shows speaker offline after migration | Speaker config not pointing to correct URL | Check `margeServerUrl` via `GET /setup/summary/{deviceId}` |
|
||||
|
||||
---
|
||||
|
||||
## Session Trace (2026-05-02, ST10)
|
||||
|
||||
Raw log of the first interactive migration run.
|
||||
|
||||
### Service Configuration
|
||||
|
||||
Settings applied in the web UI before migration:
|
||||
|
||||
| Setting | Value |
|
||||
|---------------------|---------------------------------------------------------------------|
|
||||
| Target Domain | `soundtouch.local` (resolvable from speaker to `192.168.x.z`) |
|
||||
| DNS Discovery | enabled |
|
||||
| Upstream DNS | home Wi-Fi gateway |
|
||||
| Mirroring | enabled (for tracing while Bose cloud is still up) |
|
||||
| Mirrored endpoints | `/bmx/*`, `/streaming/*`, `/accounts/*`, `/v1/scmudc/*`, `/oauth/*` |
|
||||
| Proxy logging | enabled, including bodies |
|
||||
| Record interactions | enabled |
|
||||
| Skip recording | `/setup/*`, `/web/*` |
|
||||
|
||||
Settings saved and service restarted.
|
||||
|
||||
### Navigation Flow
|
||||
|
||||
1. **Tab 1 — Settings**: entered all settings above, clicked **Save Settings**, restarted service
|
||||
2. **Tab 2 — Devices**: speaker appeared via mDNS discovery; clicked **Sync Data**
|
||||
3. **Tab 3 — Data Sync**: clicked **Start Sync** to pull account/device data from Bose cloud
|
||||
4. **Tab 2 — Devices**: clicked **Migrate** on the speaker entry
|
||||
5. In the Migrate panel: selected **Migration Method → `/etc/resolv.conf`**
|
||||
6. Ran pre-migration checks (see below)
|
||||
7. Ran migration steps (see below)
|
||||
8. Rebooted speaker
|
||||
9. Paired and configured speaker via the Bose app
|
||||
|
||||
### Pre-Migration Checks
|
||||
|
||||
All tests run from the **Devices → Migrate** panel after selecting the speaker (`192.168.x.y`, SoundTouch 10):
|
||||
|
||||
- **HTTPS test (explicit CA.crt)**: ✅ passed (result not recorded in detail)
|
||||
- **HTTPS test (shared trust store)**: ✅ passed
|
||||
- Speaker connected to `soundtouch.local:443` → `192.168.x.z`
|
||||
- TLS: TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256, cert issued by `SoundTouch Local Root CA`
|
||||
- CA already in speaker's system trust store (`/etc/pki/tls/certs/ca-bundle.crt`)
|
||||
- **Preliminary DNS Test**: ✅ passed
|
||||
- Raw DNS query for `aftertouch.test` returned `192.168.x.z` via the service DNS at `192.168.x.z:53`
|
||||
- **Planned `/etc/resolv.conf`**:
|
||||
```
|
||||
# Created by Aftertouch/SoundTouch-Service
|
||||
# Priority nameserver for Bose service redirection
|
||||
nameserver 192.168.x.z
|
||||
```
|
||||
|
||||
### Migration Steps
|
||||
|
||||
1. **Enable Persistent Remote Services** → `Successfully ensured remote services for SoundTouch 10 (192.168.x.y)`
|
||||
- Note: `touch /etc/remote_services (with rw): sh: rw: command not found` — safe to ignore, `touch` succeeded
|
||||
2. Reloaded migration view by deselecting and reselecting the speaker in the dropdown
|
||||
3. **Backup Config Now** → `✅ Found .original config at /opt/Bose/etc/SoundTouchSdkPrivateCfg.xml.original`
|
||||
4. **Confirm Migration** → `Successfully started migration for SoundTouch 10 (192.168.x.y). Please reboot the device to activate the changes.`
|
||||
|
||||
Command output:
|
||||
- Off-device backup created ✅
|
||||
- Write access verified ✅
|
||||
- `soundtouch.local` resolved to `192.168.x.z` ✅
|
||||
- `/mnt/nv/soundtouch-service/aftertouch.resolv.conf` uploaded ✅
|
||||
- `rc.local` already contains Aftertouch hook logic ✅
|
||||
- `(rw || mount -o remount,rw /): sh: rw: command not found` — safe to ignore (same shell quirk as above)
|
||||
- `/etc/udhcpc.d/50default` patched and verified ✅
|
||||
- `/opt/Bose/udhcpc.script` patched and verified ✅
|
||||
- CA certificate already trusted, skipping injection ✅
|
||||
|
||||
5. **Reboot Speaker** → speaker came back online after ~30 s
|
||||
|
||||
### Post-Migration
|
||||
|
||||
- Paired speaker to Bose account via app — succeeded ✅
|
||||
- Set presets via app — worked ✅
|
||||
- Mirroring active and functional during session ✅
|
||||
- No visible errors in app behaviour; service logs and interaction recordings not yet reviewed in detail
|
||||
|
||||
### Known Shell Warning (safe to ignore)
|
||||
|
||||
Two commands produced `sh: rw: command not found`. This occurs because the service wraps commands with `(rw || ...)` as a fallback pattern, but the shell on the ST10 interprets `rw` as a bare command rather than a shell variable/flag. The primary command (`touch`, `mount`) still succeeds. This is a known cosmetic issue in the migration output.
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [CAPTURE-DEVICE-PAIRING.md](CAPTURE-DEVICE-PAIRING.md) — MITM setup and pairing capture
|
||||
- [MIGRATION-GUIDE.md](MIGRATION-GUIDE.md) — full migration reference
|
||||
- [SOUNDTOUCH-SERVICE.md](SOUNDTOUCH-SERVICE.md) — service architecture and configuration
|
||||
- [BOSE-APP-ADB-Emulator.md](../analysis/BOSE-APP-ADB-Emulator.md) — Frida + mitmproxy setup
|
||||
@@ -25,13 +25,17 @@ Used by most modern SoundTouch devices (ST-10, ST-20/30 Series III, SoundTouch 3
|
||||
The classic "failover" or "alternate" setup method.
|
||||
|
||||
- **Mechanism**: The device creates its own Wi-Fi network (SSID: `Bose SoundTouch ...` or `Bose Home Speaker ...`).
|
||||
- **IP Address**: Typically `192.168.1.1` or `10.0.0.1` (device-side).
|
||||
- **IP Address**: Typically `192.0.2.1` (device-side, verified on ST10).
|
||||
- **Web Interface**: The device hosts a web server on port 80.
|
||||
- **Process**:
|
||||
1. Connect a PC/Phone to the device's Wi-Fi.
|
||||
2. Open a browser to `http://192.168.1.1`.
|
||||
3. The device serves `setup.html`, which redirects to a setup wizard (`setup/index.html`).
|
||||
4. Use the `gabbo_wifi` form to select a network and enter credentials.
|
||||
2. Open a browser to `http://192.0.2.1`.
|
||||
3. The device serves a Wi-Fi setup form — enter your home network SSID and password and click Submit.
|
||||
4. The device disconnects from AP mode and joins your home network within ~15–30 seconds.
|
||||
|
||||

|
||||
|
||||
For command-line provisioning (without a browser), see §6 below.
|
||||
|
||||
---
|
||||
|
||||
@@ -69,12 +73,96 @@ While the `soundtouch-service` focuses on migrating existing devices, a truly "c
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 5. Factory Reset Button Sequences
|
||||
|
||||
A factory reset wipes Wi-Fi credentials, account pairing, and all presets, returning the device to out-of-box state. The exact sequence varies by hardware generation.
|
||||
|
||||
> Sequences verified against official Bose reset guides in `firmware/FirmwareUpdateGuide/`. Confirm the reset succeeded by watching the status LEDs and by verifying the Wi-Fi indicator glows solid amber (setup mode).
|
||||
|
||||
| Model | Factory Restore Sequence | Confirm |
|
||||
|--------------------------|---------------------------------------------------------------------|------------------------------------|
|
||||
| SoundTouch 10 | Power on; hold **Preset 1** + **Volume −** for 10 s | Wi-Fi indicator glows solid amber |
|
||||
| SoundTouch 20 | Power on; hold **Preset 1** + **Volume −** for 10 s | Lights blink L→R, then solid amber |
|
||||
| SoundTouch 20 Series III | Hold **Preset 1** + **Preset 6** simultaneously for ~10 s | White LED sweep |
|
||||
| SoundTouch 30 Series III | Hold **Preset 1** + **Preset 6** simultaneously for ~10 s | White LED sweep |
|
||||
| SoundTouch 300 | Hold **Volume −** until light bar blinks rapidly (~15 s) | Rapid blink → off → on |
|
||||
| SoundTouch 10 (alt) | Press and hold the back recessed **Reset** pinhole for 10 s | Status LED restarts |
|
||||
| SoundTouch 20 (soft) | Hold **AUX** for 15 s until display goes blank (settings preserved) | Display blanks |
|
||||
|
||||
After factory restore the speaker enters setup mode automatically; no power-cycle is needed.
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
|
||||
### 6.1 Connect Mac to Speaker AP
|
||||
|
||||
After factory reset the speaker broadcasts an SSID like `Bose SoundTouch XXXX`. Connect the Mac to it:
|
||||
|
||||
```bash
|
||||
# List nearby SSIDs — use System Settings → Wi-Fi (the airport command was removed in macOS Sequoia+)
|
||||
# Connect (replace with actual SSID)
|
||||
networksetup -setairportnetwork en0 "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
|
||||
# Confirm reachability
|
||||
curl -sv http://192.0.2.1/ 2>&1 | head -40
|
||||
```
|
||||
|
||||
### 6.2 Trigger Wi-Fi Site Survey (Optional)
|
||||
|
||||
The setup web UI at `http://192.0.2.1/` uses the SoundTouch API on **port 8090** — the same API as normal device operation. Trigger a network scan first so the speaker finds your SSID:
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://192.0.2.1:8090/performWirelessSiteSurvey \
|
||||
-H 'Content-Type: text/xml' \
|
||||
--data-raw '<PerformWirelessSiteSurvey timeout="5"/>'
|
||||
```
|
||||
|
||||
### 6.3 Push Home Wi-Fi Credentials
|
||||
|
||||
```bash
|
||||
HOME_SSID="MyHomeNetwork"
|
||||
HOME_PASS="MyPassword"
|
||||
|
||||
curl -s -X POST http://192.0.2.1:8090/addWirelessProfile \
|
||||
-H 'Content-Type: text/xml' \
|
||||
--data-raw "<AddWirelessProfile><profile ssid=\"${HOME_SSID}\" password=\"${HOME_PASS}\" securityType=\"wpa_or_wpa2\" /></AddWirelessProfile>"
|
||||
```
|
||||
|
||||
Expected response: `<?xml version="1.0" encoding="UTF-8" ?><AddWirelessProfileResponse />`
|
||||
|
||||
The speaker will disconnect from AP mode and join the home network within ~15–30 s.
|
||||
|
||||
### 6.4 Reconnect Mac to Home Network
|
||||
|
||||
```bash
|
||||
networksetup -setairportnetwork en0 "MyHomeNetwork" "MyPassword"
|
||||
```
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Comparison: Initial Setup vs. Migration
|
||||
|
||||
| Feature | Initial Setup | Migration (soundtouch-service) |
|
||||
| :--- | :--- | :--- |
|
||||
| **Connectivity** | BLE, AP Mode, USB, WAC | Ethernet/Wi-Fi (existing) |
|
||||
| **Credentials** | Required (SSID/Pass) | Not required (uses existing) |
|
||||
| **Access** | Web UI / App protocol | SSH (root) |
|
||||
| **Primary File** | `setup/index.html` | `SoundTouchSdkPrivateCfg.xml` |
|
||||
| **Use Case** | Out-of-the-box / Reset | Redirecting active devices |
|
||||
| Feature | Initial Setup | Migration (soundtouch-service) |
|
||||
|:-----------------|:-----------------------|:-------------------------------|
|
||||
| **Connectivity** | BLE, AP Mode, USB, WAC | Ethernet/Wi-Fi (existing) |
|
||||
| **Credentials** | Required (SSID/Pass) | Not required (uses existing) |
|
||||
| **Access** | Web UI / App protocol | SSH (root) |
|
||||
| **Primary File** | `setup/index.html` | `SoundTouchSdkPrivateCfg.xml` |
|
||||
| **Use Case** | Out-of-the-box / Reset | Redirecting active devices |
|
||||
|
||||
@@ -1,81 +1,64 @@
|
||||
# HTTPS Setup & Custom CA Certificate
|
||||
# HTTPS & Custom CA Certificate
|
||||
|
||||
To use the `/etc/hosts` redirection method safely, SoundTouch devices must communicate over HTTPS. This requires the device to trust the AfterTouch Root CA certificate used by the local service.
|
||||
SoundTouch speakers communicate with cloud services over HTTPS. For the local service to work over HTTPS, speakers must trust the AfterTouch Root CA. The service manages this automatically — it generates a CA on first start and the web UI guides you through installing it on each speaker as part of the migration flow.
|
||||
|
||||
## 1. Automated Migration (Hosts Method)
|
||||
---
|
||||
|
||||
The `soundtouch-service` can automatically configure a device to use the `/etc/hosts` method:
|
||||
## How TLS works in AfterTouch
|
||||
|
||||
```bash
|
||||
curl -X POST "http://localhost:8000/setup/migrate/{deviceIP}?method=hosts"
|
||||
The service includes a built-in HTTPS listener (default port `8443`) that presents a certificate covering all Bose cloud hostnames. The certificate is signed by the AfterTouch Root CA, which is generated automatically on first start and stored in `data/certs/`.
|
||||
|
||||
**Domain coverage** — the certificate covers:
|
||||
- Wildcard: `*.api.bose.io`, `*.api.bosecm.com`
|
||||
- Specific: `streaming.bose.com`, `bmx.bose.com`, `stats.bose.com`, `updates.bose.com`, `worldwide.bose.com`, `bose-prod.apigee.net`, `media.bose.io`, `downloads.bose.com`, `voice.api.bose.io`, and more
|
||||
|
||||
> **Note**: The hostname you configure as `HTTPS_SERVER_URL` (e.g. `https://soundtouch.fritz.box:8443`) is also added as a Subject Alternative Name, ensuring valid TLS for direct browser or API access.
|
||||
|
||||
---
|
||||
|
||||
## CA trust installation (via web UI)
|
||||
|
||||
The migration flow in the web UI includes a CA trust step that:
|
||||
1. Uploads the Root CA to the speaker via SSH
|
||||
2. Appends it to the speaker's shared trust store (`/etc/pki/tls/certs/ca-bundle.crt`)
|
||||
3. Verifies connectivity over HTTPS
|
||||
|
||||
This is handled automatically — you don't need to manage CA files manually unless you're doing an advanced or manual setup.
|
||||
|
||||
---
|
||||
|
||||
## Downloading the CA certificate
|
||||
|
||||
You can download the Root CA for manual installation on other devices (phones, PCs, additional speakers):
|
||||
|
||||
```
|
||||
http://<server>:8000/setup/ca.crt
|
||||
```
|
||||
|
||||
This command will:
|
||||
1. Connect to the device via SSH.
|
||||
2. Update `/etc/hosts` to point Bose domains to the service IP.
|
||||
3. Inject the auto-generated AfterTouch Root CA into the device's trust store (`/etc/pki/tls/certs/ca-bundle.crt`).
|
||||
4. Reboot the device.
|
||||
---
|
||||
|
||||
## 2. Managing the Root CA
|
||||
## Binding to port 443
|
||||
|
||||
The AfterTouch service automatically generates a Root CA when it first starts.
|
||||
Speakers expect HTTPS on the default port 443. Since binding to port 443 requires elevated privileges, you have three options:
|
||||
|
||||
- **CA Certificate**: `data/certs/ca.crt`
|
||||
- **CA Private Key**: `data/certs/ca.key`
|
||||
1. **Port forwarding (recommended)**: Run the service on port 8443 and forward port 443 to it using `iptables` or your firewall/router.
|
||||
2. **Capabilities**: Grant the binary permission to bind low ports: `sudo setcap 'cap_net_bind_service=+ep' ./soundtouch-service`
|
||||
3. **Reverse proxy**: Use Nginx or Caddy in front of the service (see below).
|
||||
|
||||
### Downloading the CA Certificate
|
||||
You can download the CA certificate for manual installation on other devices (like your phone or PC) from:
|
||||
`http://<server-ip>:8000/setup/ca.crt`
|
||||
---
|
||||
|
||||
### 3. Built-in HTTPS Support
|
||||
## Reverse proxy (optional)
|
||||
|
||||
The `soundtouch-service` now includes a built-in HTTPS listener. This simplifies the `/etc/hosts` redirection method by automatically presenting the correct certificates for Bose domains.
|
||||
|
||||
- **HTTPS Port**: Configurable via `HTTPS_PORT` environment variable (defaults to `8443`).
|
||||
- **HTTPS Server URL**: Configurable via `HTTPS_SERVER_URL` (e.g., `https://mysoundtouch.local:8443`). If not set, the service attempts to guess it using the system hostname.
|
||||
- **Domain Coverage**: Automatically presents a certificate with comprehensive coverage using wildcard certificates (`*.api.bose.io`, `*.api.bosecm.com`) plus specific domains (`streaming.bose.com`, `updates.bose.com`, `stats.bose.com`, `bmx.bose.com`, `worldwide.bose.com`, `bose-prod.apigee.net`, etc.).
|
||||
- **Wildcard Support**: Uses RFC-compliant wildcard certificates for automatic coverage of all API subdomains, including event analytics endpoints like `events.api.bosecm.com`, `eventsdev.api.bosecm.com`, and future API services.
|
||||
- **TLS Error Logging**: Comprehensive logging of TLS handshake attempts, certificate matching, and connection failures for debugging DNS redirection issues.
|
||||
- **Automatic Setup**: On first start, it generates a server certificate signed by your AfterTouch local Root CA.
|
||||
|
||||
#### TLS Security & Debugging
|
||||
|
||||
The built-in HTTPS listener is configured to use modern and secure TLS settings while maintaining compatibility with SoundTouch devices (which support up to TLS 1.2 with OpenSSL 1.0.2).
|
||||
|
||||
- **Minimum TLS Version**: TLS 1.2
|
||||
- **Preferred Cipher Suites**:
|
||||
- `ECDHE-RSA-AES128-GCM-SHA256`
|
||||
- **TLS Debugging**: Detailed logging of:
|
||||
- Certificate requests by domain (`[TLS] Certificate request for ServerName: events.api.bosecm.com`)
|
||||
- Wildcard certificate matching (`[TLS] ✅ Serving certificate for events.api.bosecm.com (matched *.api.bosecm.com)`)
|
||||
- Handshake failures (`[TLS] ❌ Handshake failed from 192.168.1.50: tls: certificate not found`)
|
||||
- Successful connections (`[TLS] ✅ Successful connection from 192.168.1.50`)
|
||||
- `ECDHE-RSA-AES256-GCM-SHA384`
|
||||
- `ECDHE-RSA-CHACHA20-POLY1305`
|
||||
- `RSA-AES128-GCM-SHA256` (Legacy support)
|
||||
- `RSA-AES256-GCM-SHA384` (Legacy support)
|
||||
|
||||
#### Binding to Port 443
|
||||
SoundTouch devices expect HTTPS on the default port 443. Since binding to port 443 usually requires root privileges, you have two options:
|
||||
|
||||
1. **Port Forwarding (Recommended)**: Run the service on a high port (e.g., 8443) and use `iptables` or your firewall to forward traffic from 443 to 8443.
|
||||
2. **Capabilities**: Grant the binary permission to bind to low ports: `sudo setcap 'cap_net_bind_service=+ep' ./soundtouch-service`.
|
||||
3. **Reverse Proxy**: Use Nginx or Caddy as described below.
|
||||
|
||||
### 4. Reverse Proxy (Optional)
|
||||
|
||||
1. **Generate a certificate** for the Bose domains signed by your Root CA.
|
||||
2. **Configure Nginx** to use this certificate and proxy requests to `soundtouch-service`.
|
||||
If you prefer to use Nginx or another proxy for TLS termination:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name streaming.bose.com bmx.bose.com stats.bose.com updates.bose.com;
|
||||
|
||||
ssl_certificate /path/to/generated-cert.crt;
|
||||
ssl_certificate_key /path/to/generated-cert.key;
|
||||
ssl_certificate /path/to/data/certs/server.crt;
|
||||
ssl_certificate_key /path/to/data/certs/server.key;
|
||||
|
||||
# Secure TLS configuration (matches soundtouch-service defaults)
|
||||
ssl_protocols TLSv1.2;
|
||||
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-CHACHA20-POLY1305:AES128-GCM-SHA256:AES256-GCM-SHA384';
|
||||
|
||||
@@ -87,23 +70,26 @@ server {
|
||||
}
|
||||
```
|
||||
|
||||
## 5. Manual CA Injection (Legacy/Manual)
|
||||
---
|
||||
|
||||
If you prefer to inject the CA certificate manually:
|
||||
## Manual CA injection (advanced)
|
||||
|
||||
1. Copy `ca.crt` to the device:
|
||||
```bash
|
||||
scp data/certs/ca.crt root@{deviceIP}:/tmp/
|
||||
```
|
||||
2. Append it to the trust store on the device:
|
||||
```bash
|
||||
ssh root@{deviceIP} "(rw || mount -o remount,rw /) && cat /tmp/ca.crt >> /etc/pki/tls/certs/ca-bundle.crt"
|
||||
```
|
||||
If you need to inject the CA manually (e.g. without the web UI migration flow):
|
||||
|
||||
## 6. Verifying Connectivity
|
||||
```bash
|
||||
# Copy the CA to the speaker
|
||||
scp data/certs/ca.crt root@<SPEAKER-IP>:/tmp/
|
||||
|
||||
You can verify that your device can correctly reach the `soundtouch-service` over HTTPS using the management web UI.
|
||||
# Make the filesystem writable and append the CA to the trust store
|
||||
ssh root@<SPEAKER-IP> "(rw || mount -o remount,rw /) && cat /tmp/ca.crt >> /etc/pki/tls/certs/ca-bundle.crt"
|
||||
```
|
||||
|
||||
In the **Migration Summary** for a device, you will find an **HTTPS Connection Test** section:
|
||||
- **Test with Explicit CA.crt**: Uploads a temporary copy of the Root CA to the device and uses `curl --cacert` to verify the connection. Use this to verify your HTTPS setup *before* modifying the device's shared trust store.
|
||||
- **Test with Shared Trust Store**: Uses the device's default trust store. Use this to verify that your CA injection was successful and the device now natively trusts your local server.
|
||||
---
|
||||
|
||||
## TLS compatibility
|
||||
|
||||
SoundTouch speakers run OpenSSL 1.0.2, supporting up to TLS 1.2. The service is configured accordingly:
|
||||
|
||||
- **Minimum TLS version**: TLS 1.2
|
||||
- **Preferred cipher suites**: `ECDHE-RSA-AES128-GCM-SHA256`, `ECDHE-RSA-AES256-GCM-SHA384`, `ECDHE-RSA-CHACHA20-POLY1305`
|
||||
- **Legacy support**: `RSA-AES128-GCM-SHA256`, `RSA-AES256-GCM-SHA384`
|
||||
@@ -1,418 +1,193 @@
|
||||
# THIS IS A PLANNED TO BE THE MIGRATION GUIDE
|
||||
# Migration Guide: From Bose Cloud to AfterTouch
|
||||
|
||||
> This migration guide is not finalized, yet.
|
||||
> We're using it as an orientation for the required implementation.
|
||||
This guide walks through the complete process of migrating your SoundTouch speakers from Bose's cloud services to **AfterTouch**, the local replacement provided by `soundtouch-service`. By the end, your speakers will work fully independently of Bose's servers.
|
||||
|
||||
For a shorter overview, see the [Survival Guide](SURVIVAL-GUIDE.md). For safety considerations and rollback options, see the [Migration & Safety Guide](MIGRATION-SAFETY.md).
|
||||
|
||||
---
|
||||
|
||||
# Complete Migration Guide - From Bose Cloud to Local SoundTouch Service
|
||||
## What you need
|
||||
|
||||
## Overview
|
||||
- A machine that is **always on** (Raspberry Pi, NAS, home server, or similar) to run the service
|
||||
- A **USB drive** (FAT-formatted) to enable SSH on each speaker
|
||||
- Your speakers must be on the **same network** as the service host
|
||||
- About **15–30 minutes per speaker**
|
||||
|
||||
This guide will walk you through migrating your Bose SoundTouch speakers from Bose's cloud services to AfterTouch, your own local SoundTouch service. By the end of this process, your speakers will be completely independent of Bose's servers while retaining all their functionality.
|
||||
---
|
||||
|
||||
> **💡 Why Migrate?** Bose announced the shutdown of their SoundTouch cloud services in May 2026. This migration ensures your speakers continue working indefinitely with enhanced local control and monitoring.
|
||||
## Step 1: Install and start the service
|
||||
|
||||
## What You'll Need
|
||||
Choose the option that fits your setup.
|
||||
|
||||
### Hardware Requirements
|
||||
- **Raspberry Pi 4 or similar** (minimum: Raspberry Pi Zero 2W)
|
||||
- **MicroSD card** (16GB or larger)
|
||||
- **USB drive** (for device preparation)
|
||||
- **Network connection** for your Raspberry Pi
|
||||
|
||||
### Before You Start
|
||||
- **List all your SoundTouch devices** and their current locations
|
||||
- **Note your current presets and favorites** (they will be preserved)
|
||||
- **Ensure devices are on the same network** as your future SoundTouch service
|
||||
- **Basic computer skills** (following instructions, using a web browser)
|
||||
|
||||
### Time Estimate
|
||||
- **Setup**: 30-60 minutes for the service installation
|
||||
- **Per Device**: 10-15 minutes for each speaker migration
|
||||
- **Total**: 1-3 hours depending on number of devices
|
||||
|
||||
## Step 1: Install SoundTouch Service
|
||||
|
||||
### Option A: Raspberry Pi Installation (Recommended)
|
||||
|
||||
#### 1.1 Prepare Your Raspberry Pi
|
||||
|
||||
1. **Flash Raspberry Pi OS** to your SD card using Raspberry Pi Imager (see the raspberrypi.com documentation)
|
||||
2. **Enable SSH** during imaging or create an empty `ssh` file on the boot partition
|
||||
3. **Boot your Pi** and connect it to your network
|
||||
4. **Find your Pi's IP address** (check your router or use `ping raspberrypi.local`)
|
||||
|
||||
#### 1.2 Install SoundTouch Service
|
||||
|
||||
Connect to your Pi via SSH and run:
|
||||
### Binary (go install)
|
||||
|
||||
```bash
|
||||
# Download and install
|
||||
curl -sSL https://github.com/gesellix/Bose-SoundTouch/releases/latest/download/install.sh | bash
|
||||
|
||||
# Start the service
|
||||
sudo systemctl enable soundtouch-service
|
||||
sudo systemctl start soundtouch-service
|
||||
go install github.com/gesellix/bose-soundtouch/cmd/soundtouch-service@latest
|
||||
soundtouch-service
|
||||
```
|
||||
|
||||
#### 1.3 Verify Installation
|
||||
The service starts on port 8000. Open `http://localhost:8000` in your browser.
|
||||
|
||||
1. Open your web browser
|
||||
2. Go to `http://[PI_IP_ADDRESS]:8000` (replace with your Pi's IP)
|
||||
3. You should see the **SoundTouch Service Dashboard**
|
||||
### Docker Compose (recommended for home servers and VMs)
|
||||
|
||||

|
||||
*Example: SoundTouch Service main dashboard*
|
||||
The repository ships a `docker-compose.yml` ready for this use case. Clone or download it, copy the example config, then edit `.env` before starting:
|
||||
|
||||
### Option B: Docker Installation
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# Edit .env:
|
||||
# SOUNDTOUCH_HOSTNAME=192.168.1.100 ← your server's address
|
||||
# SOUNDTOUCH_VERSION=v0.70.0 ← pin to a release tag instead of 'latest'
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
If you prefer Docker, run:
|
||||
`SOUNDTOUCH_HOSTNAME` is the address your speakers will use to reach the service — use a hostname or IP reachable from the speaker, not `localhost`.
|
||||
|
||||
On **Linux** (Debian, Proxmox VE, Raspberry Pi OS, etc.) you can enable host networking for automatic speaker discovery. Uncomment the `network_mode: host` line in `docker-compose.yml` and remove the `ports:` section (they conflict with host networking). Without host networking, add your speakers by IP address in Step 4 instead.
|
||||
|
||||
For local overrides (e.g. switching to `build: .` during development), create a `docker-compose.override.yml` — Docker Compose picks it up automatically and it is not tracked in version control.
|
||||
|
||||
> **Note on `docker-compose.ci.yml`**: this file contains mock services used only for automated integration tests. It is not needed for your own deployment.
|
||||
|
||||
### Docker run (Linux — with host networking for device discovery)
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--name soundtouch-service \
|
||||
--restart unless-stopped \
|
||||
-p 8000:8000 \
|
||||
-p 8443:8443 \
|
||||
-v soundtouch-data:/data \
|
||||
gesellix/soundtouch-service:latest
|
||||
--network host \
|
||||
-v $(pwd)/data:/app/data \
|
||||
ghcr.io/gesellix/bose-soundtouch:latest
|
||||
```
|
||||
|
||||
## Step 2: Create Your Account
|
||||
### Docker run (macOS / Windows — manual device IP required)
|
||||
|
||||
### 2.1 Initial Setup
|
||||
|
||||
1. **Open the dashboard** at `http://[SERVICE_IP]:8000`
|
||||
2. Click **"Create New Account"**
|
||||
3. **Fill in your details**:
|
||||
- Account Name: `My Home Audio`
|
||||
- Email: `your@email.com` (optional, for notifications)
|
||||
- Migration Strategy: `Gradual` (recommended)
|
||||
|
||||

|
||||
*Example: Account creation form*
|
||||
|
||||
### 2.2 Account Configuration
|
||||
|
||||
After creation, you'll see your **Account Dashboard**:
|
||||
- **Account ID**: Unique identifier (e.g., `acc_home_audio_001`)
|
||||
- **Status**: `Active - Ready for Migration`
|
||||
- **Device Count**: Initially 0
|
||||
- **Migration Status**: `Prepared`
|
||||
|
||||

|
||||
*Example: Fresh account dashboard ready for device migration*
|
||||
|
||||
### 2.3 Initial Settings
|
||||
|
||||
Once your account is created, configure the global settings:
|
||||
1. **Settings**:
|
||||
- Check **Target Domain**: Ensure it's reachable from the speaker (e.g., `soundtouch.fritz.box`).
|
||||
- **DNS Discovery**: Enable DNS discovery on port `:53`. This is crucial for the DNS hook migration method.
|
||||
2. **Devices**:
|
||||
- Go to the **"Device Discovery"** tab.
|
||||
- Click **"Scan Network"** or manually add a speaker via IP address.
|
||||
- Your devices should appear with **SSH Status**: `Enabled`.
|
||||
|
||||

|
||||
*Example: Discovered devices with remote access enabled*
|
||||
|
||||
## Step 3: Prepare Your Devices
|
||||
|
||||
> **⚠️ Important**: This step temporarily enables SSH access on your speakers. SSH will be automatically disabled after migration unless you choose to keep it enabled.
|
||||
|
||||
### 3.1 Enable Remote Services
|
||||
|
||||
For each SoundTouch device:
|
||||
|
||||
1. **Prepare a USB drive**:
|
||||
- Format as FAT32
|
||||
- Create an empty file named `remote_services` (no extension)
|
||||
- (Optional) Firmware update/reset, see [Bose SoundTouch USB Update](https://downloads.bose.com/ced/soundtouch/soundtouch_usb/index.html)
|
||||
|
||||
2. **Insert USB drive** into your SoundTouch speaker
|
||||
3. **Power cycle** the device (unplug for 10 seconds, then reconnect)
|
||||
|
||||

|
||||
*Example: USB drive setup for enabling remote services*
|
||||
|
||||
## Step 4: Discover and Register Devices
|
||||
|
||||
### 4.1 Automatic Discovery
|
||||
|
||||
The service automatically scans for SoundTouch devices every 5 minutes. To trigger immediate discovery:
|
||||
|
||||
1. **Dashboard** → **"Devices"** → **"Discover Devices"**
|
||||
2. **Wait 30-60 seconds** for scan completion
|
||||
3. **Review discovered devices** in the list
|
||||
|
||||
### 4.2 Register Devices to Your Account
|
||||
|
||||
For each discovered device:
|
||||
|
||||
1. **Click device name** in the discovery list
|
||||
2. **Verify device information**:
|
||||
- Name: `Living Room Speaker`
|
||||
- Model: `SoundTouch 30`
|
||||
- MAC Address: `A8:1B:6A:53:6A:98`
|
||||
- IP Address: `192.168.1.100`
|
||||
- Status: `Discovered - Ready for Registration`
|
||||
|
||||
3. **Click "Register to Account"**
|
||||
4. **Choose registration type**:
|
||||
- **Fresh Setup**: For new or factory-reset devices
|
||||
- **Migrate from Bose**: For devices with existing Bose account (recommended)
|
||||
|
||||

|
||||
*Example: Device registration dialog with migration options*
|
||||
|
||||
### 4.3 Device Registration Results
|
||||
|
||||
After registration, you'll see:
|
||||
- **Device Status**: `Registered - Active`
|
||||
- **Account Association**: Your account name
|
||||
- **Lifecycle State**: `Active`
|
||||
- **Data Sources**: `Mirror Primary` (initially uses Bose, falls back to local)
|
||||
|
||||
## Step 5: Migrate Individual Devices
|
||||
|
||||
### 5.1 Step 3: Data Sync
|
||||
|
||||
1. **Dashboard** → **"Devices"** → Select your device
|
||||
2. Click **"Data Sync"**
|
||||
3. This fetches configuration (presets, recents, sources) from the speaker to the SoundTouch service.
|
||||
|
||||
### 5.2 Step 4: Migration
|
||||
|
||||
Once data is synced, proceed to the migration tab for the device:
|
||||
|
||||
1. **Backup XML**: Create an off-device backup of the current configuration.
|
||||
2. **Enable Persistent Remote Service**: This ensures SSH remains available after reboots.
|
||||
- *Note*: If you see `'rw: command not found'`, you can safely ignore it.
|
||||
3. **CA Certificate Configuration**:
|
||||
- **Test with explicit CA**: Verify the speaker can communicate using the local CA.
|
||||
- **Trust CA now**: Inject the local Root CA into the speaker's trust store.
|
||||
- **Test with shared trust store**: Verify general HTTPS communication.
|
||||
4. **Migration Method**:
|
||||
- Select **"Redirect via DNS hook"**.
|
||||
- **Test DNS Redirection**: Ensure the speaker correctly resolves the service domain.
|
||||
5. **Confirm Migration**: Apply the final changes to the speaker.
|
||||
|
||||
#### Example Migration Output:
|
||||
```text
|
||||
Successfully created off-device backup of current configuration.
|
||||
Pre-flight: Write access verified.
|
||||
Resolved soundtouch.fritz.box to 192.168.1.100
|
||||
Uploaded /mnt/nv/soundtouch-service/aftertouch.resolv.conf
|
||||
/mnt/nv/rc.local already contains Aftertouch hook logic
|
||||
(rw || mount -o remount,rw /): sh: rw: command not found
|
||||
|
||||
cp /etc/udhcpc.d/50default /etc/udhcpc.d/50default.original:
|
||||
Applied patch to /etc/udhcpc.d/50default
|
||||
Verified patch on /etc/udhcpc.d/50default
|
||||
cp /opt/Bose/udhcpc.script /opt/Bose/udhcpc.script.original:
|
||||
Applied patch to /opt/Bose/udhcpc.script
|
||||
Verified patch on /opt/Bose/udhcpc.script
|
||||
CA certificate already trusted, skipping injection
|
||||
```bash
|
||||
docker run -d \
|
||||
--name soundtouch-service \
|
||||
-p 8000:8000 -p 8443:8443 \
|
||||
-v $(pwd)/data:/app/data \
|
||||
--env SERVER_URL=http://soundtouch.local:8000 \
|
||||
--env HTTPS_SERVER_URL=https://soundtouch.local:8443 \
|
||||
ghcr.io/gesellix/bose-soundtouch:latest
|
||||
```
|
||||
|
||||
## Step 7: Complete Account Migration
|
||||
On macOS/Windows, device discovery via mDNS won't work inside the container — you'll add devices by IP address in Step 4.
|
||||
|
||||
### 7.1 Migrate All Devices
|
||||
|
||||
Repeat the migration process for each of your SoundTouch devices. You can migrate multiple devices simultaneously, but we recommend doing 1-2 at a time to monitor progress.
|
||||
|
||||
**Migration Dashboard** shows overall progress:
|
||||
- **Devices Migrated**: `2 of 4 completed`
|
||||
- **Currently Migrating**: `Living Room Speaker, Kitchen Speaker`
|
||||
- **Pending Migration**: `Bedroom Speaker, Office Speaker`
|
||||
- **Estimated Completion**: `3 days remaining`
|
||||
|
||||

|
||||
*Example: Account-wide migration progress*
|
||||
|
||||
### 7.2 Verify Complete Migration
|
||||
|
||||
When all devices are migrated:
|
||||
|
||||
1. **Account Status**: `Active - Fully Migrated`
|
||||
2. **Bose Dependency**: `None`
|
||||
3. **Local Control**: `100%`
|
||||
4. **Device Health**: All devices show `Healthy - Local Only`
|
||||
|
||||

|
||||
*Example: Completed migration dashboard*
|
||||
|
||||
## Step 8: Post-Migration Tasks
|
||||
|
||||
1. **Remove USB stick** from the speaker.
|
||||
2. **Reboot** the device to apply all changes.
|
||||
|
||||
### 8.1 Disable Remote Services (Optional)
|
||||
|
||||
For enhanced security, you can disable SSH on migrated devices. However, keeping it enabled allows for easier future maintenance or reverts.
|
||||
|
||||
### 8.2 Configure Backups
|
||||
|
||||
Set up automatic backups of your device configurations:
|
||||
|
||||
1. **Dashboard** → **"Settings"** → **"Backup"**
|
||||
2. **Enable Automatic Backups**: ✅
|
||||
3. **Backup Schedule**: `Daily at 2 AM`
|
||||
4. **Retention**: `Keep 30 days`
|
||||
5. **Export Location**: `/data/backups` or external storage
|
||||
|
||||

|
||||
*Example: Backup configuration settings*
|
||||
|
||||
### 8.3 Set Up Monitoring Alerts (Optional)
|
||||
|
||||
Configure notifications for important events:
|
||||
|
||||
1. **Dashboard** → **"Settings"** → **"Notifications"**
|
||||
2. **Email Notifications**: Enter your email
|
||||
3. **Alert Types**:
|
||||
- ✅ Device goes offline
|
||||
- ✅ Migration failures
|
||||
- ✅ Service errors
|
||||
- ✅ Daily health summary
|
||||
|
||||
## Troubleshooting Common Issues
|
||||
|
||||
### Device Not Discovered
|
||||
|
||||
**Problem**: Device doesn't appear in discovery scan
|
||||
|
||||
**Solutions**:
|
||||
1. **Check network**: Ensure device and service are on same network
|
||||
2. **Verify USB setup**: Confirm `remote_services` file was processed
|
||||
3. **Power cycle**: Unplug device for 30 seconds, reconnect
|
||||
4. **Manual add**: Dashboard → "Devices" → "Add Manually" with IP address
|
||||
|
||||
### Migration Stuck
|
||||
|
||||
**Problem**: Device stuck in "Migrating" status
|
||||
|
||||
**Solutions**:
|
||||
1. **Check device health**: Dashboard → Device → "Health Status"
|
||||
2. **Review logs**: Dashboard → Device → "View Logs"
|
||||
3. **Restart migration**: Device → "Migration" → "Restart Process"
|
||||
4. **Rollback**: Device → "Migration" → "Rollback to Bose"
|
||||
|
||||
### Presets Not Working
|
||||
|
||||
**Problem**: Saved presets don't work after migration
|
||||
|
||||
**Solutions**:
|
||||
1. **Verify sources**: Check configured sources are still available
|
||||
2. **Re-authenticate**: Re-login to music services (Spotify, etc.)
|
||||
3. **Rebuild presets**: Dashboard → Device → "Presets" → "Rebuild from Backup"
|
||||
|
||||
### Service Unreachable
|
||||
|
||||
**Problem**: Cannot access SoundTouch Service dashboard
|
||||
|
||||
**Solutions**:
|
||||
1. **Check service status**: `sudo systemctl status soundtouch-service`
|
||||
2. **Restart service**: `sudo systemctl restart soundtouch-service`
|
||||
3. **Check network**: Verify Pi is connected and accessible
|
||||
4. **Check ports**: Ensure ports 8000 and 8443 are not blocked
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Multi-Zone Management
|
||||
|
||||
After migration, your multi-zone setups work seamlessly:
|
||||
|
||||
1. **Dashboard** → **"Zones"**
|
||||
2. **Create Zone**: Select primary device and slaves
|
||||
3. **Zone Control**: Play, pause, volume control for entire zone
|
||||
4. **Individual Control**: Override individual speakers in zone
|
||||
|
||||
### Custom Sources
|
||||
|
||||
Add custom streaming sources:
|
||||
|
||||
1. **Dashboard** → **"Sources"** → **"Add Custom"**
|
||||
2. **Configure**:
|
||||
- Name: `Local Radio Station`
|
||||
- Stream URL: `http://stream.example.com:8000`
|
||||
- Image URL: `http://example.com/logo.png`
|
||||
3. **Assign to devices**: Select which devices can access this source
|
||||
|
||||
### API Access
|
||||
|
||||
For developers and advanced users:
|
||||
|
||||
- **REST API**: `http://[SERVICE_IP]:8000/api/v1/`
|
||||
- **Documentation**: `http://[SERVICE_IP]:8000/docs`
|
||||
- **WebSocket Events**: Real-time device status updates
|
||||
- **Export Data**: JSON/XML export of all device configurations
|
||||
|
||||
## Maintenance and Monitoring
|
||||
|
||||
### Daily Monitoring
|
||||
|
||||
Check your **Dashboard Summary**:
|
||||
- **All Devices Online**: ✅ Green indicators
|
||||
- **Response Times**: < 100ms average
|
||||
- **Error Rate**: < 1%
|
||||
- **Storage Usage**: Monitor disk space
|
||||
|
||||
### Weekly Tasks
|
||||
|
||||
1. **Review Health Reports**: Check weekly device health summaries
|
||||
2. **Update Service**: Check for SoundTouch service updates
|
||||
3. **Backup Verification**: Ensure backups are completing successfully
|
||||
4. **Log Review**: Check for any recurring issues or warnings
|
||||
|
||||
### Monthly Tasks
|
||||
|
||||
1. **Full System Backup**: Export complete account and device data
|
||||
2. **Performance Review**: Analyze response times and error patterns
|
||||
3. **Security Update**: Update Raspberry Pi OS and service
|
||||
4. **Capacity Planning**: Monitor storage and consider expansion
|
||||
|
||||
## Getting Help
|
||||
|
||||
### Documentation Resources
|
||||
|
||||
- **Technical Reference**: `/docs/reference/` - Detailed API and configuration docs
|
||||
- **Troubleshooting Guide**: `/docs/guides/TROUBLESHOOTING.md` - Common issues and solutions
|
||||
- **Community Forum**: GitHub Discussions for community support
|
||||
|
||||
### Diagnostic Information
|
||||
|
||||
When seeking help, provide:
|
||||
|
||||
1. **System Information**: Dashboard → "System" → "Download Diagnostic Report"
|
||||
2. **Device Logs**: Dashboard → Device → "Export Logs"
|
||||
3. **Migration History**: Dashboard → "Migration" → "Export Timeline"
|
||||
4. **Current Status**: Screenshot of main dashboard
|
||||
|
||||
### Support Channels
|
||||
|
||||
- **GitHub Issues**: Technical bugs and feature requests
|
||||
- **Community Discussions**: User questions and experiences
|
||||
- **Documentation Updates**: Corrections and improvements
|
||||
See [Raspberry Pi Setup](RASPBERRY-PI.md) and the [SoundTouch Service Guide](SOUNDTOUCH-SERVICE.md) for more deployment options.
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
## Step 2: Configure the service URL
|
||||
|
||||
Congratulations! 🎉 You've successfully migrated your SoundTouch speakers to local control. Your devices are now:
|
||||
Open `http://<server>:8000` and go to the **Settings** tab.
|
||||
|
||||
- ✅ **Independent** of Bose cloud services
|
||||
- ✅ **Fully functional** with all original features preserved
|
||||
- ✅ **Enhanced** with better monitoring and control
|
||||
- ✅ **Future-proof** against service shutdowns
|
||||

|
||||
|
||||
**What's Next?**
|
||||
Set the **Target Domain** to the address your speakers can reach — for example `https://soundtouch.fritz.box` or `http://192.168.1.100:8000`. This must be the host's address on your local network, not `localhost`.
|
||||
|
||||
- **Enjoy your music** with enhanced local control
|
||||
- **Monitor your system** through the dashboard
|
||||
- **Share your experience** with the community
|
||||
- **Explore advanced features** as you become more comfortable
|
||||
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.
|
||||
|
||||
Your SoundTouch speakers will now continue working indefinitely, regardless of external service availability. Welcome to true audio independence! 🔊
|
||||
> **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.
|
||||
|
||||
---
|
||||
|
||||
## Step 3: Enable SSH on each speaker
|
||||
|
||||
The migration writes updated configuration to the speaker's filesystem, which requires SSH access. Enable it once per device:
|
||||
|
||||
1. Format a USB drive as FAT (FAT32). Some speakers require the **bootable flag** to be set on the partition — see [SoundCork issue #172](https://github.com/deborahgu/soundcork/issues/172) for details.
|
||||
2. Create an empty file named **`remote_services`** (no extension) in the root of the drive.
|
||||
3. Insert the drive into the speaker's USB port while it is powered on.
|
||||
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>`
|
||||
|
||||
You only need to do this once per speaker. SSH can remain enabled for future maintenance or be disabled after migration — your choice.
|
||||
|
||||
---
|
||||
|
||||
## Step 4: Add and sync your speaker
|
||||
|
||||
### Discover
|
||||
|
||||
The service scans for SoundTouch devices automatically every few minutes. Check the **Devices** tab in the web UI. If your speaker doesn't appear, click **Scan Again** to trigger an immediate scan, or enter the IP address manually and click **Add Device**.
|
||||
|
||||

|
||||
|
||||
### Sync
|
||||
|
||||
Once the speaker appears, click **Sync Data**. This connects to the speaker and pulls its current presets, recently played items, and configured sources into the local service's datastore. It also creates an off-device backup of the speaker's configuration.
|
||||
|
||||

|
||||
|
||||
If the Bose cloud is still running, Sync also fetches your account data from Bose's servers. This is your preservation step — do it before the cloud shuts down.
|
||||
|
||||
---
|
||||
|
||||
## Step 5: Migrate
|
||||
|
||||
Click **Migrate** next to a device on the Devices tab to open the Migration tab. It shows SSH status, CA trust status, and connection test results before letting you apply the redirect.
|
||||
|
||||

|
||||
|
||||
Two redirect methods are available:
|
||||
|
||||
### XML redirect (recommended for first-time / testing)
|
||||
|
||||
Uploads a configuration file to the speaker via the SoundTouch Web API. This changes the application-level service URLs without touching the speaker's network configuration. It's the least invasive option.
|
||||
|
||||
The web UI guides you through:
|
||||
1. Previewing the config change (current vs. planned XML)
|
||||
2. Optionally installing the AfterTouch CA certificate on the speaker (requires SSH; needed for HTTPS)
|
||||
3. Applying the XML redirect
|
||||
4. Verifying the speaker can reach the local service
|
||||
|
||||
### DNS/DHCP redirect (recommended for permanent / all-device setup)
|
||||
|
||||
Configures the speaker to use a custom DNS server that resolves Bose cloud hostnames to the local service. This is the most robust method — it covers all Bose endpoints automatically and survives reboots.
|
||||
|
||||
Requirements:
|
||||
- The AfterTouch DNS server must be running and bound to **port 53** on your network. Enable it in the **Settings** tab (`DNS Discovery` → enabled).
|
||||
- HTTPS is required. The web UI walks you through trusting the CA certificate on the speaker (via SSH).
|
||||
|
||||
The web UI guides you through:
|
||||
1. Verifying the DNS server is running and reachable
|
||||
2. Installing the CA certificate on the speaker
|
||||
3. Configuring the speaker to use the AfterTouch DNS server
|
||||
4. Verifying DNS resolution and HTTPS connectivity
|
||||
|
||||
---
|
||||
|
||||
## Step 6: Reboot and verify
|
||||
|
||||
After migration, **power-cycle the speaker** (unplug and replug). This applies all configuration changes.
|
||||
|
||||
After reboot:
|
||||
- The speaker should appear as **migrated** in the Devices tab
|
||||
- Presets should load and play (served from the local service)
|
||||
- TuneIn browsing should work
|
||||
- Recently played items should appear
|
||||
|
||||
If something doesn't work, check the **Interactions** tab in the web UI for failed requests, and the **Troubleshooting** section in the [SoundTouch Service Guide](SOUNDTOUCH-SERVICE.md).
|
||||
|
||||
---
|
||||
|
||||
## Repeat for each speaker
|
||||
|
||||
Each speaker is migrated independently. You can run multiple migrations in parallel, but migrating one at a time makes it easier to diagnose issues.
|
||||
|
||||
---
|
||||
|
||||
## Rollback
|
||||
|
||||
If you need to undo a migration:
|
||||
|
||||
- **From the web UI**: Use the **Revert** action on the device — this restores the `.original` backup files created on the speaker during migration.
|
||||
- **Via SSH**: The original 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.
|
||||
|
||||
---
|
||||
|
||||
## Post-migration
|
||||
|
||||
Once all speakers are migrated, the `data/` directory is the source of truth for your presets, recents, and device state. Back it up periodically. The web UI at `http://<server>:8000` is your management interface from this point on.
|
||||
|
||||
For the Bose cloud backup you created in Step 4, keep the `.tar.gz` archive in case you need to restore credentials or presets later.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
### Professional Migration & Safety Guide
|
||||
# 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.
|
||||
|
||||
@@ -14,8 +14,8 @@ The following features are built into the `soundtouch-service` to ensure stabili
|
||||
|
||||
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.
|
||||
- Create an empty file named `remote_services` on a USB stick.
|
||||
1. **Enable SSH Access (Prerequisite)**: This toolkit requires SSH access to your speakers, which is not enabled by default.
|
||||
- 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).
|
||||
- The speaker will now allow SSH connections as `root` with no password.
|
||||
@@ -27,10 +27,11 @@ Before you proceed with the actual migration, follow these steps:
|
||||
4. **Validate SSH Access**: 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 Migration (Default)**: Less invasive, only changes the application config. Best for simple redirection.
|
||||
- **Hosts Migration**: Modifies `/etc/hosts` on the device. Good for system-wide redirection of specific domains.
|
||||
- **ResolvConf Migration**: Points the device to the AfterTouch DNS server. Best for discovering unknown Bose endpoints and dynamic interception. **Note**: This method requires the DNS Discovery Server to be running on port 53. The service includes a pre-flight check to ensure the server is properly bound before allowing this migration.
|
||||
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.
|
||||
- **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.
|
||||
6. **Monitor Logs**: Run the `soundtouch-service` with `DEBUG` or `INFO` logging to see the step-by-step progress of the migration.
|
||||
|
||||
#### 🔄 Rollback Strategy
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
# Connecting Music Services (Spotify & Amazon Music)
|
||||
|
||||
This guide explains how to link your Spotify or Amazon Music account to AfterTouch so your speakers can stream music from those services.
|
||||
|
||||
---
|
||||
|
||||
## How it works
|
||||
|
||||
Connecting a music service happens in three separate steps, each done once:
|
||||
|
||||
1. **Register a developer app** with Spotify or Amazon (one-time setup by the person running AfterTouch).
|
||||
2. **Authorize your personal account** so AfterTouch can access your music library.
|
||||
3. **Prime your speaker** so the speaker itself learns about the source.
|
||||
|
||||
Each step is described below. If someone else is hosting AfterTouch for you, step 1 may already be done — ask them.
|
||||
|
||||
---
|
||||
|
||||
## Who registers the developer app?
|
||||
|
||||
The developer app is what allows AfterTouch to talk to Spotify's or Amazon's servers on behalf of users. It requires registering an account on a developer portal.
|
||||
|
||||
**If you run AfterTouch for yourself only:** You register one app and use it yourself.
|
||||
|
||||
**If you run AfterTouch for a group** (e.g., your household): You register one app, configure it in AfterTouch, and everyone who uses your AfterTouch instance shares it. They never see your app credentials — those stay on your server. However, they do need to trust you, since their music account tokens are stored by your AfterTouch installation.
|
||||
|
||||
**If you don't trust the AfterTouch operator:** Run your own AfterTouch instance and register your own app. That way everything stays under your control.
|
||||
|
||||
---
|
||||
|
||||
## Spotify
|
||||
|
||||
### Step 1: Register a Spotify developer app
|
||||
|
||||
1. Go to [developer.spotify.com/dashboard](https://developer.spotify.com/dashboard) and log in with your Spotify account.
|
||||
2. Click **Create app**.
|
||||
3. Give it any name and description (e.g., "My AfterTouch").
|
||||
4. Under **Redirect URIs**, add:
|
||||
```
|
||||
http://<your-aftertouch-ip>:8000/mgmt/spotify/callback
|
||||
```
|
||||
Replace `<your-aftertouch-ip>:8000` with the address of your AfterTouch server.
|
||||
5. Save the app.
|
||||
6. Open the app's settings and note down the **Client ID** and **Client Secret**.
|
||||
|
||||
### Step 2: Enter credentials in AfterTouch
|
||||
|
||||
1. Open the AfterTouch web interface and go to the **Settings** tab.
|
||||
2. Scroll to **Spotify Integration**.
|
||||
3. Enter your **Client ID**, **Client Secret**, and the **Redirect URI** you registered above.
|
||||
4. Click **Save Settings**.
|
||||
|
||||
The status should change to **Active**.
|
||||
|
||||
### Step 3: Authorize your Spotify account
|
||||
|
||||
1. Go to the **Local Account** tab (tab 7).
|
||||
2. Click **Connect Spotify to this Account**.
|
||||
3. A Spotify login window opens. Log in and grant permission.
|
||||
4. When the window closes, your account is linked. You should see your Spotify username appear.
|
||||
|
||||
### Step 4: Prime your speaker
|
||||
|
||||
After authorizing, each speaker needs to be told about the Spotify source.
|
||||
|
||||
1. Go to the **Devices** tab (tab 2).
|
||||
2. Find your speaker and click **Prime Spotify**.
|
||||
3. The speaker will now show Spotify as an available source.
|
||||
|
||||
Repeat step 4 for each speaker.
|
||||
|
||||
---
|
||||
|
||||
## Amazon Music
|
||||
|
||||
> **Current status: account linking works, streaming does not.**
|
||||
>
|
||||
> The OAuth flow and token storage are fully functional. However, the speaker's `AmazonClient` contacts `music-api.amazon.com` directly with the access token and receives a 401. Amazon Music's streaming API requires scopes that are only available to registered Amazon Music partners — a standard Login with Amazon app does not qualify. The infrastructure is in place and will work if those scopes ever become available, but following these steps will not result in working Amazon Music playback today.
|
||||
|
||||
### Step 1: Register an Amazon developer app (LWA)
|
||||
|
||||
1. Go to [developer.amazon.com/loginwithamazon/console/site/lwa/overview.html](https://developer.amazon.com/loginwithamazon/console/site/lwa/overview.html) and log in with your Amazon account.
|
||||
2. Click **Create a New Security Profile**.
|
||||
3. Give it any name and description (e.g., "My AfterTouch").
|
||||
4. In the security profile's **Web Settings**, add under **Allowed Return URLs**:
|
||||
```
|
||||
http://<your-aftertouch-ip>:8000/mgmt/amazon/callback
|
||||
```
|
||||
Replace `<your-aftertouch-ip>:8000` with the address of your AfterTouch server.
|
||||
5. Save and note down the **Client ID** and **Client Secret**.
|
||||
|
||||
### Step 2: Enter credentials in AfterTouch
|
||||
|
||||
1. Open the AfterTouch web interface and go to the **Settings** tab.
|
||||
2. Scroll to **Amazon Music Integration**.
|
||||
3. Enter your **Client ID**, **Client Secret**, and the **Redirect URI** you registered above.
|
||||
4. Click **Save Settings**.
|
||||
|
||||
The status should change to **Active**.
|
||||
|
||||
### Step 3: Authorize your Amazon account
|
||||
|
||||
1. Go to the **Local Account** tab (tab 7).
|
||||
2. Click **Connect Amazon Music to this Account**.
|
||||
3. An Amazon login window opens. Log in and grant permission.
|
||||
4. When the window closes, your account is linked.
|
||||
|
||||
### Step 4: Prime your speaker
|
||||
|
||||
1. Go to the **Devices** tab (tab 2).
|
||||
2. Find your speaker and click **Prime Amazon**.
|
||||
3. The speaker will now show Amazon Music as an available source.
|
||||
|
||||
Repeat step 4 for each speaker.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**"Failed to initialize" when clicking Connect:**
|
||||
The app credentials in Settings are missing or incorrect. Double-check the Client ID, Client Secret, and Redirect URI. The Redirect URI in AfterTouch must exactly match the one registered in the developer portal.
|
||||
|
||||
**The login window opens but redirects to an error page:**
|
||||
The Redirect URI registered with Spotify/Amazon does not match what AfterTouch is sending. Make sure the address (including the port) is identical in both places.
|
||||
|
||||
**The speaker doesn't show the new source after priming:**
|
||||
Try rebooting the speaker. It may take a minute to update its source list after priming.
|
||||
|
||||
**The login window doesn't open (popup blocked):**
|
||||
Allow popups from the AfterTouch address in your browser settings, then try again. Alternatively, the status message will show a direct link you can click.
|
||||
@@ -0,0 +1,132 @@
|
||||
# Self-Hosting AfterTouch
|
||||
|
||||
This guide walks you through running AfterTouch on your own computer or server. No programming knowledge required.
|
||||
|
||||
---
|
||||
|
||||
## What is self-hosting?
|
||||
|
||||
AfterTouch is software that runs on a computer in your home and takes over the role of Bose's cloud servers. Your speakers talk to it instead of Bose.
|
||||
|
||||
For this to work, the computer running AfterTouch must be:
|
||||
|
||||
- **Always on** (or at least on whenever you want to use your speakers)
|
||||
- **On the same local network** as your speakers
|
||||
- **Reachable by a stable IP address** (see [Stable IP Address](#stable-ip-address) below)
|
||||
|
||||
Good choices: a Raspberry Pi, a NAS (like Synology or QNAP), an always-on PC or Mac, or a small server. A laptop that you close and put away is not ideal.
|
||||
|
||||
---
|
||||
|
||||
## Step 1: Get the software
|
||||
|
||||
Go to the [AfterTouch releases page](https://github.com/gesellix/Bose-SoundTouch/releases) and download the latest release for your operating system:
|
||||
|
||||
| Your system | File to download |
|
||||
|-----------------------|------------------------------------------|
|
||||
| Raspberry Pi (64-bit) | `soundtouch-service_linux_arm64.tar.gz` |
|
||||
| Raspberry Pi (32-bit) | `soundtouch-service_linux_arm.tar.gz` |
|
||||
| Linux (64-bit PC) | `soundtouch-service_linux_amd64.tar.gz` |
|
||||
| macOS (Apple Silicon) | `soundtouch-service_darwin_arm64.tar.gz` |
|
||||
| macOS (Intel) | `soundtouch-service_darwin_amd64.tar.gz` |
|
||||
| Windows | `soundtouch-service_windows_amd64.zip` |
|
||||
|
||||
Extract the archive. You will find a single file called `soundtouch-service` (or `soundtouch-service.exe` on Windows).
|
||||
|
||||
### Alternative: Docker
|
||||
|
||||
If you already use Docker, you can run AfterTouch as a container instead. See the [Deployment Guide](DEPLOYMENT.md) for Docker instructions.
|
||||
|
||||
---
|
||||
|
||||
## Step 2: Run it
|
||||
|
||||
Open a terminal (or Command Prompt on Windows), navigate to the folder where you extracted the file, and run:
|
||||
|
||||
```
|
||||
./soundtouch-service
|
||||
```
|
||||
|
||||
On Windows:
|
||||
```
|
||||
soundtouch-service.exe
|
||||
```
|
||||
|
||||
You should see log output like:
|
||||
```
|
||||
Starting AfterTouch service on :8000
|
||||
```
|
||||
|
||||
AfterTouch is now running on port 8000.
|
||||
|
||||
---
|
||||
|
||||
## Step 3: Open the web interface
|
||||
|
||||
In a web browser on any device on your network, go to:
|
||||
|
||||
```
|
||||
http://<your-server-ip>:8000
|
||||
```
|
||||
|
||||
Replace `<your-server-ip>` with the actual IP address of the computer running AfterTouch. For example: `http://192.168.1.100:8000`.
|
||||
|
||||
If you are on the same computer that is running AfterTouch, you can use `http://localhost:8000`.
|
||||
|
||||
You should see the AfterTouch web interface with tabs: Overview, Settings, Devices, and so on.
|
||||
|
||||
---
|
||||
|
||||
## Step 4: Configure the server URL
|
||||
|
||||
This is the most important setting. Go to the **Settings** tab and set the **Target Domain** to the full address of your AfterTouch server — the same address you used to open the web interface:
|
||||
|
||||
```
|
||||
http://192.168.1.100:8000
|
||||
```
|
||||
|
||||
Use the IP address of your server, **not** `localhost`. Your speakers need to reach this address over the network, and they cannot resolve `localhost`.
|
||||
|
||||
Click **Save Settings**.
|
||||
|
||||
---
|
||||
|
||||
## Step 5: Proceed with migration
|
||||
|
||||
You are now ready to migrate your speakers. Follow the main [Migration Guide](MIGRATION-GUIDE.md) for the remaining steps (discovering devices, syncing data, and redirecting your speakers to AfterTouch).
|
||||
|
||||
---
|
||||
|
||||
## Keeping AfterTouch running
|
||||
|
||||
By default, AfterTouch stops when you close the terminal. To keep it running permanently:
|
||||
|
||||
**Raspberry Pi / Linux:** See the [Raspberry Pi Guide](RASPBERRY-PI.md) for instructions on running AfterTouch as a background service using `systemd`.
|
||||
|
||||
**NAS devices:** Most NAS systems support Docker. Use the Docker instructions in the [Deployment Guide](DEPLOYMENT.md).
|
||||
|
||||
**macOS:** You can use `launchd` to run AfterTouch at login. Creating a `launchd` plist is beyond this guide, but the [Deployment Guide](DEPLOYMENT.md) has a systemd example you can adapt.
|
||||
|
||||
**Windows:** You can use Task Scheduler to run AfterTouch at startup.
|
||||
|
||||
---
|
||||
|
||||
## Stable IP address
|
||||
|
||||
AfterTouch must always be reachable at the same address, because your speakers will be configured to point to it. If the IP changes, your speakers will stop working until you reconfigure them.
|
||||
|
||||
The easiest solution is to assign a **static (fixed) IP address** to the computer running AfterTouch in your router's settings. Look for "DHCP reservation" or "static IP" in your router's administration interface, and bind the server's MAC address to a fixed IP.
|
||||
|
||||
---
|
||||
|
||||
## Security note
|
||||
|
||||
AfterTouch's web interface and management API have no login by default. On a typical home network this is fine, since only devices on your local network can reach it.
|
||||
|
||||
If you want to restrict access — for example, on a shared network — start the service with a username and password:
|
||||
|
||||
```
|
||||
./soundtouch-service --mgmt-username admin --mgmt-password yourpassword
|
||||
```
|
||||
|
||||
This protects the Settings tab (where your Spotify and Amazon credentials are stored) from being read or changed by others on the network.
|
||||
@@ -7,7 +7,7 @@ The `soundtouch-service` is a comprehensive local server that emulates Bose's cl
|
||||
The service provides:
|
||||
|
||||
- **🏠 Local Service Emulation**: Complete BMX (Bose Media eXchange) and Marge service implementation
|
||||
- **🔧 Device Migration**: Seamlessly migrate devices from Bose cloud to local services via XML config, `/etc/hosts`, or `/etc/resolv.conf`
|
||||
- **🔧 Device Migration**: Migrate devices from Bose cloud to local services via XML redirect or DNS/DHCP redirect
|
||||
- **🔍 DNS Discovery & Interception**: Built-in DNS server to discover unknown Bose endpoints and selectively intercept cloud traffic
|
||||
- **📊 Traffic Proxying**: Inspect and log all device communications for debugging
|
||||
- **🌐 Web Management UI**: Browser-based interface for device management
|
||||
@@ -169,7 +169,7 @@ The service supports multiple ways to configure its behavior. When multiple sour
|
||||
| `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 `resolv.conf` migration) | `:53` |
|
||||
| `DNS_BIND_ADDR` | `--dns-bind` | Bind address for the DNS discovery server (standard port `:53` is required for DNS/DHCP migration) | `:53` |
|
||||
| `MIRROR_ENABLED` | | Enable background mirroring of specific endpoints to Bose cloud | `false` |
|
||||
| `MIRROR_ENDPOINTS` | | Comma-separated list of path patterns to mirror (e.g., `/streaming/account/*/device/*/recent`) | `[]` |
|
||||
| `INTERNAL_PATHS` | `--internal-paths` | Paths for internal requests to exclude from recording (e.g., `/setup/*`, `/web/*`) | `[]` |
|
||||
@@ -247,7 +247,7 @@ curl "http://192.168.1.100:8090/presets"
|
||||
curl "http://localhost:8000/events/192.168.1.100"
|
||||
```
|
||||
|
||||
#### ResolvConf Migration (DHCP-Aware DNS Redirection)
|
||||
#### DNS/DHCP Migration (DHCP-Aware DNS Redirection)
|
||||
|
||||
The most robust and flexible DNS-based migration method. It utilizes the device's persistent `/mnt/nv/rc.local` script to inject a priority DNS hook into the system's DHCP configuration.
|
||||
|
||||
@@ -665,7 +665,7 @@ find data/stats/ -name "*.json" -mtime +90 -delete
|
||||
- `GET /setup/discovery-status`: Check if a scan is currently in progress.
|
||||
- `POST /setup/sync/{deviceIP}`: Fetch presets, recents, and sources from a device.
|
||||
- `GET /setup/summary/{deviceIP}`: Get a detailed migration readiness summary.
|
||||
- `POST /setup/migrate/{deviceIP}`: Migrate a device using the specified method (XML/Hosts).
|
||||
- `POST /setup/migrate/{deviceIP}`: Migrate a device using the specified method (XML or DNS).
|
||||
- `GET /setup/ca.crt`: Download the Root CA certificate for manual installation.
|
||||
|
||||
#### `GET /setup/interactions`
|
||||
|
||||
@@ -1,85 +1,107 @@
|
||||
### Bose Cloud Shutdown: Survival Guide for SoundTouch
|
||||
# Bose Cloud Shutdown: Survival Guide
|
||||
|
||||
With Bose's announcement of discontinuing cloud support for SoundTouch devices in May 2026, this project provides the necessary tools to keep your speakers fully functional using a local emulation service.
|
||||
Bose is shutting down SoundTouch cloud services on **May 6, 2026**. After that date, the following stop working:
|
||||
|
||||
This guide explains how to set up the `soundtouch-service` to run your devices independently of Bose's servers.
|
||||
- Music service browsing (TuneIn, Spotify connect via app, etc.)
|
||||
- Preset and recently-played sync
|
||||
- The official SoundTouch app
|
||||
- Software update checks
|
||||
|
||||
What **continues to work** regardless:
|
||||
- Local playback controls via `soundtouch-cli`, `soundtouch-web`, or any app that uses the local Web API
|
||||
- Bluetooth, AUX, and AirPlay inputs
|
||||
- Multiroom zones (local, peer-to-peer)
|
||||
|
||||
**AfterTouch** — the `soundtouch-service` — restores everything in the first list by running a local replacement for the Bose cloud on your own network.
|
||||
|
||||
---
|
||||
|
||||
### Supported Use Cases
|
||||
## How it works
|
||||
|
||||
1. **Local Service Emulation**: The service emulates Bose's BMX (Bose Media eXchange) and Marge services, which handle content registries, presets, recents, and software update checks.
|
||||
2. **Traffic Redirection**: Tools are provided to redirect your speakers to this local service instead of `*.bose.com`.
|
||||
3. **Offline Operation**: Once redirected, the speakers function without needing to reach Bose's servers.
|
||||
4. **Preset & Recent Management**: Captures and stores presets and "recently played" items locally.
|
||||
The service emulates the Bose cloud endpoints that speakers call for music service browsing, device registration, preset sync, and update checks. Once a speaker is redirected to point at the local service instead of Bose's servers, it operates independently. The built-in web UI at `http://<server>:8000` handles all setup steps.
|
||||
|
||||
---
|
||||
|
||||
### Setup Steps
|
||||
## Prerequisites
|
||||
|
||||
To set up your SoundTouch system for local-only operation, follow these steps:
|
||||
### 1. A machine that's always on
|
||||
|
||||
#### 1. Install and Start the Service
|
||||
Run the `soundtouch-service` on a machine that is always on (like a Raspberry Pi or a NAS) within your local network.
|
||||
The service must run on a host that's available whenever your speakers are in use — a Raspberry Pi, NAS, home server, or similar. The host needs a stable local address (e.g. `soundtouch.fritz.box` or a fixed IP) reachable from your speakers.
|
||||
|
||||
```bash
|
||||
# Install the service
|
||||
go install github.com/gesellix/bose-soundtouch/cmd/soundtouch-service@latest
|
||||
See [Raspberry Pi Setup](RASPBERRY-PI.md) and the [SoundTouch Service Guide](SOUNDTOUCH-SERVICE.md) for deployment options, including Docker.
|
||||
|
||||
# Start the service (defaults to http://localhost:8000)
|
||||
soundtouch-service
|
||||
```
|
||||
### 2. SSH access on your speakers (for migration)
|
||||
|
||||
#### 2. Access the Management UI
|
||||
Open your web browser and navigate to the service's web interface:
|
||||
`http://<your-server-ip>:8000/`, e.g. `http://localhost:8000/`
|
||||
Redirecting a speaker's service URLs requires writing to its configuration. This is done via SSH. Enable it once per device:
|
||||
|
||||
*Note: The service also supports a `/web/` path for management.*
|
||||
1. 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.
|
||||
2. Insert the drive into the speaker's USB port while it's powered on.
|
||||
3. Power-cycle the speaker (unplug and replug). After boot, root SSH is available with no password.
|
||||
|
||||
#### 3. Enable SSH on Your Speakers
|
||||
To migrate your speakers, the service needs SSH access. You can enable it by:
|
||||
1. Creating an empty file named `remote_services` on a USB stick.
|
||||
2. Inserting the USB stick into the SoundTouch speaker's service port.
|
||||
3. Rebooting the speaker (unplug/replug).
|
||||
|
||||
**Verify SSH Access:**
|
||||
- Confirm the device responds to SSH without a password: `ssh -o HostKeyAlgorithms=+ssh-rsa -o PubkeyAcceptedAlgorithms=+ssh-rsa root@<IP>`
|
||||
- Or use the **Migration** tab in the Web UI to see if the device shows a "✅ Success" status for SSH.
|
||||
Once enabled, you can log in as `root` (no password).
|
||||
|
||||
#### 4. Setup Through the Web UI
|
||||
The web interface handles the entire process in a guided flow. Before proceeding, we strongly recommend reviewing the [Migration & Safety Guide](MIGRATION-SAFETY.md).
|
||||
|
||||
* **Step 1: Settings**: Configure your server's IP or domain. This ensures the speakers know where to find the local services.
|
||||
* **Step 2: Devices**: The service automatically scans for SoundTouch devices on your network. If a device is not found, you can manually add its IP address.
|
||||
* **Step 3: Data Sync**: Select your device and click "Start Sync". This will automatically fetch your presets, recents, and configured sources from the speaker and store them in the local `data/` directory.
|
||||
* **Step 4: Migration**: Choose your redirection method (XML Recommended) and click "Confirm Migration". After the migration, reboot your speaker to apply the changes.
|
||||
|
||||
#### 5. Verify Your Local Data
|
||||
Once migrated, your speaker will use the data captured during the Sync step.
|
||||
* The service stores data in the `data/` directory, organized by device serial number (e.g., `data/default/devices/<SERIAL>/`).
|
||||
* **Automatic Capture**: As you use the device (changing presets, playing new music), the service continues to "learn" and update your local files.
|
||||
You can leave SSH enabled for future maintenance, or disable it once migration is complete.
|
||||
|
||||
---
|
||||
|
||||
### Comparison with other implementations (soundcork)
|
||||
Our implementation (`soundtouch-service`) is largely compatible with the Python-based `soundcork` project but offers several advantages:
|
||||
- **Web UI**: Integrated management interface for discovery and migration.
|
||||
- **Surgical Migration**: Uses XML-based redirection by default, which is less invasive than `/etc/hosts`.
|
||||
- **Automated SSL**: Handles Root CA injection automatically for secure communication.
|
||||
- **Proxy Support**: Can proxy requests to original Bose servers while "learning" your configuration.
|
||||
## Scenario A: Migrate before the shutdown
|
||||
|
||||
Do this while the Bose cloud is still running. Your existing presets and listening history are preserved.
|
||||
|
||||
**Step 1 — Back up your data.**
|
||||
Run `soundtouch-backup all` to save your Bose account data (presets, paired devices, music sources) and each speaker's local state. See the [soundtouch-backup README](../../cmd/soundtouch-backup/README.md) for usage.
|
||||
|
||||
**Step 2 — Start the service and open the web UI** at `http://<server>:8000`.
|
||||
|
||||
**Step 3 — Configure the server URL.**
|
||||
In the Settings tab, set the server URL to the address your speakers can reach (e.g. `http://soundtouch.fritz.box:8000`). If you plan to use DNS/DHCP redirect, also configure the HTTPS server URL.
|
||||
|
||||
**Step 4 — Add your speaker.**
|
||||
The service discovers devices on your network automatically. If a speaker doesn't appear, add it manually by IP address.
|
||||
|
||||
**Step 5 — Sync device data.**
|
||||
Click "Sync" on the device to pull its current presets, recents, and sources from the Bose cloud into the local service's datastore.
|
||||
|
||||
**Step 6 — Migrate.**
|
||||
The web UI offers two redirect methods and walks you through each step:
|
||||
|
||||
| Method | How it works | When to use |
|
||||
|--------------|--------------------------------------------------------|----------------------------------------------------------|
|
||||
| XML redirect | Uploads a config file to the speaker via the Web API | Testing; simpler setup; covers only registered endpoints |
|
||||
| DNS/DHCP | Custom DNS resolves Bose hostnames to the local server | All devices at once; full coverage |
|
||||
|
||||
Both methods require TLS when the speaker uses HTTPS to contact the service. The web UI guides you through installing the service's CA certificate on the speaker (requires SSH).
|
||||
|
||||
**Step 7 — Reboot the speaker.**
|
||||
Power-cycle the speaker to apply the changes. After reboot it contacts the local service instead of Bose's cloud.
|
||||
|
||||
---
|
||||
|
||||
### Alternative: DNS Redirection (No SSH)
|
||||
If you prefer not to modify your speakers via SSH, you can use a local DNS server (like Pi-hole, AdGuard Home, or Unbound) to point the following domains to your local server's IP:
|
||||
## Scenario B: Set up after the shutdown (or after a factory reset)
|
||||
|
||||
* `bmx.bose.com`
|
||||
* `streaming.bose.com`
|
||||
* `updates.bose.com`
|
||||
* `stats.bose.com`
|
||||
* `content.api.bose.io`
|
||||
If the Bose cloud is gone, or you've factory-reset a speaker, there's no existing account to migrate from. You start fresh with a local account.
|
||||
|
||||
*Note: DNS redirection for HTTPS services requires the speakers to trust your local service's SSL certificate. The SSH-based migration handles this automatically by injecting the CA.*
|
||||
**Step 1 — Set up DNS/DHCP redirect first** (recommended).
|
||||
Configure your network's DNS to resolve the Bose cloud hostnames to the local service's address before the speaker tries to register. This way, when the speaker boots and attempts to register, it reaches AfterTouch automatically instead of failing to reach Bose.
|
||||
|
||||
See the [SoundTouch Service Guide](SOUNDTOUCH-SERVICE.md) for the built-in DNS server configuration and the list of hostnames to redirect.
|
||||
|
||||
**Step 2 — Connect the speaker to Wi-Fi.**
|
||||
Use the speaker's built-in AP mode or BLE setup flow. See [Device Initial Setup](DEVICE-INITIAL-SETUP.md) for factory reset button sequences and Wi-Fi provisioning.
|
||||
|
||||
**Step 3 — Start the service and open the web UI** at `http://<server>:8000`.
|
||||
|
||||
**Step 4 — Add the speaker.**
|
||||
After connecting to Wi-Fi, the speaker should appear in the web UI automatically (or add it manually by IP). If DNS redirect is already in place, the speaker is already communicating with AfterTouch.
|
||||
|
||||
**Step 5 — Migrate** (if not already using DNS redirect).
|
||||
If you didn't set up DNS first, use the XML redirect method from the web UI to update the speaker's service URLs. The web UI walks you through the steps including CA certificate setup.
|
||||
|
||||
**Step 6 — Reboot the speaker.**
|
||||
Power-cycle to ensure all changes take effect.
|
||||
|
||||
---
|
||||
|
||||
## After migration
|
||||
|
||||
Once migrated, your speaker uses the local service for music browsing, preset sync, and device registration. The web UI at `http://<server>:8000` is your management interface going forward. Back up the `data/` directory periodically in case you need to restore.
|
||||
|
||||
For the complete step-by-step walkthrough with commands and troubleshooting, see the [Migration Guide](MIGRATION-GUIDE.md). For safety measures and rollback options, see the [Migration & Safety Guide](MIGRATION-SAFETY.md).
|
||||
|
||||
@@ -853,6 +853,85 @@ cat data/accounts/3230304/devices/*/DeviceInfo.xml | grep macAddress
|
||||
|
||||
---
|
||||
|
||||
## 🌐 **Hostname Resolution** {#hostname-resolution}
|
||||
|
||||
### Why the service resolves the hostname from the device
|
||||
|
||||
When you migrate a speaker using the resolv.conf method, the service needs to write a raw IP address into the speaker's network configuration. That IP must be the address the *speaker itself* can reach — which is not necessarily the same address your computer resolves.
|
||||
|
||||
In environments with NAT, split-horizon DNS, or Docker/container networking, `soundtouch.local` (or whatever you set as `SERVER_URL`) may resolve to a different IP depending on who is asking. The service therefore resolves the hostname by running `ping -c 1 <hostname>` over SSH on the speaker and extracting the IP from the output. This is the authoritative result: it is exactly what the speaker would use.
|
||||
|
||||
If that SSH ping fails, migration is aborted. Writing an unresolvable or incorrectly resolved hostname into `aftertouch.resolv.conf` would silently break the speaker's DNS config and prevent it from reaching the service after reboot.
|
||||
|
||||
**The XML migration method is different.** It writes the full URL (e.g. `http://soundtouch.local:8000`) into `SoundTouchSdkPrivateCfg.xml`. The speaker resolves the hostname at connect time, not at migration time. This means migration can proceed even if the hostname is not yet reachable — for example, when the service will be deployed under that hostname but is not running yet. A warning is still shown in the UI so you are aware, but the Confirm Migration button remains enabled.
|
||||
|
||||
### ❌ "Cannot resolve target hostname for migration"
|
||||
|
||||
**Symptoms** (migration log or web UI warning):
|
||||
```
|
||||
cannot resolve target hostname for migration: cannot resolve "soundtouch.local":
|
||||
SSH ping from device failed and service-side DNS lookup also failed
|
||||
```
|
||||
or:
|
||||
```
|
||||
resolved "soundtouch.local" to 192.168.1.100 from service, not from device —
|
||||
result may be wrong if NAT or split-DNS is in use
|
||||
```
|
||||
|
||||
**What this means:**
|
||||
|
||||
The service could not confirm the IP by running `ping` on the speaker via SSH. Either:
|
||||
- the `ping` binary is not available or not in `$PATH` on this firmware, or
|
||||
- the hostname is not resolvable from the speaker's network context.
|
||||
|
||||
**Diagnosis — run manually over SSH:**
|
||||
|
||||
```bash
|
||||
# SSH into the speaker
|
||||
ssh root@<speaker-ip>
|
||||
|
||||
# Try to resolve the service hostname
|
||||
ping -c 1 soundtouch.local
|
||||
# or use the IP directly to verify connectivity
|
||||
ping -c 1 192.168.1.100
|
||||
|
||||
# Check the speaker's current DNS config
|
||||
cat /etc/resolv.conf
|
||||
|
||||
# Check if ping is available
|
||||
which ping
|
||||
busybox ping --help
|
||||
```
|
||||
|
||||
**Solutions:**
|
||||
|
||||
#### 1. Use an IP address as SERVER_URL
|
||||
|
||||
The most reliable fix. If the hostname cannot be resolved from the device, use a raw IP instead. Resolution is skipped entirely when `SERVER_URL` contains an IP.
|
||||
|
||||
```bash
|
||||
# In your .env
|
||||
SERVER_URL=http://192.168.1.100:8000
|
||||
HTTPS_SERVER_URL=https://192.168.1.100:8443
|
||||
```
|
||||
|
||||
HTTPS works correctly with IP addresses — the service certificate includes the IP as a Subject Alternative Name (SAN).
|
||||
|
||||
#### 2. Ensure the hostname resolves on the speaker's network segment
|
||||
|
||||
If you use `soundtouch.local`, verify mDNS is working from another device on the same subnet:
|
||||
|
||||
```bash
|
||||
avahi-resolve -n soundtouch.local # Linux
|
||||
dns-sd -G v4 soundtouch.local # macOS
|
||||
```
|
||||
|
||||
#### 3. Use the XML migration method
|
||||
|
||||
Select the XML method in the migration UI. It writes the full URL and the speaker resolves it at connect time, so hostname resolution is not required during migration. This also allows migrating to a hostname that is not yet live.
|
||||
|
||||
---
|
||||
|
||||
## 🛟 **Getting More Help**
|
||||
|
||||
### Information to Gather
|
||||
|
||||
@@ -1,90 +1,17 @@
|
||||
# Images for Migration Guide
|
||||
# docs/images
|
||||
|
||||
This directory contains images, screenshots, and diagrams referenced in the migration guide and other documentation.
|
||||
Screenshots and diagrams referenced by the documentation.
|
||||
|
||||
## Required Images for Migration Guide
|
||||
## Current screenshots
|
||||
|
||||
The following images need to be created to complete the migration guide:
|
||||
| File | Shows | Used in |
|
||||
|------|-------|---------|
|
||||
| `ui-settings.png` | AfterTouch web UI — Settings tab (Target Domain, DNS Discovery, Mirroring) | Migration Guide |
|
||||
| `ui-devices.png` | AfterTouch web UI — Devices tab (discovered speakers with Sync/Migrate actions) | Migration Guide |
|
||||
| `ui-sync.png` | AfterTouch web UI — Data Sync tab (successful sync result) | Migration Guide |
|
||||
| `ui-migration.png` | AfterTouch web UI — Migration tab (HTTPS test, DNS test, method selector) | Migration Guide |
|
||||
| `speaker-ap-wifi-setup.png` | Speaker AP mode Wi-Fi setup page at `http://192.0.2.1` | Device Initial Setup |
|
||||
|
||||
### Dashboard Screenshots
|
||||
- **dashboard-home.png** - Main SoundTouch Service dashboard homepage
|
||||
- **account-creation.png** - Account creation form with fields filled
|
||||
- **account-dashboard.png** - Fresh account dashboard showing ready state
|
||||
- **device-discovery.png** - Device discovery page showing found speakers
|
||||
- **device-registration.png** - Device registration dialog with options
|
||||
- **migration-setup.png** - Migration configuration dialog
|
||||
- **migration-progress.png** - Migration progress tracker showing phases
|
||||
- **migration-health.png** - Migration health monitoring dashboard
|
||||
- **account-migration.png** - Account-wide migration progress overview
|
||||
- **migration-complete.png** - Completed migration dashboard view
|
||||
- **backup-setup.png** - Backup configuration settings page
|
||||
## Adding new screenshots
|
||||
|
||||
### Setup and Preparation
|
||||
- **usb-remote-services.png** - USB drive setup showing file structure
|
||||
- **raspberry-pi-setup.png** - Raspberry Pi with connected cables (optional)
|
||||
|
||||
### Process Diagrams
|
||||
- **migration-flow-diagram.png** - Flow chart showing migration phases
|
||||
- **network-topology.png** - Network diagram showing Pi, router, speakers
|
||||
- **data-flow-diagram.png** - How data flows between components
|
||||
|
||||
## Image Requirements
|
||||
|
||||
### Technical Specifications
|
||||
- **Format**: PNG preferred for screenshots, SVG for diagrams
|
||||
- **Resolution**: Minimum 1200px width for screenshots
|
||||
- **File Size**: Keep under 500KB when possible for fast loading
|
||||
- **Naming**: Use descriptive kebab-case names as shown above
|
||||
|
||||
### Content Guidelines
|
||||
- **Clean Interface**: Show realistic but clean interface states
|
||||
- **Consistent Styling**: Use consistent colors and styling across images
|
||||
- **Readable Text**: Ensure all text in screenshots is legible
|
||||
- **Example Data**: Use realistic example data (Living Room Speaker, etc.)
|
||||
- **Status Indicators**: Show clear success/error states with appropriate colors
|
||||
|
||||
### Placeholder Content
|
||||
Until real screenshots are available, consider:
|
||||
- **Mockups**: Create simple mockups showing the expected interface
|
||||
- **Wireframes**: Basic wireframes indicating layout and content
|
||||
- **Diagrams**: Technical diagrams can be created immediately
|
||||
- **Text Placeholders**: Use `[Image: Description]` in documentation
|
||||
|
||||
## Creating the Images
|
||||
|
||||
### For Dashboard Screenshots
|
||||
1. Set up the enhanced SoundTouch service
|
||||
2. Create sample account and register devices
|
||||
3. Take screenshots at key points in the migration process
|
||||
4. Edit for clarity (highlight important elements, add annotations)
|
||||
|
||||
### For Diagrams
|
||||
1. Use tools like Lucidchart, draw.io, or similar
|
||||
2. Follow consistent color scheme:
|
||||
- Blue: SoundTouch Service components
|
||||
- Green: Healthy/successful states
|
||||
- Orange: Warning/in-progress states
|
||||
- Red: Error/problematic states
|
||||
- Gray: External/third-party components
|
||||
|
||||
### For Physical Setup
|
||||
1. Take photos of actual hardware setup
|
||||
2. Show USB drive preparation process
|
||||
3. Demonstrate network connections if helpful
|
||||
|
||||
## Alternative Text Requirements
|
||||
|
||||
Each image should have appropriate alt text for accessibility:
|
||||
|
||||
```markdown
|
||||

|
||||
*Caption: Additional context or explanation*
|
||||
```
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
Consider adding:
|
||||
- **Video Walkthroughs**: Screen recordings of key processes
|
||||
- **Interactive Demos**: Web-based interactive guides
|
||||
- **Troubleshooting Screenshots**: Common error states and solutions
|
||||
- **Mobile Views**: How to access from mobile devices
|
||||
PNG format, 1200 px or wider. Use descriptive kebab-case names. Update this README when adding files.
|
||||
|
After Width: | Height: | Size: 1.2 MiB |
|
After Width: | Height: | Size: 334 KiB |
|
After Width: | Height: | Size: 544 KiB |
|
After Width: | Height: | Size: 516 KiB |
|
After Width: | Height: | Size: 266 KiB |
@@ -0,0 +1,521 @@
|
||||
# SoundTouch Device WebSocket API — Pairing & Operation Flow
|
||||
|
||||
Reference document derived from mitmproxy captures of the Bose SoundTouch Android app
|
||||
(`bose-pairing-20260502-155542`, `bose-pairing-20260502-165549`).
|
||||
|
||||
> **Why this matters:** With Bose cloud services shutting down on 2026-05-06, the original
|
||||
> app may stop working for pairing and playback control. This document captures the exact
|
||||
> WebSocket message sequences needed to replicate those flows independently.
|
||||
|
||||
---
|
||||
|
||||
## Connection
|
||||
|
||||
All interactions use the SoundTouch WebSocket API on the speaker's local IP, port **8090**
|
||||
(the same port as the REST API). Connect with the `Gabbo` sub-protocol:
|
||||
|
||||
```
|
||||
GET ws://192.168.x.y:8090/
|
||||
Upgrade: websocket
|
||||
Sec-WebSocket-Protocol: Gabbo
|
||||
```
|
||||
|
||||
Upon connection the server immediately sends an identification banner:
|
||||
|
||||
```xml
|
||||
<SoundTouchSdkInfo serverVersion="4" serverBuild="trunk r46330 v4 epdbuild hepdswbld04" />
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Message Envelope
|
||||
|
||||
All subsequent messages (except `selectLastWiFiSource`, see below) use this envelope:
|
||||
|
||||
**Client → Server request:**
|
||||
```xml
|
||||
<msg>
|
||||
<header deviceID="{device_id}" url="{endpoint}" method="{GET|POST}">
|
||||
<request requestID="{n}">
|
||||
<info type="new"/> <!-- or type="update" -->
|
||||
<!-- optional: <sourceItem source="TUNEIN"/> -->
|
||||
</request>
|
||||
</header>
|
||||
<body>
|
||||
<!-- payload, may be empty -->
|
||||
</body>
|
||||
</msg>
|
||||
```
|
||||
|
||||
**Server → Client response:**
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<msg>
|
||||
<header deviceID="{device_id}" url="{endpoint}" method="{GET|POST}">
|
||||
<request requestID="{n}" msgType="RESPONSE">
|
||||
<info type="new"/>
|
||||
</request>
|
||||
</header>
|
||||
<body>
|
||||
<!-- response payload -->
|
||||
</body>
|
||||
</msg>
|
||||
```
|
||||
|
||||
**Server → Client push (unsolicited):**
|
||||
```xml
|
||||
<updates deviceID="{device_id}">
|
||||
<nowPlayingUpdated>...</nowPlayingUpdated>
|
||||
</updates>
|
||||
```
|
||||
|
||||
`requestID` is a monotonically increasing integer per connection (client-side sequence).
|
||||
`{device_id}` is the speaker's MAC address with colons removed (e.g. `08DF1F0BA325`).
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — Discovery: Is the Speaker Already Paired?
|
||||
|
||||
```xml
|
||||
<!-- C→S: fetch device info -->
|
||||
<msg><header deviceID="{device_id}" url="info" method="GET">
|
||||
<request requestID="1"><info type="new"/></request>
|
||||
</header></msg>
|
||||
|
||||
<!-- S→C: response -->
|
||||
<info deviceID="{device_id}">
|
||||
<name>SoundTouch 10</name>
|
||||
<type>SoundTouch 10</type>
|
||||
<margeAccountUUID>9569497</margeAccountUUID> <!-- empty = unpaired -->
|
||||
<margeURL>https://streaming.bose.com</margeURL>
|
||||
...
|
||||
</info>
|
||||
```
|
||||
|
||||
- **Empty `margeAccountUUID`** → device is unpaired, proceed to Phase 2
|
||||
- **Populated `margeAccountUUID`** → already paired with that account ID
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — Pairing a New Speaker
|
||||
|
||||
### 2.1 Setup State Machine
|
||||
|
||||
The pairing flow uses a setup state machine on the device. States must be sent in order.
|
||||
|
||||
```xml
|
||||
<!-- 1. Start setup -->
|
||||
<msg><header deviceID="{device_id}" url="setup" method="POST">
|
||||
<request requestID="21"></request>
|
||||
</header><body><setupState state="SETUP_START"/></body></msg>
|
||||
|
||||
<!-- 2. Enter identify mode — device flashes/beeps; 300 000 ms timeout -->
|
||||
<msg><header deviceID="{device_id}" url="setup" method="POST">
|
||||
<request requestID="22"></request>
|
||||
</header><body><setupState state="SETUP_IDENTIFY_DEVICE_ENTER" timeout="300000"/></body></msg>
|
||||
|
||||
<!-- Server pushes: -->
|
||||
<updates deviceID="{device_id}">
|
||||
<soundTouchConfigurationUpdated>
|
||||
<soundTouchConfigurationStatus status="SOUNDTOUCH_CONFIGURING"/>
|
||||
</soundTouchConfigurationUpdated>
|
||||
</updates>
|
||||
|
||||
<!-- 3. Set language (3 = German; adjust as needed) -->
|
||||
<msg><header deviceID="{device_id}" url="language" method="POST">
|
||||
<request requestID="23"></request>
|
||||
</header><body><sysLanguage>3</sysLanguage></body></msg>
|
||||
|
||||
<!-- 4. Enter setup (user has confirmed identification) -->
|
||||
<msg><header deviceID="{device_id}" url="setup" method="POST">
|
||||
<request requestID="24"></request>
|
||||
</header><body><setupState state="SETUP_ENTER"/></body></msg>
|
||||
|
||||
<!-- 5. Leave identify mode -->
|
||||
<msg><header deviceID="{device_id}" url="setup" method="POST">
|
||||
<request requestID="25"></request>
|
||||
</header><body><setupState state="SETUP_IDENTIFY_DEVICE_LEAVE"/></body></msg>
|
||||
|
||||
<!-- 6. Set device name -->
|
||||
<msg><header deviceID="{device_id}" url="name" method="POST">
|
||||
<request requestID="26"></request>
|
||||
</header><body><name>My SoundTouch 10</name></body></msg>
|
||||
```
|
||||
|
||||
### 2.2 Account Pairing — The Critical Step
|
||||
|
||||
```xml
|
||||
<!-- C→S: pair device with account -->
|
||||
<msg><header deviceID="{device_id}" url="setMargeAccount" method="POST">
|
||||
<request requestID="27"></request>
|
||||
</header><body>
|
||||
<PairDeviceWithAccount>
|
||||
<accountId>{accountId}</accountId>
|
||||
<userAuthToken>Bearer {token}</userAuthToken>
|
||||
</PairDeviceWithAccount>
|
||||
</body></msg>
|
||||
|
||||
<!-- S→C: device info response with margeAccountUUID now set -->
|
||||
<info deviceID="{device_id}">
|
||||
...
|
||||
<margeAccountUUID>{accountId}</margeAccountUUID>
|
||||
...
|
||||
</info>
|
||||
```
|
||||
|
||||
The server also pushes several `sourcesUpdated` events after successful pairing.
|
||||
|
||||
**`{accountId}`** — the numeric Bose account ID (e.g. `9569497`), obtainable from
|
||||
`GET /streaming/account/login` on soundtouch-service.
|
||||
|
||||
**`{token}`** — a Bearer token issued by Bose authentication (or soundtouch-service).
|
||||
The full token from the captures:
|
||||
```
|
||||
Bearer NtJDRbNtY3hDhm5K8FC2JprRhRQNH3QdZjG6aR4ASwYQg4rvZMY6dPLc3Bm6zvWNciWzCpMWZ/dbITRQoVdClOdssgDO+Nlh4ZJWp2w3tZiGzB8Flho0c+ipXnT/0Yg5
|
||||
```
|
||||
(session-specific; obtain a fresh one from the service's account login flow)
|
||||
|
||||
### 2.3 Finish Setup and Telemetry
|
||||
|
||||
```xml
|
||||
<!-- Leave setup state machine -->
|
||||
<msg><header deviceID="{device_id}" url="setup" method="POST">
|
||||
<request requestID="28"></request>
|
||||
</header><body><setupState state="SETUP_LEAVE"/></body></msg>
|
||||
|
||||
<!-- Trigger device to sync customer support info to Marge cloud -->
|
||||
<msg><header deviceID="{device_id}" url="pushCustomerSupportInfoToMarge" method="GET">
|
||||
<request requestID="29"></request>
|
||||
</header></msg>
|
||||
|
||||
<!-- S→C: -->
|
||||
<status>/pushCustomerSupportInfoToMarge</status>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Unpairing
|
||||
|
||||
```xml
|
||||
<!-- C→S: remove device from account -->
|
||||
<msg><header deviceID="{device_id}" url="setMargeAccount" method="POST">
|
||||
<request requestID="24">
|
||||
<info mainNode="removeDevice" type="new"/>
|
||||
<sourceItem source="SETTINGS" sourceAccount="{device_id}"/>
|
||||
</request>
|
||||
</header><body><UnPairDeviceWithAccount/></body></msg>
|
||||
|
||||
<!-- S→C: response with device info showing empty margeAccountUUID -->
|
||||
<!-- Server also pushes: <updates><infoUpdated/></updates> -->
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — App Initialization (Bulk State Fetch)
|
||||
|
||||
When the app connects to an already-paired device it sends these in rapid parallel sequence:
|
||||
|
||||
```
|
||||
info (GET) — device metadata, check pairing
|
||||
sources (GET) — available input sources
|
||||
presets (GET) — saved presets 1–6
|
||||
swUpdateQuery (POST) — check if update is in progress
|
||||
capabilities (GET) — hardware capabilities, network config
|
||||
bassCapabilities (GET) — bass range and defaults
|
||||
now_playing (GET) — current playback state
|
||||
volume (GET) — current volume
|
||||
getZone (GET) — multi-room zone membership
|
||||
clockDisplay (POST) — set clock timezone/format
|
||||
```
|
||||
|
||||
Then a second wave:
|
||||
|
||||
```
|
||||
swUpdateCheck (POST) — check for new firmware
|
||||
systemtimeout (GET) — power-saving timeout
|
||||
rebroadcastlatencymode (GET) — zone latency mode
|
||||
getGroup (GET) — stereo-pair group
|
||||
language (GET, sourceItem source="settings") — UI language
|
||||
bass (GET) — current bass level
|
||||
serviceAvailability (GET, sourceItem source="add_service" or "settings")
|
||||
webserver/pingRequest (GET) — keepalive
|
||||
pushCustomerSupportInfoToMarge (GET) — telemetry
|
||||
netStats (GET, sourceItem source="settings") — network statistics
|
||||
introspect (POST, sourceItem source="AIRPLAY") — AirPlay2 capabilities
|
||||
```
|
||||
|
||||
`clockDisplay` example with timezone:
|
||||
```xml
|
||||
<clockDisplay>
|
||||
<clockConfig timezoneInfo="Europe/Berlin" timeFormat="TIME_FORMAT_12HOUR_ID"/>
|
||||
</clockDisplay>
|
||||
```
|
||||
|
||||
`serviceAvailability` response lists availability of all service types (PANDORA, AIRPLAY,
|
||||
AMAZON, DEEZER, SPOTIFY, TUNEIN, SIRIUSXM_EVEREST, BLUETOOTH, etc.) with `isAvailable`
|
||||
and optional `reason` attributes.
|
||||
|
||||
---
|
||||
|
||||
## Playback Control
|
||||
|
||||
### Start Playback via `playbackRequest` (preferred — bypasses source checks)
|
||||
|
||||
```xml
|
||||
<msg><header deviceID="{device_id}" url="playbackRequest" method="POST">
|
||||
<request requestID="{n}"><info type="new"/></request>
|
||||
</header><body>
|
||||
<playbackRequest source="TUNEIN" sourceAccount="">
|
||||
<container type="stationurl"
|
||||
location="/v1/playback/station/s25260"
|
||||
isPresetable="true"
|
||||
source="TUNEIN"
|
||||
sourceAccount="">
|
||||
<itemName>1LIVE</itemName>
|
||||
</container>
|
||||
</playbackRequest>
|
||||
</body></msg>
|
||||
|
||||
<!-- S→C response: -->
|
||||
<playbackResponse source="TUNEIN" sourceAccount=""/>
|
||||
|
||||
<!-- S→C pushes: nowPlayingUpdated, recentsUpdated -->
|
||||
```
|
||||
|
||||
For a TuneIn podcast episode, use `type="tracklisturl"` and
|
||||
`location="/v1/playback/episodes/{id}?encoded_name={base64}"`.
|
||||
|
||||
### Select Content via `select` (triggers preset/recents UI highlight)
|
||||
|
||||
```xml
|
||||
<msg><header deviceID="{device_id}" url="select" method="POST">
|
||||
<request requestID="{n}"><info type="new"/></request>
|
||||
</header><body>
|
||||
<ContentItem source="TUNEIN"
|
||||
type="stationurl"
|
||||
location="/v1/playback/station/s25260"
|
||||
sourceAccount="TUNEIN"
|
||||
isPresetable="true">
|
||||
<itemName>1LIVE</itemName>
|
||||
</ContentItem>
|
||||
</body></msg>
|
||||
```
|
||||
|
||||
Note: `select` with a TUNEIN item that the device can't resolve directly may return
|
||||
`error value="1005" name="UNKNOWN_SOURCE_ERROR"`. Use `playbackRequest` instead for
|
||||
reliable playback.
|
||||
|
||||
### Special: Select Last Wi-Fi Source
|
||||
|
||||
A plain-text (non-XML) client message:
|
||||
```
|
||||
selectLastWiFiSource
|
||||
```
|
||||
|
||||
Server responds with plain text:
|
||||
```
|
||||
<?xml version="1.0" encoding="UTF-8" ?><status>/selectLastWiFiSource</status>
|
||||
```
|
||||
|
||||
### Key Presses
|
||||
|
||||
```xml
|
||||
<!-- press -->
|
||||
<msg><header deviceID="{device_id}" url="key" method="POST">
|
||||
<request requestID="{n}"><info mainNode="keyPress" type="new"/><sourceItem source="TUNEIN"/></request>
|
||||
</header><body><key state="press" sender="Gabbo">{KEY}</key></body></msg>
|
||||
|
||||
<!-- release (required for POWER — not for STOP/PAUSE) -->
|
||||
<msg><header deviceID="{device_id}" url="key" method="POST">
|
||||
<request requestID="{n}"><info mainNode="keyRelease" type="new"/><sourceItem source="TUNEIN"/></request>
|
||||
</header><body><key state="release" sender="Gabbo">{KEY}</key></body></msg>
|
||||
```
|
||||
|
||||
Key names observed: `POWER`, `STOP`, `PAUSE`, `ADD_FAVORITE`
|
||||
|
||||
`sender="Gabbo"` is the app identifier string used by all Bose mobile apps.
|
||||
|
||||
### Volume
|
||||
|
||||
```xml
|
||||
<!-- Set volume (0–100) -->
|
||||
<msg><header deviceID="{device_id}" url="volume" method="POST">
|
||||
<request requestID="{n}"><info mainNode="volume" type="new"/><sourceItem source="TUNEIN"/></request>
|
||||
</header><body><volume>30</volume></body></msg>
|
||||
|
||||
<!-- S→C push: -->
|
||||
<updates deviceID="{device_id}">
|
||||
<volumeUpdated>
|
||||
<volume><targetvolume>30</targetvolume><actualvolume>30</actualvolume><muteenabled>false</muteenabled></volume>
|
||||
</volumeUpdated>
|
||||
</updates>
|
||||
```
|
||||
|
||||
### Bass
|
||||
|
||||
```xml
|
||||
<!-- Get -->
|
||||
<msg><header deviceID="{device_id}" url="bass" method="GET">
|
||||
<request requestID="{n}"><info type="new"/></request>
|
||||
</header></msg>
|
||||
|
||||
<!-- Set (range: bassMin to bassMax from bassCapabilities, typically -9 to 0) -->
|
||||
<msg><header deviceID="{device_id}" url="bass" method="POST">
|
||||
<request requestID="{n}"><info mainNode="bassSet" type="new"/><sourceItem source="SETTINGS"/></request>
|
||||
</header><body><bass>-2</bass></body></msg>
|
||||
|
||||
<!-- S→C push: <updates><bassUpdated/></updates> -->
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Browse & Navigate
|
||||
|
||||
```xml
|
||||
<!-- Open recents menu -->
|
||||
<msg><header deviceID="{device_id}" url="navigate" method="POST">
|
||||
<request requestID="{n}"><info mainNode="navigateMenu" type="new"/><sourceItem source="RECENTS"/></request>
|
||||
</header><body><navigate menu="recents"/></body></msg>
|
||||
|
||||
<!-- S→C response: -->
|
||||
<navigateResponse menu="recents">
|
||||
<totalItems>4</totalItems>
|
||||
<items>
|
||||
<item type="stationurl" source="TUNEIN" location="/v1/playback/station/s25260"
|
||||
sourceAccount="TUNEIN" isPresetable="true" id="0">
|
||||
<itemName>1LIVE</itemName>
|
||||
</item>
|
||||
...
|
||||
</items>
|
||||
</navigateResponse>
|
||||
```
|
||||
|
||||
Use `type="update"` on `<info>` for subsequent refresh calls on the same menu.
|
||||
|
||||
---
|
||||
|
||||
## Settings
|
||||
|
||||
### System Timeout (Power-Saving)
|
||||
|
||||
```xml
|
||||
<!-- Read -->
|
||||
<msg><header deviceID="{device_id}" url="systemtimeout" method="GET">
|
||||
<request requestID="{n}"><info type="new"/></request>
|
||||
</header></msg>
|
||||
|
||||
<!-- Write: disable auto power-off -->
|
||||
<msg><header deviceID="{device_id}" url="systemtimeout" method="POST">
|
||||
<request requestID="{n}"><info mainNode="systemtimeout" type="new"/><sourceItem source="SETTINGS"/></request>
|
||||
</header><body><systemtimeout><powersaving_enabled>false</powersaving_enabled></systemtimeout></body></msg>
|
||||
```
|
||||
|
||||
### Clock Display
|
||||
|
||||
```xml
|
||||
<msg><header deviceID="{device_id}" url="clockDisplay" method="POST">
|
||||
<request requestID="{n}"><info mainNode="clockDisplayBypass" type="new"/></request>
|
||||
</header><body>
|
||||
<clockDisplay>
|
||||
<clockConfig timezoneInfo="Europe/Berlin" timeFormat="TIME_FORMAT_12HOUR_ID"/>
|
||||
</clockDisplay>
|
||||
</body></msg>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Keepalive
|
||||
|
||||
The app sends a ping roughly every 30 seconds:
|
||||
|
||||
```xml
|
||||
<!-- C→S -->
|
||||
<msg><header deviceID="{device_id}" url="webserver/pingRequest" method="GET">
|
||||
<request requestID="{n}"><info type="new"/></request>
|
||||
</header></msg>
|
||||
|
||||
<!-- S→C -->
|
||||
<pingRequest pong="true"/>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Server Push Events (Unsolicited)
|
||||
|
||||
The server wraps push events in `<updates deviceID="{device_id}">`:
|
||||
|
||||
| Event element | Trigger |
|
||||
|----------------------------------|-----------------------------------------------------------------------------------------------------|
|
||||
| `nowPlayingUpdated` | Source/track changed, playback state changed |
|
||||
| `nowSelectionUpdated` | Preset slot highlighted (UI selection changed) |
|
||||
| `recentsUpdated` | Recents list changed |
|
||||
| `presetsUpdated` | Preset saved or modified |
|
||||
| `volumeUpdated` | Volume changed (any source) |
|
||||
| `bassUpdated` | Bass level changed |
|
||||
| `connectionStateUpdated` | Wi-Fi signal strength changed (`EXCELLENT_SIGNAL`, `GOOD_SIGNAL`, `MARGINAL_SIGNAL`, `POOR_SIGNAL`) |
|
||||
| `soundTouchConfigurationUpdated` | Setup state changed (e.g. `SOUNDTOUCH_CONFIGURING`) |
|
||||
| `infoUpdated` | Device info changed (e.g. after un-pairing) |
|
||||
| `sourcesUpdated` | Available sources list changed |
|
||||
|
||||
Separate push (not inside `<updates>`):
|
||||
```xml
|
||||
<userActivityUpdate deviceID="{device_id}"/>
|
||||
```
|
||||
Sent after any physical or app-initiated user action.
|
||||
|
||||
---
|
||||
|
||||
## Notification (Client → Device Push)
|
||||
|
||||
Used by the app to notify the device of data that has changed on the service side
|
||||
(e.g. after syncing presets from cloud). Header uses `propagate="false"`:
|
||||
|
||||
```xml
|
||||
<msg>
|
||||
<header deviceID="{device_id}" url="notification" method="POST" propagate="false">
|
||||
<request requestID="{n}"><info mainNode="presetsUpdated" type="new"/></request>
|
||||
</header>
|
||||
<body>
|
||||
<updates deviceID="{device_id}"><presetsUpdated/></updates>
|
||||
</body>
|
||||
</msg>
|
||||
|
||||
<!-- S→C response: -->
|
||||
<status>/notification</status>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Complete Pairing Sequence (Minimal)
|
||||
|
||||
To pair a freshly factory-reset speaker to a Bose account (soundtouch-service must be
|
||||
running and authenticated):
|
||||
|
||||
```
|
||||
1. Connect WebSocket to ws://{speakerIP}:8090/
|
||||
2. Receive: <SoundTouchSdkInfo .../>
|
||||
3. GET info → confirm margeAccountUUID is empty
|
||||
4. POST setup SETUP_START
|
||||
5. POST setup SETUP_IDENTIFY_DEVICE_ENTER (timeout=300000)
|
||||
(user physically presses button on speaker to confirm identity)
|
||||
6. POST language <sysLanguage>3</sysLanguage>
|
||||
7. POST setup SETUP_ENTER
|
||||
8. POST setup SETUP_IDENTIFY_DEVICE_LEAVE
|
||||
9. POST name <name>{desired name}</name>
|
||||
10. POST setMargeAccount <PairDeviceWithAccount>
|
||||
<accountId>{accountId}</accountId>
|
||||
<userAuthToken>Bearer {token}</userAuthToken>
|
||||
</PairDeviceWithAccount>
|
||||
→ device responds with info, margeAccountUUID is now set
|
||||
11. POST setup SETUP_LEAVE
|
||||
12. GET pushCustomerSupportInfoToMarge (telemetry, safe to skip)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Source References
|
||||
|
||||
- `bose-pairing-20260502-155542` — Session 1: initial pairing of SoundTouch 10 to account 9569497
|
||||
- `bose-pairing-20260502-165549` — Session 2: re-pairing and full operation (TuneIn, Spotify, presets)
|
||||
- Raw WebSocket files: `scripts/android/mitm/{session}/mirror/{n}-websocket/*.txt`
|
||||
- Companion HTTP upgrade files: `scripts/android/mitm/{session}/mirror/{n}-*.http`
|
||||
@@ -1,8 +1,8 @@
|
||||
module navigation-station-demo
|
||||
|
||||
go 1.26.2
|
||||
go 1.26.3
|
||||
|
||||
require github.com/gesellix/bose-soundtouch v0.57.0
|
||||
require github.com/gesellix/bose-soundtouch v0.71.2
|
||||
|
||||
require github.com/gorilla/websocket v1.5.3 // indirect
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
module preset-management-example
|
||||
|
||||
go 1.26.2
|
||||
go 1.26.3
|
||||
|
||||
require github.com/gesellix/bose-soundtouch v0.57.0
|
||||
require github.com/gesellix/bose-soundtouch v0.71.2
|
||||
|
||||
require github.com/gorilla/websocket v1.5.3 // indirect
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
module github.com/gesellix/bose-soundtouch
|
||||
|
||||
go 1.26.2
|
||||
go 1.26.3
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.2.5
|
||||
@@ -14,6 +14,7 @@ require (
|
||||
github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef
|
||||
github.com/urfave/cli/v2 v2.27.7
|
||||
golang.org/x/crypto v0.50.0
|
||||
golang.org/x/term v0.42.0
|
||||
)
|
||||
|
||||
require (
|
||||
|
||||
@@ -783,7 +783,11 @@ func (c *Client) SelectSource(source, sourceAccount string) error {
|
||||
case "BLUETOOTH":
|
||||
contentItem.ItemName = "Bluetooth"
|
||||
case "AUX":
|
||||
contentItem.ItemName = "AUX Input"
|
||||
contentItem.ItemName = "AUX IN"
|
||||
// The speaker rejects AUX with empty sourceAccount as INVALID_SOURCE.
|
||||
if contentItem.SourceAccount == "" {
|
||||
contentItem.SourceAccount = "AUX"
|
||||
}
|
||||
case "TUNEIN":
|
||||
contentItem.ItemName = "TuneIn"
|
||||
case "PANDORA":
|
||||
@@ -818,7 +822,7 @@ func (c *Client) SelectBluetooth() error {
|
||||
return c.SelectSource("BLUETOOTH", "")
|
||||
}
|
||||
|
||||
// SelectAux is a convenience method to select AUX input
|
||||
// SelectAux is a convenience method to select AUX input.
|
||||
func (c *Client) SelectAux() error {
|
||||
return c.SelectSource("AUX", "")
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ func TestClient_SelectSource(t *testing.T) {
|
||||
{
|
||||
name: "Valid AUX source",
|
||||
source: "AUX",
|
||||
sourceAccount: "",
|
||||
sourceAccount: "AUX",
|
||||
wantError: false,
|
||||
},
|
||||
{
|
||||
@@ -305,7 +305,7 @@ func TestClient_ConvenienceSourceMethods(t *testing.T) {
|
||||
method: "aux",
|
||||
sourceAccount: "",
|
||||
expectedSource: "AUX",
|
||||
expectedAccount: "",
|
||||
expectedAccount: "AUX",
|
||||
},
|
||||
{
|
||||
name: "SelectTuneIn",
|
||||
@@ -530,7 +530,7 @@ func getExpectedItemName(source string) string {
|
||||
case "BLUETOOTH":
|
||||
return "Bluetooth"
|
||||
case "AUX":
|
||||
return "AUX Input"
|
||||
return "AUX IN"
|
||||
case "TUNEIN":
|
||||
return "TuneIn"
|
||||
case "PANDORA":
|
||||
|
||||
@@ -171,6 +171,7 @@ func (d *DNSDiscovery) shouldIntercept(hostname string) bool {
|
||||
"music.api.bose.com",
|
||||
"bosecm.com",
|
||||
"bose.io",
|
||||
"downloads.bose.com",
|
||||
}
|
||||
|
||||
for _, service := range interceptList {
|
||||
|
||||
@@ -135,6 +135,22 @@ func NewSpotifyOAuthCredentials(user, code, displayName string) *OAuthCredential
|
||||
}
|
||||
}
|
||||
|
||||
// NewAmazonOAuthCredentials creates OAuth credentials for Amazon Music (cs1 / "token").
|
||||
// code is the AmazonSecret JSON envelope stored as the credential in Sources.xml.
|
||||
func NewAmazonOAuthCredentials(user, code, displayName string) *OAuthCredentials {
|
||||
if displayName == "" {
|
||||
displayName = user
|
||||
}
|
||||
|
||||
return &OAuthCredentials{
|
||||
Source: "AMAZON",
|
||||
DisplayName: displayName,
|
||||
User: user,
|
||||
Code: code,
|
||||
Version: "token",
|
||||
}
|
||||
}
|
||||
|
||||
// MusicServiceAccountResponse represents the response from account management operations
|
||||
type MusicServiceAccountResponse struct {
|
||||
XMLName xml.Name `xml:"status"`
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package models
|
||||
|
||||
import "encoding/xml"
|
||||
|
||||
// Group represents a stereo pair of two ST10 SoundTouch speakers.
|
||||
type Group struct {
|
||||
XMLName xml.Name `xml:"group"`
|
||||
ID string `xml:"id,attr,omitempty"`
|
||||
Name string `xml:"name"`
|
||||
MasterDeviceID string `xml:"masterDeviceId"`
|
||||
Roles GroupRoles `xml:"roles"`
|
||||
SenderIPAddress string `xml:"senderIPAddress,omitempty"`
|
||||
}
|
||||
|
||||
// GroupRoles contains the role assignments for devices in a group.
|
||||
type GroupRoles struct {
|
||||
Roles []GroupRole `xml:"groupRole"`
|
||||
}
|
||||
|
||||
// GroupRole describes the role (LEFT or RIGHT) of a single device in a group.
|
||||
type GroupRole struct {
|
||||
DeviceID string `xml:"deviceId"`
|
||||
Role string `xml:"role"`
|
||||
IPAddress string `xml:"ipAddress,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
// Package amazon provides Amazon Music (Login with Amazon) OAuth integration
|
||||
// and token management for the SoundTouch service.
|
||||
package amazon
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// AmazonAuthorizeURL is the Login with Amazon (LWA) authorization endpoint.
|
||||
AmazonAuthorizeURL = "https://www.amazon.com/ap/oa"
|
||||
// AmazonTokenURL is the LWA token endpoint.
|
||||
AmazonTokenURL = "https://api.amazon.com/auth/o2/token"
|
||||
// AmazonProfileURL is the LWA user profile endpoint.
|
||||
AmazonProfileURL = "https://api.amazon.com/user/profile"
|
||||
// AmazonScopes are the OAuth scopes for account linking.
|
||||
// amazon_music:access is required for music-api.amazon.com but is only available
|
||||
// to device client IDs (Amazon Music partner apps), not standard application
|
||||
// client IDs (amzn1.application-oa2-client.*). Requesting it returns a 400
|
||||
// lwa-invalid-parameter-bad-scope error from the LWA authorization endpoint.
|
||||
AmazonScopes = "profile"
|
||||
)
|
||||
|
||||
// Account represents a stored Amazon account with tokens.
|
||||
type Account struct {
|
||||
UserID string `json:"user_id"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Email string `json:"email"`
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
BoseSecret string `json:"bose_secret,omitempty"`
|
||||
// SiteID is written into the AmazonSecret credential envelope. Its origin is
|
||||
// unconfirmed (may be a static Bose partner ID or a per-user Music API value).
|
||||
SiteID string `json:"site_id,omitempty"`
|
||||
}
|
||||
|
||||
// Service manages Amazon OAuth flow and token lifecycle.
|
||||
type Service struct {
|
||||
clientID string
|
||||
clientSecret string
|
||||
redirectURI string
|
||||
dataDir string
|
||||
mu sync.RWMutex
|
||||
accounts map[string]*Account
|
||||
|
||||
// Overridable URLs for testing
|
||||
tokenURL string
|
||||
profileURL string
|
||||
}
|
||||
|
||||
// NewAmazonService creates a new Service and loads any persisted accounts.
|
||||
func NewAmazonService(clientID, clientSecret, redirectURI, dataDir string) *Service {
|
||||
return &Service{
|
||||
clientID: clientID,
|
||||
clientSecret: clientSecret,
|
||||
redirectURI: redirectURI,
|
||||
dataDir: dataDir,
|
||||
accounts: make(map[string]*Account),
|
||||
tokenURL: AmazonTokenURL,
|
||||
profileURL: AmazonProfileURL,
|
||||
}
|
||||
}
|
||||
|
||||
// Load loads persisted accounts from disk.
|
||||
func (s *Service) Load() error {
|
||||
return s.load()
|
||||
}
|
||||
|
||||
// SetEndpoints allows overriding default Amazon API endpoints (for testing).
|
||||
func (s *Service) SetEndpoints(tokenURL, profileURL string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.tokenURL = tokenURL
|
||||
s.profileURL = profileURL
|
||||
}
|
||||
|
||||
// BuildAuthorizeURL constructs the LWA OAuth authorization URL.
|
||||
func (s *Service) BuildAuthorizeURL(state string) string {
|
||||
params := url.Values{
|
||||
"client_id": {s.clientID},
|
||||
"response_type": {"code"},
|
||||
"redirect_uri": {s.redirectURI},
|
||||
"scope": {AmazonScopes},
|
||||
}
|
||||
if state != "" {
|
||||
params.Set("state", state)
|
||||
}
|
||||
|
||||
return AmazonAuthorizeURL + "?" + params.Encode()
|
||||
}
|
||||
|
||||
// ExchangeCodeAndStore exchanges an authorization code for tokens,
|
||||
// fetches the user profile, and stores the account.
|
||||
func (s *Service) ExchangeCodeAndStore(code string) error {
|
||||
tokenResp, err := s.exchangeCode(code)
|
||||
if err != nil {
|
||||
return fmt.Errorf("token exchange: %w", err)
|
||||
}
|
||||
|
||||
accessToken, _ := tokenResp["access_token"].(string)
|
||||
refreshToken, _ := tokenResp["refresh_token"].(string)
|
||||
|
||||
expiresIn, _ := tokenResp["expires_in"].(float64)
|
||||
if expiresIn == 0 {
|
||||
expiresIn = 3600
|
||||
}
|
||||
|
||||
profile, err := s.getUserProfile(accessToken)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fetch profile: %w", err)
|
||||
}
|
||||
|
||||
// LWA profile uses "user_id" and "name" (not "id" and "display_name" like Spotify).
|
||||
userID, _ := profile["user_id"].(string)
|
||||
displayName, _ := profile["name"].(string)
|
||||
email, _ := profile["email"].(string)
|
||||
|
||||
boseSecret := s.generateBoseSecret()
|
||||
|
||||
account := &Account{
|
||||
UserID: userID,
|
||||
DisplayName: displayName,
|
||||
Email: email,
|
||||
AccessToken: accessToken,
|
||||
RefreshToken: refreshToken,
|
||||
ExpiresAt: time.Now().Unix() + int64(expiresIn),
|
||||
BoseSecret: boseSecret,
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
s.accounts[userID] = account
|
||||
s.mu.Unlock()
|
||||
|
||||
if err := s.save(); err != nil {
|
||||
return fmt.Errorf("save accounts: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[Amazon] Account linked: %s (%s)", displayName, userID)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// exchangeCode exchanges an authorization code for tokens.
|
||||
// Amazon LWA requires client_id and client_secret as POST body fields,
|
||||
// not as HTTP Basic Auth (unlike Spotify).
|
||||
func (s *Service) exchangeCode(code string) (map[string]interface{}, error) {
|
||||
data := url.Values{
|
||||
"grant_type": {"authorization_code"},
|
||||
"code": {code},
|
||||
"redirect_uri": {s.redirectURI},
|
||||
"client_id": {s.clientID},
|
||||
"client_secret": {s.clientSecret},
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, s.tokenURL, strings.NewReader(data.Encode()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("token request: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("token exchange failed (%d): %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("parse response: %w", err)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Service) getUserProfile(accessToken string) (map[string]interface{}, error) {
|
||||
req, err := http.NewRequest(http.MethodGet, s.profileURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("profile request: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("profile fetch failed (%d): %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("parse profile: %w", err)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// RefreshAccessToken refreshes the access token for the given account.
|
||||
// Amazon LWA requires client credentials as POST body fields.
|
||||
func (s *Service) RefreshAccessToken(account *Account) error {
|
||||
data := url.Values{
|
||||
"grant_type": {"refresh_token"},
|
||||
"refresh_token": {account.RefreshToken},
|
||||
"client_id": {s.clientID},
|
||||
"client_secret": {s.clientSecret},
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, s.tokenURL, strings.NewReader(data.Encode()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("refresh request: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("token refresh failed (%d): %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return fmt.Errorf("parse response: %w", err)
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
account.AccessToken, _ = result["access_token"].(string)
|
||||
|
||||
expiresIn, _ := result["expires_in"].(float64)
|
||||
if expiresIn == 0 {
|
||||
expiresIn = 3600
|
||||
}
|
||||
|
||||
account.ExpiresAt = time.Now().Unix() + int64(expiresIn)
|
||||
if newRefresh, ok := result["refresh_token"].(string); ok && newRefresh != "" {
|
||||
account.RefreshToken = newRefresh
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
if err := s.save(); err != nil {
|
||||
return fmt.Errorf("save accounts: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetFreshToken returns a valid access token and username, refreshing if needed.
|
||||
func (s *Service) GetFreshToken() (accessToken, username string, err error) {
|
||||
s.mu.RLock()
|
||||
|
||||
if len(s.accounts) == 0 {
|
||||
s.mu.RUnlock()
|
||||
return "", "", fmt.Errorf("no Amazon accounts linked")
|
||||
}
|
||||
|
||||
var account *Account
|
||||
for _, a := range s.accounts {
|
||||
account = a
|
||||
break
|
||||
}
|
||||
|
||||
s.mu.RUnlock()
|
||||
|
||||
// Check if token needs refresh (expired or within 60s of expiry)
|
||||
if account.ExpiresAt < time.Now().Unix()+60 {
|
||||
if err := s.RefreshAccessToken(account); err != nil {
|
||||
return "", "", fmt.Errorf("refresh token: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
return account.AccessToken, account.UserID, nil
|
||||
}
|
||||
|
||||
// GetAccounts returns a copy of all accounts with tokens stripped for API responses.
|
||||
func (s *Service) GetAccounts() []Account {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
result := make([]Account, 0, len(s.accounts))
|
||||
for _, a := range s.accounts {
|
||||
result = append(result, Account{
|
||||
UserID: a.UserID,
|
||||
DisplayName: a.DisplayName,
|
||||
Email: a.Email,
|
||||
ExpiresAt: a.ExpiresAt,
|
||||
BoseSecret: a.BoseSecret,
|
||||
// AccessToken and RefreshToken deliberately omitted
|
||||
})
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// GetAccountBySecret retrieves an Amazon account by its Bose surrogate secret.
|
||||
func (s *Service) GetAccountBySecret(secret string) (*Account, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
for _, a := range s.accounts {
|
||||
if a.BoseSecret == secret {
|
||||
return a, true
|
||||
}
|
||||
}
|
||||
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// GetAllAccounts returns all accounts including tokens. Used internally by
|
||||
// bridgeAmazonToMarge to build the AmazonSecret credential envelope.
|
||||
func (s *Service) GetAllAccounts() []*Account {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
result := make([]*Account, 0, len(s.accounts))
|
||||
for _, a := range s.accounts {
|
||||
result = append(result, a)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// GetAccountByRefreshToken retrieves an Amazon account by its current refresh token.
|
||||
// Used by the token handler because the speaker sends back the actual LWA refresh token
|
||||
// (extracted from the AmazonSecret JSON in Sources.xml), not a surrogate.
|
||||
func (s *Service) GetAccountByRefreshToken(refreshToken string) (*Account, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
for _, a := range s.accounts {
|
||||
if a.RefreshToken == refreshToken {
|
||||
return a, true
|
||||
}
|
||||
}
|
||||
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func (s *Service) generateBoseSecret() string {
|
||||
prefix := "ba-"
|
||||
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return fmt.Sprintf("%s%d", prefix, time.Now().UnixNano())
|
||||
}
|
||||
|
||||
return prefix + hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// save persists accounts to disk as JSON.
|
||||
func (s *Service) save() error {
|
||||
s.mu.RLock()
|
||||
|
||||
data := make(map[string]*Account, len(s.accounts))
|
||||
for k, v := range s.accounts {
|
||||
data[k] = v
|
||||
}
|
||||
|
||||
s.mu.RUnlock()
|
||||
|
||||
dir := filepath.Join(s.dataDir, "amazon")
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return fmt.Errorf("create directory: %w", err)
|
||||
}
|
||||
|
||||
jsonData, err := json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal accounts: %w", err)
|
||||
}
|
||||
|
||||
path := filepath.Join(dir, "accounts.json")
|
||||
if err := os.WriteFile(path, jsonData, 0600); err != nil {
|
||||
return fmt.Errorf("write file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// load reads persisted accounts from disk.
|
||||
func (s *Service) load() error {
|
||||
path := filepath.Join(s.dataDir, "amazon", "accounts.json")
|
||||
|
||||
jsonData, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil // No accounts file yet, not an error
|
||||
}
|
||||
|
||||
return fmt.Errorf("read file: %w", err)
|
||||
}
|
||||
|
||||
var accounts map[string]*Account
|
||||
if err := json.Unmarshal(jsonData, &accounts); err != nil {
|
||||
return fmt.Errorf("unmarshal accounts: %w", err)
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
s.accounts = accounts
|
||||
s.mu.Unlock()
|
||||
|
||||
log.Printf("[Amazon] Loaded %d account(s)", len(accounts))
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
package amazon
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestBuildAuthorizeURL(t *testing.T) {
|
||||
svc := NewAmazonService("test-client-id", "test-secret", "ueberboese-login://amazon", t.TempDir())
|
||||
|
||||
state := "test-state"
|
||||
gotURL := svc.BuildAuthorizeURL(state)
|
||||
|
||||
if !strings.Contains(gotURL, "client_id=test-client-id") {
|
||||
t.Errorf("URL should contain client_id, got: %s", gotURL)
|
||||
}
|
||||
if !strings.Contains(gotURL, "redirect_uri=") {
|
||||
t.Errorf("URL should contain redirect_uri, got: %s", gotURL)
|
||||
}
|
||||
if !strings.Contains(gotURL, "scope=") {
|
||||
t.Errorf("URL should contain scope, got: %s", gotURL)
|
||||
}
|
||||
if !strings.Contains(gotURL, "response_type=code") {
|
||||
t.Errorf("URL should contain response_type=code, got: %s", gotURL)
|
||||
}
|
||||
if !strings.Contains(gotURL, "state=test-state") {
|
||||
t.Errorf("URL should contain state=test-state, got: %s", gotURL)
|
||||
}
|
||||
if !strings.HasPrefix(gotURL, AmazonAuthorizeURL) {
|
||||
t.Errorf("URL should start with %s, got: %s", AmazonAuthorizeURL, gotURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAccountsStripsTokens(t *testing.T) {
|
||||
svc := NewAmazonService("cid", "csecret", "ueberboese-login://amazon", t.TempDir())
|
||||
|
||||
svc.mu.Lock()
|
||||
svc.accounts["amzn1.account.EXAMPLE"] = &Account{
|
||||
UserID: "amzn1.account.EXAMPLE",
|
||||
DisplayName: "Test User",
|
||||
Email: "test@example.com",
|
||||
AccessToken: "secret-access-token",
|
||||
RefreshToken: "secret-refresh-token",
|
||||
ExpiresAt: time.Now().Add(1 * time.Hour).Unix(),
|
||||
}
|
||||
svc.mu.Unlock()
|
||||
|
||||
accounts := svc.GetAccounts()
|
||||
|
||||
if len(accounts) != 1 {
|
||||
t.Fatalf("expected 1 account, got %d", len(accounts))
|
||||
}
|
||||
|
||||
if accounts[0].AccessToken != "" {
|
||||
t.Errorf("AccessToken should be stripped, got: %s", accounts[0].AccessToken)
|
||||
}
|
||||
if accounts[0].RefreshToken != "" {
|
||||
t.Errorf("RefreshToken should be stripped, got: %s", accounts[0].RefreshToken)
|
||||
}
|
||||
if accounts[0].UserID != "amzn1.account.EXAMPLE" {
|
||||
t.Errorf("UserID should be preserved, got: %s", accounts[0].UserID)
|
||||
}
|
||||
if accounts[0].DisplayName != "Test User" {
|
||||
t.Errorf("DisplayName should be preserved, got: %s", accounts[0].DisplayName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExchangeCodeAndStore(t *testing.T) {
|
||||
// Mock token endpoint — Amazon uses POST body credentials, not Basic Auth.
|
||||
tokenServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
switch r.Form.Get("grant_type") {
|
||||
case "authorization_code":
|
||||
if r.Form.Get("code") != "test-auth-code" {
|
||||
t.Errorf("expected code=test-auth-code, got %s", r.Form.Get("code"))
|
||||
}
|
||||
|
||||
// Amazon uses POST body credentials, not HTTP Basic Auth.
|
||||
if r.Form.Get("client_id") != "cid" {
|
||||
t.Errorf("expected client_id=cid in POST body, got %q", r.Form.Get("client_id"))
|
||||
}
|
||||
if r.Form.Get("client_secret") != "csecret" {
|
||||
t.Errorf("expected client_secret=csecret in POST body, got %q", r.Form.Get("client_secret"))
|
||||
}
|
||||
_, _, hasBasicAuth := r.BasicAuth()
|
||||
if hasBasicAuth {
|
||||
t.Error("Amazon token endpoint must NOT use HTTP Basic Auth")
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"access_token": "new-at",
|
||||
"refresh_token": "new-rt",
|
||||
"expires_in": 3600,
|
||||
})
|
||||
default:
|
||||
t.Errorf("unexpected grant_type: %s", r.Form.Get("grant_type"))
|
||||
http.Error(w, "bad request", 400)
|
||||
}
|
||||
}))
|
||||
defer tokenServer.Close()
|
||||
|
||||
// Mock profile endpoint — LWA returns "user_id" and "name" (not "id" / "display_name").
|
||||
profileServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
auth := r.Header.Get("Authorization")
|
||||
if auth != "Bearer new-at" {
|
||||
t.Errorf("expected Bearer new-at, got %s", auth)
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"user_id": "amzn1.account.TESTUSER123",
|
||||
"name": "Amazon User",
|
||||
"email": "user@amazon.com",
|
||||
})
|
||||
}))
|
||||
defer profileServer.Close()
|
||||
|
||||
dir := t.TempDir()
|
||||
svc := NewAmazonService("cid", "csecret", "ueberboese-login://amazon", dir)
|
||||
svc.SetEndpoints(tokenServer.URL, profileServer.URL)
|
||||
|
||||
err := svc.ExchangeCodeAndStore("test-auth-code")
|
||||
if err != nil {
|
||||
t.Fatalf("ExchangeCodeAndStore failed: %v", err)
|
||||
}
|
||||
|
||||
svc.mu.RLock()
|
||||
account, ok := svc.accounts["amzn1.account.TESTUSER123"]
|
||||
svc.mu.RUnlock()
|
||||
|
||||
if !ok {
|
||||
t.Fatal("account not found after exchange")
|
||||
}
|
||||
if account.DisplayName != "Amazon User" {
|
||||
t.Errorf("expected Amazon User, got %s", account.DisplayName)
|
||||
}
|
||||
if account.Email != "user@amazon.com" {
|
||||
t.Errorf("expected user@amazon.com, got %s", account.Email)
|
||||
}
|
||||
if account.AccessToken != "new-at" {
|
||||
t.Errorf("expected new-at, got %s", account.AccessToken)
|
||||
}
|
||||
if account.RefreshToken != "new-rt" {
|
||||
t.Errorf("expected new-rt, got %s", account.RefreshToken)
|
||||
}
|
||||
|
||||
// Verify saved to disk under amazon/ (not spotify/).
|
||||
accountsFile := filepath.Join(dir, "amazon", "accounts.json")
|
||||
data, err := os.ReadFile(accountsFile)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read accounts file: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(data), "amzn1.account.TESTUSER123") {
|
||||
t.Error("accounts file should contain the user ID")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshAccessToken(t *testing.T) {
|
||||
tokenServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
t.Errorf("expected POST, got %s", r.Method)
|
||||
}
|
||||
if err := r.ParseForm(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Form.Get("grant_type") != "refresh_token" {
|
||||
t.Errorf("expected grant_type=refresh_token, got %s", r.Form.Get("grant_type"))
|
||||
}
|
||||
if r.Form.Get("refresh_token") != "my-refresh-token" {
|
||||
t.Errorf("expected refresh_token=my-refresh-token, got %s", r.Form.Get("refresh_token"))
|
||||
}
|
||||
|
||||
// Amazon uses POST body credentials.
|
||||
if r.Form.Get("client_id") != "cid" {
|
||||
t.Errorf("expected client_id=cid in POST body, got %q", r.Form.Get("client_id"))
|
||||
}
|
||||
if r.Form.Get("client_secret") != "csecret" {
|
||||
t.Errorf("expected client_secret=csecret in POST body, got %q", r.Form.Get("client_secret"))
|
||||
}
|
||||
_, _, hasBasicAuth := r.BasicAuth()
|
||||
if hasBasicAuth {
|
||||
t.Error("Amazon token endpoint must NOT use HTTP Basic Auth")
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"access_token": "new-access-token",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
"refresh_token": "new-refresh-token",
|
||||
})
|
||||
}))
|
||||
defer tokenServer.Close()
|
||||
|
||||
svc := NewAmazonService("cid", "csecret", "ueberboese-login://amazon", t.TempDir())
|
||||
svc.tokenURL = tokenServer.URL
|
||||
|
||||
account := &Account{
|
||||
UserID: "amzn1.account.USER",
|
||||
AccessToken: "old-expired-token",
|
||||
RefreshToken: "my-refresh-token",
|
||||
ExpiresAt: time.Now().Add(-1 * time.Hour).Unix(),
|
||||
}
|
||||
|
||||
svc.mu.Lock()
|
||||
svc.accounts[account.UserID] = account
|
||||
svc.mu.Unlock()
|
||||
|
||||
if err := svc.RefreshAccessToken(account); err != nil {
|
||||
t.Fatalf("RefreshAccessToken: %v", err)
|
||||
}
|
||||
|
||||
if account.AccessToken != "new-access-token" {
|
||||
t.Errorf("expected new-access-token, got %s", account.AccessToken)
|
||||
}
|
||||
if account.RefreshToken != "new-refresh-token" {
|
||||
t.Errorf("expected new-refresh-token, got %s", account.RefreshToken)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetFreshTokenRefreshesExpired(t *testing.T) {
|
||||
tokenServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"access_token": "new-access-token",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
"refresh_token": "new-refresh-token",
|
||||
})
|
||||
}))
|
||||
defer tokenServer.Close()
|
||||
|
||||
svc := NewAmazonService("cid", "csecret", "ueberboese-login://amazon", t.TempDir())
|
||||
svc.tokenURL = tokenServer.URL
|
||||
|
||||
svc.mu.Lock()
|
||||
svc.accounts["amzn1.account.USER"] = &Account{
|
||||
UserID: "amzn1.account.USER",
|
||||
AccessToken: "old-expired-token",
|
||||
RefreshToken: "my-refresh-token",
|
||||
ExpiresAt: time.Now().Add(-1 * time.Hour).Unix(),
|
||||
}
|
||||
svc.mu.Unlock()
|
||||
|
||||
accessToken, username, err := svc.GetFreshToken()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if accessToken != "new-access-token" {
|
||||
t.Errorf("expected new-access-token, got %s", accessToken)
|
||||
}
|
||||
if username != "amzn1.account.USER" {
|
||||
t.Errorf("expected amzn1.account.USER, got %s", username)
|
||||
}
|
||||
|
||||
svc.mu.RLock()
|
||||
account := svc.accounts["amzn1.account.USER"]
|
||||
svc.mu.RUnlock()
|
||||
|
||||
if account.RefreshToken != "new-refresh-token" {
|
||||
t.Errorf("refresh token should be updated, got %s", account.RefreshToken)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetFreshTokenNoAccounts(t *testing.T) {
|
||||
svc := NewAmazonService("cid", "csecret", "ueberboese-login://amazon", t.TempDir())
|
||||
|
||||
_, _, err := svc.GetFreshToken()
|
||||
if err == nil {
|
||||
t.Error("expected error when no accounts exist")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetFreshTokenNotExpired(t *testing.T) {
|
||||
svc := NewAmazonService("cid", "csecret", "ueberboese-login://amazon", t.TempDir())
|
||||
|
||||
svc.mu.Lock()
|
||||
svc.accounts["amzn1.account.USER"] = &Account{
|
||||
UserID: "amzn1.account.USER",
|
||||
AccessToken: "valid-token",
|
||||
RefreshToken: "rt",
|
||||
ExpiresAt: time.Now().Add(1 * time.Hour).Unix(),
|
||||
}
|
||||
svc.mu.Unlock()
|
||||
|
||||
token, username, err := svc.GetFreshToken()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if token != "valid-token" {
|
||||
t.Errorf("expected valid-token, got %s", token)
|
||||
}
|
||||
if username != "amzn1.account.USER" {
|
||||
t.Errorf("expected amzn1.account.USER, got %s", username)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveAndLoad(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
|
||||
svc := NewAmazonService("cid", "csecret", "ueberboese-login://amazon", dir)
|
||||
svc.mu.Lock()
|
||||
svc.accounts["amzn1.account.USER1"] = &Account{
|
||||
UserID: "amzn1.account.USER1",
|
||||
DisplayName: "Test User",
|
||||
Email: "test@example.com",
|
||||
AccessToken: "at",
|
||||
RefreshToken: "rt",
|
||||
ExpiresAt: 1234567890,
|
||||
}
|
||||
svc.accounts["amzn1.account.USER2"] = &Account{
|
||||
UserID: "amzn1.account.USER2",
|
||||
DisplayName: "User Two",
|
||||
Email: "two@example.com",
|
||||
AccessToken: "at2",
|
||||
RefreshToken: "rt2",
|
||||
ExpiresAt: 9876543210,
|
||||
}
|
||||
svc.mu.Unlock()
|
||||
|
||||
if err := svc.save(); err != nil {
|
||||
t.Fatalf("save failed: %v", err)
|
||||
}
|
||||
|
||||
accountsFile := filepath.Join(dir, "amazon", "accounts.json")
|
||||
if _, err := os.Stat(accountsFile); os.IsNotExist(err) {
|
||||
t.Fatal("amazon/accounts.json was not created")
|
||||
}
|
||||
|
||||
svc2 := NewAmazonService("cid", "csecret", "ueberboese-login://amazon", dir)
|
||||
if err := svc2.Load(); err != nil {
|
||||
t.Fatalf("load failed: %v", err)
|
||||
}
|
||||
|
||||
svc2.mu.RLock()
|
||||
defer svc2.mu.RUnlock()
|
||||
|
||||
if len(svc2.accounts) != 2 {
|
||||
t.Fatalf("expected 2 accounts after load, got %d", len(svc2.accounts))
|
||||
}
|
||||
|
||||
u1, ok := svc2.accounts["amzn1.account.USER1"]
|
||||
if !ok {
|
||||
t.Fatal("USER1 not found after load")
|
||||
}
|
||||
if u1.DisplayName != "Test User" {
|
||||
t.Errorf("expected Test User, got %s", u1.DisplayName)
|
||||
}
|
||||
if u1.AccessToken != "at" {
|
||||
t.Errorf("expected at, got %s", u1.AccessToken)
|
||||
}
|
||||
if u1.ExpiresAt != 1234567890 {
|
||||
t.Errorf("expected ExpiresAt 1234567890, got %d", u1.ExpiresAt)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package amazon
|
||||
|
||||
import "github.com/gesellix/bose-soundtouch/pkg/service/zeroconf"
|
||||
|
||||
// PushAmazonCredentials pushes Amazon Music credentials to a speaker using the
|
||||
// ZeroConf DH key exchange protocol. Falls back to simplified token push if
|
||||
// the speaker does not support DH (older firmware).
|
||||
// zcBaseURL is the base URL of the ZeroConf endpoint, e.g. "http://192.168.1.10:8200/zc".
|
||||
func PushAmazonCredentials(zcBaseURL, username, accessToken string) error {
|
||||
return zeroconf.PushCredentials(zcBaseURL, username, accessToken)
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package amazon
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/zeroconf"
|
||||
)
|
||||
|
||||
func TestPushAmazonCredentials_FullRoundTrip(t *testing.T) {
|
||||
speakerPrivate, speakerPublicBytes, err := zeroconf.GenerateDHKeyPair()
|
||||
if err != nil {
|
||||
t.Fatalf("speaker keygen: %v", err)
|
||||
}
|
||||
|
||||
type received struct {
|
||||
username string
|
||||
authData string
|
||||
authType int
|
||||
}
|
||||
var got received
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Query().Get("action") {
|
||||
case "getInfo":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"status": 101,
|
||||
"statusString": "OK",
|
||||
"publicKey": base64.StdEncoding.EncodeToString(speakerPublicBytes),
|
||||
})
|
||||
|
||||
case "addUser":
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
blobBytes, err := base64.StdEncoding.DecodeString(r.FormValue("blob"))
|
||||
if err != nil {
|
||||
http.Error(w, "bad blob base64: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
clientKeyBytes, err := base64.StdEncoding.DecodeString(r.FormValue("clientKey"))
|
||||
if err != nil {
|
||||
http.Error(w, "bad clientKey base64: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
shared := zeroconf.ComputeSharedSecret(speakerPrivate, clientKeyBytes)
|
||||
encKey, macKey := zeroconf.DeriveKeys(shared)
|
||||
|
||||
plaintext, err := zeroconf.DecryptBlob(encKey, macKey, blobBytes)
|
||||
if err != nil {
|
||||
http.Error(w, "decrypt failed: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Minimal protobuf parse: field 1 = username, field 4 = authData, field 5 = authType
|
||||
i := 0
|
||||
for i < len(plaintext) {
|
||||
tag := plaintext[i]
|
||||
i++
|
||||
fieldNum := tag >> 3
|
||||
wireType := tag & 0x07
|
||||
switch wireType {
|
||||
case 0:
|
||||
val, n := readVarint(plaintext[i:])
|
||||
i += n
|
||||
if fieldNum == 5 {
|
||||
got.authType = int(val)
|
||||
}
|
||||
case 2:
|
||||
length, n := readVarint(plaintext[i:])
|
||||
i += n
|
||||
value := plaintext[i : i+int(length)]
|
||||
i += int(length)
|
||||
switch fieldNum {
|
||||
case 1:
|
||||
got.username = string(value)
|
||||
case 4:
|
||||
got.authData = string(value)
|
||||
}
|
||||
default:
|
||||
http.Error(w, "unexpected wire type", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
const wantUsername = "amazonuser@example.com"
|
||||
const wantToken = "Atza|access-token"
|
||||
|
||||
if err := PushAmazonCredentials(srv.URL+"/zc", wantUsername, wantToken); err != nil {
|
||||
t.Fatalf("PushAmazonCredentials: %v", err)
|
||||
}
|
||||
|
||||
if got.username != wantUsername {
|
||||
t.Errorf("username = %q, want %q", got.username, wantUsername)
|
||||
}
|
||||
if got.authData != wantToken {
|
||||
t.Errorf("authData = %q, want %q", got.authData, wantToken)
|
||||
}
|
||||
if uint64(got.authType) != zeroconf.AuthTypeOAuthToken {
|
||||
t.Errorf("authType = %d, want %d (AuthTypeOAuthToken)", got.authType, zeroconf.AuthTypeOAuthToken)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPushAmazonCredentials_FallbackOnGetInfoFailure(t *testing.T) {
|
||||
var receivedForm map[string]string
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Query().Get("action") {
|
||||
case "getInfo":
|
||||
http.Error(w, "not supported", http.StatusNotFound)
|
||||
case "addUser":
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
receivedForm = map[string]string{
|
||||
"userName": r.FormValue("userName"),
|
||||
"blob": r.FormValue("blob"),
|
||||
"clientKey": r.FormValue("clientKey"),
|
||||
"tokenType": r.FormValue("tokenType"),
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
const wantUsername = "amazonuser@example.com"
|
||||
const wantToken = "Atza|raw-access-token"
|
||||
|
||||
if err := PushAmazonCredentials(srv.URL+"/zc", wantUsername, wantToken); err != nil {
|
||||
t.Fatalf("PushAmazonCredentials: %v", err)
|
||||
}
|
||||
|
||||
if receivedForm == nil {
|
||||
t.Fatal("addUser was never called")
|
||||
}
|
||||
if receivedForm["userName"] != wantUsername {
|
||||
t.Errorf("userName = %q, want %q", receivedForm["userName"], wantUsername)
|
||||
}
|
||||
if receivedForm["blob"] != wantToken {
|
||||
t.Errorf("blob = %q, want raw token %q", receivedForm["blob"], wantToken)
|
||||
}
|
||||
if receivedForm["tokenType"] != "accesstoken" {
|
||||
t.Errorf("tokenType = %q, want %q", receivedForm["tokenType"], "accesstoken")
|
||||
}
|
||||
if receivedForm["clientKey"] != "" {
|
||||
t.Errorf("clientKey = %q, want empty for simplified fallback", receivedForm["clientKey"])
|
||||
}
|
||||
}
|
||||
|
||||
func readVarint(data []byte) (uint64, int) {
|
||||
var val uint64
|
||||
for i, b := range data {
|
||||
val |= uint64(b&0x7f) << (7 * uint(i))
|
||||
if b&0x80 == 0 {
|
||||
return val, i + 1
|
||||
}
|
||||
}
|
||||
return 0, len(data)
|
||||
}
|
||||
@@ -42,6 +42,41 @@ func isTuneInURL(rawURL string) bool {
|
||||
return allowedTuneInHosts[u.Hostname()]
|
||||
}
|
||||
|
||||
// isTuneInOpmlURI returns true when the URL's host is opml.radiotime.com,
|
||||
// used to select the OPML/ashx parser over the JSON API parser.
|
||||
func isTuneInOpmlURI(rawURL string) bool {
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return strings.EqualFold(u.Hostname(), "opml.radiotime.com")
|
||||
}
|
||||
|
||||
// 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 {
|
||||
if rawURL == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return rawURL
|
||||
}
|
||||
|
||||
q := u.Query()
|
||||
q.Set("render", "json")
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// tuneInSearchURI returns the TuneIn search API URL with the query properly URL-encoded.
|
||||
func tuneInSearchURI(query string) string {
|
||||
return TuneInSearchAPI + url.QueryEscape(query)
|
||||
}
|
||||
|
||||
func fetchJSON(fetchURL string) (map[string]interface{}, error) {
|
||||
if !isTuneInURL(fetchURL) {
|
||||
return nil, fmt.Errorf("URL not in allowed list: %s", fetchURL)
|
||||
@@ -110,7 +145,7 @@ func TuneInNavigate(encodedURI string, subsection *int) (*models.BmxNavResponse,
|
||||
err error
|
||||
)
|
||||
|
||||
if strings.HasPrefix(tuneInURI, "http://opml.radiotime.com/") {
|
||||
if isTuneInOpmlURI(tuneInURI) {
|
||||
sections, err = tuneInSectionsAshx(tuneInURI, subsection)
|
||||
} else {
|
||||
sections, err = tuneInSectionsJSONAPI(tuneInURI, subsection)
|
||||
@@ -291,7 +326,7 @@ func tuneInNavigateLink(item map[string]interface{}) models.BmxNavItem {
|
||||
text, _ := item["text"].(string)
|
||||
subtext, _ := item["subtext"].(string)
|
||||
|
||||
encURL := base64.URLEncoding.EncodeToString([]byte(rawURL + "&render=json"))
|
||||
encURL := base64.URLEncoding.EncodeToString([]byte(tuneInRenderJSONURI(rawURL)))
|
||||
|
||||
return models.BmxNavItem{
|
||||
Links: &models.Links{BmxNavigate: &models.Link{Href: fmt.Sprintf("/v1/navigate/%s", encURL)}},
|
||||
@@ -303,7 +338,7 @@ func tuneInNavigateLink(item map[string]interface{}) models.BmxNavItem {
|
||||
|
||||
// TuneInSearch returns live search results from TuneIn for the given query.
|
||||
func TuneInSearch(query string) (*models.BmxNavResponse, error) {
|
||||
tuneInURI := TuneInSearchAPI + url.QueryEscape(query)
|
||||
tuneInURI := tuneInSearchURI(query)
|
||||
|
||||
templated := true
|
||||
bmxSearchLink := &models.Link{
|
||||
@@ -336,7 +371,7 @@ func TuneInSearch(query string) (*models.BmxNavResponse, error) {
|
||||
|
||||
return &models.BmxNavResponse{
|
||||
Links: &models.Links{
|
||||
Self: &models.Link{Href: fmt.Sprintf("/v1/search?q=%s", query)},
|
||||
Self: &models.Link{Href: fmt.Sprintf("/v1/search?q=%s", url.QueryEscape(query))},
|
||||
BmxSearch: bmxSearchLink,
|
||||
},
|
||||
BmxSections: sections,
|
||||
@@ -353,7 +388,7 @@ func tuneInSearchSection(item map[string]interface{}, idx int, query, layout str
|
||||
if pivotURL != "" {
|
||||
href = fmt.Sprintf("/v1/navigate/%s", base64.URLEncoding.EncodeToString([]byte(pivotURL)))
|
||||
} else {
|
||||
encodedQuery := base64.URLEncoding.EncodeToString([]byte(TuneInSearchAPI + query))
|
||||
encodedQuery := base64.URLEncoding.EncodeToString([]byte(tuneInSearchURI(query)))
|
||||
href = fmt.Sprintf("/v1/navigate/sub/%d/%s", idx, encodedQuery)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,155 @@ package bmx
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTuneInRenderJSONURI(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "empty URL returns empty",
|
||||
input: "",
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "URL with no query params gets render=json added",
|
||||
input: "http://opml.radiotime.com/Browse.ashx",
|
||||
want: "http://opml.radiotime.com/Browse.ashx?render=json",
|
||||
},
|
||||
{
|
||||
name: "URL with other params gets render=json appended",
|
||||
input: "http://opml.radiotime.com/Browse.ashx?c=news",
|
||||
want: "http://opml.radiotime.com/Browse.ashx?c=news&render=json",
|
||||
},
|
||||
{
|
||||
name: "URL already containing render=json is not duplicated",
|
||||
input: "http://opml.radiotime.com/?render=json",
|
||||
want: "http://opml.radiotime.com/?render=json",
|
||||
},
|
||||
{
|
||||
name: "URL with render=xml gets render replaced with json",
|
||||
input: "http://opml.radiotime.com/Browse.ashx?c=podcast&render=xml",
|
||||
want: "http://opml.radiotime.com/Browse.ashx?c=podcast&render=json",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := tuneInRenderJSONURI(tt.input)
|
||||
if got != tt.want {
|
||||
t.Errorf("tuneInRenderJSONURI(%q) = %q, want %q", tt.input, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsTuneInOpmlURI(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
want bool
|
||||
}{
|
||||
{"http://opml.radiotime.com/Browse.ashx", true},
|
||||
{"https://opml.radiotime.com/Browse.ashx", true},
|
||||
{"http://opml.radiotime.com/?render=json", true},
|
||||
{"http://api.radiotime.com/profiles?fulltextsearch=true", false},
|
||||
{"http://example.com", false},
|
||||
{"not-a-url", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.input, func(t *testing.T) {
|
||||
got := isTuneInOpmlURI(tt.input)
|
||||
if got != tt.want {
|
||||
t.Errorf("isTuneInOpmlURI(%q) = %v, want %v", tt.input, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTuneInSearchURI(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
query string
|
||||
check func(string) bool
|
||||
}{
|
||||
{
|
||||
name: "spaces are percent-encoded",
|
||||
query: "radio paradise",
|
||||
check: func(u string) bool { return !strings.Contains(u, " ") && strings.Contains(u, "radio+paradise") },
|
||||
},
|
||||
{
|
||||
name: "ampersand is encoded",
|
||||
query: "news & talk",
|
||||
check: func(u string) bool { return !strings.Contains(u, " ") && strings.Contains(u, "%26") },
|
||||
},
|
||||
{
|
||||
name: "plain query is appended to base URL",
|
||||
query: "jazz",
|
||||
check: func(u string) bool { return u == TuneInSearchAPI+"jazz" },
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := tuneInSearchURI(tt.query)
|
||||
if !tt.check(got) {
|
||||
t.Errorf("tuneInSearchURI(%q) = %q: check failed", tt.query, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTuneInNavigateLinkEncodesRenderJSON(t *testing.T) {
|
||||
item := map[string]interface{}{
|
||||
"URL": "http://opml.radiotime.com/Browse.ashx?c=news",
|
||||
"text": "News",
|
||||
"subtext": "Latest",
|
||||
"image": "http://example.com/news.png",
|
||||
}
|
||||
|
||||
result := tuneInNavigateLink(item)
|
||||
|
||||
href := result.Links.BmxNavigate.Href
|
||||
encoded := strings.TrimPrefix(href, "/v1/navigate/")
|
||||
decoded, err := base64.URLEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to decode navigate href: %v", err)
|
||||
}
|
||||
|
||||
got := string(decoded)
|
||||
if !strings.Contains(got, "render=json") {
|
||||
t.Errorf("navigate href %q missing render=json", got)
|
||||
}
|
||||
if strings.Count(got, "render=json") > 1 {
|
||||
t.Errorf("navigate href %q has duplicate render=json", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTuneInNavigateLinkNoDuplicateRenderJSON(t *testing.T) {
|
||||
item := map[string]interface{}{
|
||||
"URL": "http://opml.radiotime.com/Browse.ashx?c=podcast&render=json",
|
||||
}
|
||||
|
||||
result := tuneInNavigateLink(item)
|
||||
|
||||
href := result.Links.BmxNavigate.Href
|
||||
encoded := strings.TrimPrefix(href, "/v1/navigate/")
|
||||
decoded, err := base64.URLEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to decode navigate href: %v", err)
|
||||
}
|
||||
|
||||
got := string(decoded)
|
||||
if strings.Count(got, "render=json") != 1 {
|
||||
t.Errorf("navigate href %q should contain render=json exactly once", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlayCustomStream(t *testing.T) {
|
||||
// Simple test for custom stream XML generation
|
||||
dataObj := struct {
|
||||
|
||||
@@ -17,7 +17,8 @@ import (
|
||||
|
||||
// CertificateManager handles CA and certificate generation.
|
||||
type CertificateManager struct {
|
||||
CertsDir string
|
||||
CertsDir string
|
||||
CommonName string // CN for generated server certs; defaults to "localhost" if empty
|
||||
}
|
||||
|
||||
// NewCertificateManager creates a new CertificateManager.
|
||||
@@ -137,7 +138,7 @@ func (cm *CertificateManager) GetServerTLSConfig(domains []string) (*tls.Config,
|
||||
|
||||
// GenerateCA generates a new CA certificate and key.
|
||||
func (cm *CertificateManager) GenerateCA() error {
|
||||
priv, err := rsa.GenerateKey(rand.Reader, 4096)
|
||||
priv, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -255,11 +256,16 @@ func (cm *CertificateManager) GenerateCertificate(domains []string) ([]byte, []b
|
||||
}
|
||||
}
|
||||
|
||||
cn := cm.CommonName
|
||||
if cn == "" {
|
||||
cn = "localhost"
|
||||
}
|
||||
|
||||
template := x509.Certificate{
|
||||
SerialNumber: serialNumber,
|
||||
Subject: pkix.Name{
|
||||
Organization: []string{"AfterTouch"},
|
||||
CommonName: domains[0],
|
||||
CommonName: cn,
|
||||
},
|
||||
NotBefore: notBefore,
|
||||
NotAfter: notAfter,
|
||||
|
||||
@@ -16,6 +16,7 @@ func TestCertificateManager(t *testing.T) {
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
cm := NewCertificateManager(filepath.Join(tempDir, "certs"))
|
||||
cm.CommonName = "test.local"
|
||||
|
||||
// Test CA generation
|
||||
if err := cm.EnsureCA(); err != nil {
|
||||
@@ -67,8 +68,8 @@ func TestCertificateManager(t *testing.T) {
|
||||
t.Fatalf("Failed to parse certificate: %v", err)
|
||||
}
|
||||
|
||||
if cert.Subject.CommonName != domains[0] {
|
||||
t.Errorf("Expected CommonName %s, got %s", domains[0], cert.Subject.CommonName)
|
||||
if cert.Subject.CommonName != cm.CommonName {
|
||||
t.Errorf("Expected CommonName %s, got %s", cm.CommonName, cert.Subject.CommonName)
|
||||
}
|
||||
|
||||
// Check DNS names
|
||||
|
||||
@@ -8,8 +8,10 @@ import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
@@ -22,6 +24,9 @@ import (
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/constants"
|
||||
)
|
||||
|
||||
// ErrGroupNotFound is returned when no group is found for a given device.
|
||||
var ErrGroupNotFound = errors.New("group not found")
|
||||
|
||||
func exists(path string) bool {
|
||||
_, err := os.Stat(path)
|
||||
return err == nil
|
||||
@@ -1642,34 +1647,32 @@ func (ds *DataStore) GetETagForRecents(account, device string) int64 {
|
||||
return info.ModTime().UnixNano() / int64(time.Millisecond)
|
||||
}
|
||||
|
||||
// contentHashForFiles returns a SHA-256 hex digest over the concatenated contents of the given file paths.
|
||||
func contentHashForFiles(paths ...string) string {
|
||||
h := sha256.New()
|
||||
|
||||
for _, p := range paths {
|
||||
f, err := os.Open(p)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
_, _ = io.Copy(h, f)
|
||||
_ = f.Close()
|
||||
}
|
||||
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
// GetETagForAccount returns a content hash (SHA-256) over presets, sources, and recents for the account and device.
|
||||
// If device is empty, it hashes across all devices in the account.
|
||||
// The default sources fingerprint is always included so that newly added defaults (e.g. Amazon)
|
||||
// invalidate cached responses even when the stored Sources.xml has not changed.
|
||||
func (ds *DataStore) GetETagForAccount(account, device string) string {
|
||||
h := sha256.New()
|
||||
|
||||
// Include the default sources fingerprint so mergeDefaultSources changes are visible.
|
||||
defaults := ds.GetDefaultSources()
|
||||
for i := range defaults {
|
||||
_, _ = io.WriteString(h, defaults[i].ID+defaults[i].SourceKeyType+defaults[i].DisplayName)
|
||||
}
|
||||
|
||||
if device != "" {
|
||||
deviceDir := ds.AccountDeviceDir(account, device)
|
||||
for _, name := range []string{constants.PresetsFile, constants.SourcesFile, constants.RecentsFile} {
|
||||
f, err := os.Open(filepath.Join(deviceDir, name))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
return contentHashForFiles(
|
||||
filepath.Join(deviceDir, constants.PresetsFile),
|
||||
filepath.Join(deviceDir, constants.SourcesFile),
|
||||
filepath.Join(deviceDir, constants.RecentsFile),
|
||||
)
|
||||
_, _ = io.Copy(h, f)
|
||||
_ = f.Close()
|
||||
}
|
||||
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
devicesDir := ds.AccountDevicesDir(account)
|
||||
@@ -1679,8 +1682,6 @@ func (ds *DataStore) GetETagForAccount(account, device string) string {
|
||||
// If-None-Match header and return 304 on the first request.
|
||||
entries, _ := os.ReadDir(devicesDir)
|
||||
|
||||
h := sha256.New()
|
||||
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() {
|
||||
deviceDir := ds.AccountDeviceDir(account, entry.Name())
|
||||
@@ -1717,6 +1718,12 @@ type Settings struct {
|
||||
PreferredSource string `json:"preferred_source,omitempty"`
|
||||
InternalPaths []string `json:"internal_paths,omitempty"`
|
||||
Shortcuts map[string]int `json:"shortcuts,omitempty"`
|
||||
SpotifyClientID string `json:"spotify_client_id,omitempty"`
|
||||
SpotifyClientSecret string `json:"spotify_client_secret,omitempty"`
|
||||
SpotifyRedirectURI string `json:"spotify_redirect_uri,omitempty"`
|
||||
AmazonClientID string `json:"amazon_client_id,omitempty"`
|
||||
AmazonClientSecret string `json:"amazon_client_secret,omitempty"`
|
||||
AmazonRedirectURI string `json:"amazon_redirect_uri,omitempty"`
|
||||
}
|
||||
|
||||
// GetSettings retrieves the global service settings.
|
||||
@@ -1906,3 +1913,158 @@ func (ds *DataStore) ClearDNSDiscoveries() error {
|
||||
|
||||
return os.Remove(path)
|
||||
}
|
||||
|
||||
// groupFilePath returns the on-disk path for a group file.
|
||||
func (ds *DataStore) groupFilePath(account, groupID string) string {
|
||||
return filepath.Join(ds.AccountDevicesDir(account), "Group_"+groupID+".xml")
|
||||
}
|
||||
|
||||
// generateGroupID returns a unique 7-digit group ID that has no existing file.
|
||||
func (ds *DataStore) generateGroupID(account string) string {
|
||||
for {
|
||||
id := fmt.Sprintf("%07d", rand.Int63n(10_000_000)) //nolint:gosec
|
||||
if !exists(ds.groupFilePath(account, id)) {
|
||||
return id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetGroupForDevice returns the group containing the given device, or nil if ungrouped.
|
||||
func (ds *DataStore) GetGroupForDevice(account, deviceID string) (*models.Group, error) {
|
||||
ds.fileMutex.RLock()
|
||||
defer ds.fileMutex.RUnlock()
|
||||
|
||||
dir := ds.AccountDevicesDir(account)
|
||||
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, ErrGroupNotFound
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, e := range entries {
|
||||
if e.IsDir() || !strings.HasPrefix(e.Name(), "Group_") || !strings.HasSuffix(e.Name(), ".xml") {
|
||||
continue
|
||||
}
|
||||
|
||||
data, readErr := os.ReadFile(filepath.Join(dir, e.Name()))
|
||||
if readErr != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
var g models.Group
|
||||
if unmarshalErr := xml.Unmarshal(data, &g); unmarshalErr != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, role := range g.Roles.Roles {
|
||||
if role.DeviceID == deviceID {
|
||||
return &g, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil, ErrGroupNotFound
|
||||
}
|
||||
|
||||
// AddGroup saves a new group to disk and returns its generated ID.
|
||||
func (ds *DataStore) AddGroup(account string, group *models.Group) (string, error) {
|
||||
ds.fileMutex.Lock()
|
||||
defer ds.fileMutex.Unlock()
|
||||
|
||||
dir := ds.AccountDevicesDir(account)
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
id := ds.generateGroupID(account)
|
||||
group.ID = id
|
||||
|
||||
data, err := xml.MarshalIndent(group, "", " ")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return id, ds.atomicWriteFile(ds.groupFilePath(account, id), append([]byte(xml.Header), data...))
|
||||
}
|
||||
|
||||
// ModifyGroup updates the name of an existing group and returns the updated group.
|
||||
func (ds *DataStore) ModifyGroup(account, groupID, newName string) (*models.Group, error) {
|
||||
ds.fileMutex.Lock()
|
||||
defer ds.fileMutex.Unlock()
|
||||
|
||||
path := ds.groupFilePath(account, groupID)
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("group %s not found", groupID)
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var g models.Group
|
||||
if xmlErr := xml.Unmarshal(data, &g); xmlErr != nil {
|
||||
return nil, xmlErr
|
||||
}
|
||||
|
||||
g.Name = newName
|
||||
|
||||
updated, err := xml.MarshalIndent(&g, "", " ")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := ds.atomicWriteFile(path, append([]byte(xml.Header), updated...)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &g, nil
|
||||
}
|
||||
|
||||
// DeleteGroup removes a group from disk.
|
||||
func (ds *DataStore) DeleteGroup(account, groupID string) error {
|
||||
ds.fileMutex.Lock()
|
||||
defer ds.fileMutex.Unlock()
|
||||
|
||||
err := os.Remove(ds.groupFilePath(account, groupID))
|
||||
if os.IsNotExist(err) {
|
||||
return fmt.Errorf("group %s not found", groupID)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// SaveTuneInFavorite records a TuneIn station as favorited by creating a marker file.
|
||||
// File presence indicates the station is a favorite; no content is stored.
|
||||
func (ds *DataStore) SaveTuneInFavorite(stationID string) error {
|
||||
if ds == nil || ds.DataDir == "" || stationID == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
dir := ds.safeJoin("tunein", "favorites")
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(ds.safeJoin("tunein", "favorites", stationID), nil, 0644)
|
||||
}
|
||||
|
||||
// DeleteTuneInFavorite removes a previously saved TuneIn favorite marker file.
|
||||
// Returns nil if the station was not favorited.
|
||||
func (ds *DataStore) DeleteTuneInFavorite(stationID string) error {
|
||||
if ds == nil || ds.DataDir == "" || stationID == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
err := os.Remove(ds.safeJoin("tunein", "favorites", stationID))
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -22,6 +23,8 @@ func TestDocsConsistency(t *testing.T) {
|
||||
|
||||
summaryText := string(summaryContent)
|
||||
|
||||
docsIgnore := readDocsIgnore(t, filepath.Join(projectRoot, ".docsignore"))
|
||||
|
||||
// List of directories to check
|
||||
dirsToCheck := []string{".", "guides", "reference", "analysis"}
|
||||
|
||||
@@ -48,6 +51,13 @@ func TestDocsConsistency(t *testing.T) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Skip files listed in .docsignore at the project root
|
||||
for _, skip := range docsIgnore {
|
||||
if strings.HasSuffix(path, filepath.FromSlash(skip)) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Get relative path from docs/
|
||||
relPath, err := filepath.Rel(docsDir, path)
|
||||
if err != nil {
|
||||
@@ -69,3 +79,31 @@ func TestDocsConsistency(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// readDocsIgnore reads a .docsignore file and returns the non-empty, non-comment lines.
|
||||
// If the file does not exist it returns nil without failing the test.
|
||||
func readDocsIgnore(t *testing.T, path string) []string {
|
||||
t.Helper()
|
||||
f, err := os.Open(path)
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read %s: %v", path, err)
|
||||
}
|
||||
defer func() { _ = f.Close() }()
|
||||
|
||||
var patterns []string
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
patterns = append(patterns, line)
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
t.Fatalf("Error reading %s: %v", path, err)
|
||||
}
|
||||
return patterns
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// HandleAlexaCertificate handles POST /alexa/certificate.
|
||||
//
|
||||
// The speaker sends a CSR (PEM, URL-form-encoded as "csr") and a JSON "data" field
|
||||
// containing a Bearer token, device MAC address, device type, and AWS region.
|
||||
// The real voice.api.bose.io endpoint forwards the CSR to AWS IoT, which signs it
|
||||
// and returns a device certificate, the account's IoT endpoint URL, and a client ID.
|
||||
// The speaker uses these to establish a persistent MQTT connection to Alexa IoT.
|
||||
//
|
||||
// Full implementation requires an AWS IoT integration:
|
||||
// - Parse the CSR from the form body
|
||||
// - Exchange it via the AWS IoT CreateKeysAndCertificate or RegisterThing API
|
||||
// - Return {"certificatePem": "...", "iot_endpoint": "...", "client_id": "..."}
|
||||
//
|
||||
// Until implemented, Alexa voice control will not work after cloud shutdown.
|
||||
func (s *Server) HandleAlexaCertificate(w http.ResponseWriter, r *http.Request) {
|
||||
device := ""
|
||||
|
||||
if err := r.ParseForm(); err == nil {
|
||||
if data := r.FormValue("data"); data != "" {
|
||||
var d struct {
|
||||
Device string `json:"device"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(data), &d); err == nil {
|
||||
device = d.Device
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("[alexa] certificate provisioning not implemented (device=%s); Alexa voice control requires AWS IoT integration", device)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusNotImplemented)
|
||||
_, _ = w.Write([]byte(`{"error":"not_implemented","message":"Alexa IoT certificate provisioning requires AWS IoT integration. See voice.api.bose.io /alexa/certificate handler."}`))
|
||||
}
|
||||
@@ -4,12 +4,14 @@ package handlers
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/bmx"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
@@ -148,6 +150,29 @@ func (s *Server) HandleTuneInToken(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// HandleOrionToken returns an anonymous Orion access token.
|
||||
// The token is a base64-encoded JSON serial, matching the pattern used by the real Bose BMX Orion service.
|
||||
func (s *Server) HandleOrionToken(w http.ResponseWriter, _ *http.Request) {
|
||||
token := datastore.GenerateSerialSecret("orion")
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleOrionPlayback returns Orion playback information.
|
||||
func (s *Server) HandleOrionPlayback(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") == "" {
|
||||
@@ -341,3 +366,27 @@ func (s *Server) HandleTuneInSearch(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleTuneInFavorite handles POST /bmx/tunein/v1/favorite/{stationID}.
|
||||
func (s *Server) HandleTuneInFavorite(w http.ResponseWriter, r *http.Request) {
|
||||
stationID := chi.URLParam(r, "stationID")
|
||||
if err := s.ds.SaveTuneInFavorite(stationID); err != nil {
|
||||
log.Printf("Failed to persist TuneIn favorite %s: %v", stationID, err)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
_, _ = w.Write([]byte("{}"))
|
||||
}
|
||||
|
||||
// HandleTuneInDeleteFavorite handles DELETE /bmx/tunein/v1/favorite/{stationID}.
|
||||
func (s *Server) HandleTuneInDeleteFavorite(w http.ResponseWriter, r *http.Request) {
|
||||
stationID := chi.URLParam(r, "stationID")
|
||||
if err := s.ds.DeleteTuneInFavorite(stationID); err != nil {
|
||||
log.Printf("Failed to delete TuneIn favorite %s: %v", stationID, err)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
_, _ = w.Write([]byte("{}"))
|
||||
}
|
||||
|
||||
@@ -2,7 +2,9 @@ package handlers
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"math/big"
|
||||
@@ -17,6 +19,19 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// sourceProvidersETag returns a stable ETag for the source providers list,
|
||||
// derived from the serialized content so it only changes when the list changes.
|
||||
func sourceProvidersETag() string {
|
||||
data, err := marge.SourceProvidersToXML()
|
||||
if err != nil {
|
||||
return "source-providers-v1"
|
||||
}
|
||||
|
||||
sum := sha256.Sum256(data)
|
||||
|
||||
return fmt.Sprintf("%x", sum[:8])
|
||||
}
|
||||
|
||||
// HandleMargeCreateAccount creates a new account from Stockholm (XML).
|
||||
func (s *Server) HandleMargeCreateAccount(w http.ResponseWriter, r *http.Request) {
|
||||
body, err := io.ReadAll(r.Body)
|
||||
@@ -128,7 +143,7 @@ func (s *Server) HandleMargeLogin(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// HandleMargeSourceProviders returns the Marge source providers.
|
||||
func (s *Server) HandleMargeSourceProviders(w http.ResponseWriter, r *http.Request) {
|
||||
etag := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
||||
etag := sourceProvidersETag()
|
||||
if r.Header.Get("If-None-Match") == etag {
|
||||
w.WriteHeader(http.StatusNotModified)
|
||||
return
|
||||
@@ -679,26 +694,142 @@ func (s *Server) HandleMargeStreamingToken(w http.ResponseWriter, _ *http.Reques
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
// HandleMargeDeviceGroup returns grouping information for a device (empty group by default).
|
||||
func (s *Server) HandleMargeDeviceGroup(w http.ResponseWriter, _ *http.Request) {
|
||||
// Native firmware expects vnd.bose.streaming content type
|
||||
// HandleMargeDeviceGroup returns grouping information for a device.
|
||||
func (s *Server) HandleMargeDeviceGroup(w http.ResponseWriter, r *http.Request) {
|
||||
account := chi.URLParam(r, "account")
|
||||
device := chi.URLParam(r, "device")
|
||||
|
||||
w.Header().Set("Content-Type", "application/vnd.bose.streaming-v1.2+xml")
|
||||
|
||||
group, err := s.ds.GetGroupForDevice(account, device)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(constants.XMLHeader + `<group/>`))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
data, err := xml.Marshal(group)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(constants.XMLHeader + `<group/>`))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(constants.XMLHeader + `<group/>`))
|
||||
_, _ = w.Write([]byte(constants.XMLHeader))
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
// HandleMargeDeviceGroupServer returns grouping server information (404 by default if not a server).
|
||||
func (s *Server) HandleMargeDeviceGroupServer(w http.ResponseWriter, r *http.Request) {
|
||||
// Not in a group as server
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
|
||||
// HandleMargeDeviceGroupMember returns grouping member information (404 by default if not a member).
|
||||
func (s *Server) HandleMargeDeviceGroupMember(w http.ResponseWriter, r *http.Request) {
|
||||
// Not in a group as member
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
|
||||
// HandleMargeAddGroup creates a new stereo group for an account.
|
||||
func (s *Server) HandleMargeAddGroup(w http.ResponseWriter, r *http.Request) {
|
||||
account := chi.URLParam(r, "account")
|
||||
if !validatePathID(account) {
|
||||
http.Error(w, "Invalid account ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to read body", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var group models.Group
|
||||
if xmlErr := xml.Unmarshal(body, &group); xmlErr != nil {
|
||||
http.Error(w, "Invalid XML", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
id, err := s.ds.AddGroup(account, &group)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
data, err := xml.Marshal(&group)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/vnd.bose.streaming-v1.2+xml")
|
||||
w.Header().Set("Location", s.serverURL+"/account/"+account+"/group/"+id)
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = w.Write([]byte(constants.XMLHeader))
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
// HandleMargeModifyGroup updates the name of an existing stereo group.
|
||||
func (s *Server) HandleMargeModifyGroup(w http.ResponseWriter, r *http.Request) {
|
||||
account := chi.URLParam(r, "account")
|
||||
groupID := chi.URLParam(r, "groupId")
|
||||
|
||||
if !validatePathID(account) || !validatePathID(groupID) {
|
||||
http.Error(w, "Invalid ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to read body", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var req models.Group
|
||||
if xmlErr := xml.Unmarshal(body, &req); xmlErr != nil {
|
||||
http.Error(w, "Invalid XML", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
updated, err := s.ds.ModifyGroup(account, groupID, req.Name)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
data, err := xml.Marshal(updated)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/vnd.bose.streaming-v1.2+xml")
|
||||
_, _ = w.Write([]byte(constants.XMLHeader))
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
// HandleMargeDeleteGroup removes a stereo group.
|
||||
func (s *Server) HandleMargeDeleteGroup(w http.ResponseWriter, r *http.Request) {
|
||||
account := chi.URLParam(r, "account")
|
||||
groupID := chi.URLParam(r, "groupId")
|
||||
|
||||
if !validatePathID(account) || !validatePathID(groupID) {
|
||||
http.Error(w, "Invalid ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.ds.DeleteGroup(account, groupID); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
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>`))
|
||||
}
|
||||
|
||||
// HandleMusicProviderIsEligible returns the music provider eligibility.
|
||||
func (s *Server) HandleMusicProviderIsEligible(w http.ResponseWriter, _ *http.Request) {
|
||||
// For now, we return false as seen in the interaction sample.
|
||||
|
||||
@@ -278,6 +278,124 @@ func TestMargeAccountFull(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestMargeAccountFullExcludesEmptyAmazonSource is a regression test for the two-device scenario
|
||||
// observed in production: device A81B6A536A98 (alphabetically last, used as lastDeviceID)
|
||||
// has Sources.xml with 6 sources but no Amazon. The first device has Amazon with empty
|
||||
// credentials (written before OAuth was implemented). Amazon must NOT appear in /full —
|
||||
// an empty-credential Amazon causes the speaker's AmazonController to fail JSON parsing.
|
||||
func TestMargeAccountFullExcludesEmptyAmazonSource(t *testing.T) {
|
||||
tempDir, err := os.MkdirTemp("", "st-test-amazon-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(tempDir) }()
|
||||
|
||||
ds := datastore.NewDataStore(tempDir)
|
||||
|
||||
account := "3230304"
|
||||
|
||||
// First device (alphabetically): has Amazon in Sources.xml
|
||||
firstDeviceID := "08DF1F0BA325"
|
||||
firstDir := filepath.Join(tempDir, "accounts", account, "devices", firstDeviceID)
|
||||
if err := os.MkdirAll(firstDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create first device dir: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(firstDir, "DeviceInfo.xml"), []byte(`
|
||||
<info deviceID="08DF1F0BA325">
|
||||
<name>A Sound Machine</name>
|
||||
<type>SoundTouch 20 scm</type>
|
||||
</info>
|
||||
`), 0644); err != nil {
|
||||
t.Fatalf("Failed to write first device DeviceInfo.xml: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(firstDir, "Sources.xml"), []byte(`<sources>
|
||||
<source id="10006" type="AMAZON" createdOn="2026-01-01T00:00:00.000+00:00" updatedOn="2026-01-01T00:00:00.000+00:00" displayName="Amazon Music" secret="" secretType="token" sourceproviderid="20">
|
||||
<sourceKey type="AMAZON" account=""/>
|
||||
</source>
|
||||
</sources>`), 0644); err != nil {
|
||||
t.Fatalf("Failed to write first device Sources.xml: %v", err)
|
||||
}
|
||||
|
||||
// Second device (alphabetically last = lastDeviceID): 6 sources but NO Amazon.
|
||||
// This reproduces the real full.xml returned by the live service.
|
||||
lastDeviceID := "A81B6A536A98"
|
||||
lastDir := filepath.Join(tempDir, "accounts", account, "devices", lastDeviceID)
|
||||
if err := os.MkdirAll(lastDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create last device dir: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(lastDir, "DeviceInfo.xml"), []byte(`
|
||||
<info deviceID="A81B6A536A98">
|
||||
<name>Another Speaker</name>
|
||||
<type>SoundTouch 300</type>
|
||||
</info>
|
||||
`), 0644); err != nil {
|
||||
t.Fatalf("Failed to write last device DeviceInfo.xml: %v", err)
|
||||
}
|
||||
// Sources.xml mirrors the real persisted file: AUX, INTERNET_RADIO, LOCAL_INTERNET_RADIO,
|
||||
// TUNEIN, RADIO_BROWSER, Spotify — no Amazon.
|
||||
lastSourcesXML := `<sources>
|
||||
<source id="10001" type="Audio" createdOn="2015-03-11T19:12:38.000+00:00" updatedOn="2015-03-11T19:12:38.000+00:00" displayName="AUX IN" secret="" secretType="token" sourceproviderid="9">
|
||||
<sourceKey type="AUX" account="AUX"/>
|
||||
</source>
|
||||
<source id="10002" type="Audio" createdOn="2015-03-11T19:12:38.000+00:00" updatedOn="2015-03-11T19:12:38.000+00:00" displayName="" secret="" secretType="token" sourceproviderid="2">
|
||||
<sourceKey type="INTERNET_RADIO" account=""/>
|
||||
</source>
|
||||
<source id="10003" type="Audio" createdOn="2019-01-24T08:18:37.000+00:00" updatedOn="2019-02-03T18:35:45.000+00:00" displayName="" secret="eyJzZXJpYWwiOiJsb2NhbC1pbnRlcm5ldC1yYWRpbyJ9" secretType="token" sourceproviderid="11">
|
||||
<sourceKey type="LOCAL_INTERNET_RADIO" account=""/>
|
||||
</source>
|
||||
<source id="10004" type="Audio" createdOn="2017-07-20T16:43:48.000+00:00" updatedOn="2017-07-20T16:43:48.000+00:00" displayName="" secret="eyJzZXJpYWwiOiJ0dW5laW4ifQ==" secretType="token" sourceproviderid="25">
|
||||
<sourceKey type="TUNEIN" account=""/>
|
||||
</source>
|
||||
<source id="10005" type="Audio" createdOn="2026-02-16T01:01:01.000+00:00" updatedOn="2026-02-16T01:01:01.000+00:00" displayName="" secret="" secretType="token" sourceproviderid="39">
|
||||
<sourceKey type="RADIO_BROWSER" account=""/>
|
||||
</source>
|
||||
<source id="SRC_1776706409" type="Audio" createdOn="2026-04-20T17:33:29.483+00:00" updatedOn="2026-04-20T17:33:29.483+00:00" displayName="" secret="bs-6c58d056c2d35df85f57ad2334b0cdc4" secretType="token_version_3" sourceproviderid="15">
|
||||
<sourceKey type="SPOTIFY" account="gesellix"/>
|
||||
</source>
|
||||
</sources>`
|
||||
if err := os.WriteFile(filepath.Join(lastDir, "Sources.xml"), []byte(lastSourcesXML), 0644); err != nil {
|
||||
t.Fatalf("Failed to write last device Sources.xml: %v", err)
|
||||
}
|
||||
|
||||
r, _ := setupRouter("http://localhost:8001", ds)
|
||||
ts := httptest.NewServer(r)
|
||||
defer ts.Close()
|
||||
|
||||
res, err := http.Get(ts.URL + "/marge/accounts/" + account + "/full")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
t.Errorf("Expected 200 OK, got %v", res.Status)
|
||||
}
|
||||
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
bodyStr := string(body)
|
||||
|
||||
// Amazon with empty credentials must not appear — the speaker's AmazonController
|
||||
// fails to parse an empty secret and returns MUSIC_SERVICE_ACCOUNT_LOGIN_FAILED.
|
||||
if strings.Contains(bodyStr, "<sourceproviderid>20</sourceproviderid>") {
|
||||
t.Errorf("/full response must not include an empty-credential Amazon source; body:\n%s", bodyStr)
|
||||
}
|
||||
|
||||
// The 6 sources from lastDeviceID's stored Sources.xml must all be present.
|
||||
// Checked by sourceproviderid since <name> may hold a display name rather than the type string.
|
||||
for _, wantProviderID := range []string{
|
||||
"<sourceproviderid>9</sourceproviderid>", // AUX
|
||||
"<sourceproviderid>2</sourceproviderid>", // INTERNET_RADIO
|
||||
"<sourceproviderid>11</sourceproviderid>", // LOCAL_INTERNET_RADIO
|
||||
"<sourceproviderid>25</sourceproviderid>", // TUNEIN
|
||||
"<sourceproviderid>39</sourceproviderid>", // RADIO_BROWSER
|
||||
"<sourceproviderid>15</sourceproviderid>", // Spotify
|
||||
} {
|
||||
if !strings.Contains(bodyStr, wantProviderID) {
|
||||
t.Errorf("/full response is missing source with %s; body:\n%s", wantProviderID, bodyStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMargeAccountSources(t *testing.T) {
|
||||
tempDir, err := os.MkdirTemp("", "st-test-*")
|
||||
if err != nil {
|
||||
@@ -333,7 +451,7 @@ func TestMargeAccountSources(t *testing.T) {
|
||||
"<createdOn>2024-01-01T00:00:00Z</createdOn>",
|
||||
"<updatedOn>2024-01-01T00:00:00Z</updatedOn>",
|
||||
"<credential type=\"token\">TOKEN1</credential>",
|
||||
"<name>User1</name>",
|
||||
"<name>Source1</name>",
|
||||
"<sourcename></sourcename>",
|
||||
"<sourceSettings/>",
|
||||
"<username>User1</username>",
|
||||
@@ -1563,3 +1681,177 @@ func TestMargeAdvancedFeatures(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMargeGroupCRUD(t *testing.T) {
|
||||
tempDir, err := os.MkdirTemp("", "st-group-test-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
|
||||
defer func() { _ = os.RemoveAll(tempDir) }()
|
||||
|
||||
ds := datastore.NewDataStore(tempDir)
|
||||
r, _ := setupRouter("http://localhost:8001", ds)
|
||||
ts := httptest.NewServer(r)
|
||||
defer ts.Close()
|
||||
|
||||
account := "ACC001"
|
||||
device1 := "AABBCCDDEEFF"
|
||||
device2 := "112233445566"
|
||||
|
||||
groupXML := `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<group>
|
||||
<name>Living Room Stereo</name>
|
||||
<masterDeviceId>` + device1 + `</masterDeviceId>
|
||||
<roles>
|
||||
<groupRole><deviceId>` + device1 + `</deviceId><role>LEFT</role><ipAddress>192.168.1.10</ipAddress></groupRole>
|
||||
<groupRole><deviceId>` + device2 + `</deviceId><role>RIGHT</role><ipAddress>192.168.1.11</ipAddress></groupRole>
|
||||
</roles>
|
||||
<senderIPAddress>192.168.1.10</senderIPAddress>
|
||||
</group>`
|
||||
|
||||
var groupID string
|
||||
|
||||
t.Run("GET device group returns empty group before creation", func(t *testing.T) {
|
||||
res, err := http.Get(ts.URL + "/marge/streaming/account/" + account + "/device/" + device1 + "/group")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
t.Errorf("Expected 200, got %d", res.StatusCode)
|
||||
}
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
if !strings.Contains(string(body), "<group") {
|
||||
t.Errorf("Expected <group> element, got: %s", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("POST group creates a new group and returns 201 with ID", func(t *testing.T) {
|
||||
res, err := http.Post(
|
||||
ts.URL+"/marge/streaming/account/"+account+"/group",
|
||||
"application/xml",
|
||||
bytes.NewBufferString(groupXML),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
|
||||
if res.StatusCode != http.StatusCreated {
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
t.Fatalf("Expected 201 Created, got %d: %s", res.StatusCode, body)
|
||||
}
|
||||
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
if !strings.Contains(string(body), `<group `) {
|
||||
t.Errorf("Response missing <group> with id attr: %s", body)
|
||||
}
|
||||
|
||||
// Parse out the group ID from the response XML
|
||||
type groupResp struct {
|
||||
ID string `xml:"id,attr"`
|
||||
}
|
||||
var gr groupResp
|
||||
if err := xml.Unmarshal(body, &gr); err != nil {
|
||||
t.Fatalf("Failed to unmarshal group response: %v", err)
|
||||
}
|
||||
if gr.ID == "" {
|
||||
t.Fatalf("Response group has no ID: %s", body)
|
||||
}
|
||||
groupID = gr.ID
|
||||
})
|
||||
|
||||
t.Run("GET device group returns the group after creation", func(t *testing.T) {
|
||||
res, err := http.Get(ts.URL + "/marge/streaming/account/" + account + "/device/" + device1 + "/group")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
t.Errorf("Expected 200, got %d", res.StatusCode)
|
||||
}
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
if !strings.Contains(string(body), "Living Room Stereo") {
|
||||
t.Errorf("Expected group name in response: %s", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("POST group/{groupId} renames the group", func(t *testing.T) {
|
||||
if groupID == "" {
|
||||
t.Skip("No group ID from prior subtest")
|
||||
}
|
||||
modXML := `<group><name>Bedroom Stereo</name><masterDeviceId>` + device1 + `</masterDeviceId></group>`
|
||||
req, _ := http.NewRequest(http.MethodPost,
|
||||
ts.URL+"/marge/streaming/account/"+account+"/group/"+groupID,
|
||||
bytes.NewBufferString(modXML),
|
||||
)
|
||||
req.Header.Set("Content-Type", "application/xml")
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
t.Fatalf("Expected 200, got %d: %s", res.StatusCode, body)
|
||||
}
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
if !strings.Contains(string(body), "Bedroom Stereo") {
|
||||
t.Errorf("Expected updated name in response: %s", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("DELETE group/{groupId} removes the group", func(t *testing.T) {
|
||||
if groupID == "" {
|
||||
t.Skip("No group ID from prior subtest")
|
||||
}
|
||||
req, _ := http.NewRequest(http.MethodDelete,
|
||||
ts.URL+"/marge/streaming/account/"+account+"/group/"+groupID,
|
||||
nil,
|
||||
)
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
t.Fatalf("Expected 200, got %d: %s", res.StatusCode, body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("DELETE group/{groupId} returns 404 for missing group", func(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodDelete,
|
||||
ts.URL+"/marge/streaming/account/"+account+"/group/9999999",
|
||||
nil,
|
||||
)
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
|
||||
if res.StatusCode != http.StatusNotFound {
|
||||
t.Errorf("Expected 404, got %d", res.StatusCode)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GET device group is empty after deletion", func(t *testing.T) {
|
||||
res, err := http.Get(ts.URL + "/marge/streaming/account/" + account + "/device/" + device1 + "/group")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
// Should be back to empty <group/>
|
||||
if strings.Contains(string(body), "Bedroom Stereo") {
|
||||
t.Errorf("Group should be gone after deletion: %s", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ var webFS embed.FS
|
||||
//go:embed static/media/*
|
||||
var mediaFS embed.FS
|
||||
|
||||
//go:embed static/ced
|
||||
var cedFS embed.FS
|
||||
|
||||
//go:embed static/bmx_services.json
|
||||
var bmxServicesJSON []byte
|
||||
|
||||
@@ -59,3 +62,21 @@ func (s *Server) HandleMedia() http.HandlerFunc {
|
||||
http.StripPrefix("/media", http.FileServer(http.FS(subFS))).ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleBmxIcons returns a handler for serving BMX icon assets (media.bose.io /bmx-icons/*).
|
||||
func (s *Server) HandleBmxIcons() http.HandlerFunc {
|
||||
subFS, _ := fs.Sub(mediaFS, "static/media")
|
||||
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
http.FileServer(http.FS(subFS)).ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleCedStatic returns a handler for serving downloads.bose.com CED static files.
|
||||
func (s *Server) HandleCedStatic() http.HandlerFunc {
|
||||
subFS, _ := fs.Sub(cedFS, "static/ced")
|
||||
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
http.StripPrefix("/ced", http.FileServer(http.FS(subFS))).ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,8 +7,8 @@ import (
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/client"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
@@ -442,3 +442,284 @@ func (s *Server) HandleMgmtPrimeDevice(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"status":"Priming triggered"}`))
|
||||
}
|
||||
|
||||
// HandleMgmtAmazonInit starts the Amazon OAuth flow by returning an authorization URL.
|
||||
func (s *Server) HandleMgmtAmazonInit(w http.ResponseWriter, r *http.Request) {
|
||||
s.mu.RLock()
|
||||
svc := s.amazonService
|
||||
s.mu.RUnlock()
|
||||
|
||||
if svc == nil {
|
||||
http.Error(w, `{"error":"amazon not configured"}`, http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
state := r.URL.Query().Get("account")
|
||||
redirectURL := svc.BuildAuthorizeURL(state)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetEscapeHTML(false)
|
||||
|
||||
if err := enc.Encode(map[string]string{
|
||||
"redirectUrl": redirectURL,
|
||||
}); err != nil {
|
||||
log.Printf("[Mgmt] Failed to encode Amazon redirect URL: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleMgmtAmazonCallback is the browser OAuth callback from Amazon LWA.
|
||||
// Not protected by Basic Auth — Amazon redirects the user's browser here directly.
|
||||
// Returns an HTML page the user can close.
|
||||
func (s *Server) HandleMgmtAmazonCallback(w http.ResponseWriter, r *http.Request) {
|
||||
s.mu.RLock()
|
||||
svc := s.amazonService
|
||||
s.mu.RUnlock()
|
||||
|
||||
if svc == nil {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
_, _ = w.Write([]byte(`<html><body><h1>Error</h1><p>Amazon Music integration not configured</p></body></html>`))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if errMsg := r.URL.Query().Get("error"); errMsg != "" {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`<html><body><h1>Amazon Authorization Failed</h1><p>Error: ` + errMsg + `</p></body></html>`))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
code := r.URL.Query().Get("code")
|
||||
if code == "" {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`<html><body><h1>Missing authorization code</h1></body></html>`))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err := svc.ExchangeCodeAndStore(code); err != nil {
|
||||
log.Printf("[Mgmt] Amazon callback failed: %v", err)
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = w.Write([]byte(`<html><body><h1>Error</h1><p>Token exchange failed</p></body></html>`))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
accountID := r.URL.Query().Get("account")
|
||||
if accountID == "" {
|
||||
accountID = r.URL.Query().Get("state")
|
||||
}
|
||||
|
||||
s.bridgeAmazonToMarge(accountID)
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
_, _ = w.Write([]byte(`<html><body><h1>Amazon Music Connected</h1><p>You can close this window.</p></body></html>`))
|
||||
}
|
||||
|
||||
// HandleMgmtAmazonConfirm exchanges an authorization code for tokens.
|
||||
// Used by the ueberboese mobile app after the deep link callback delivers the code.
|
||||
// Protected by Basic Auth.
|
||||
func (s *Server) HandleMgmtAmazonConfirm(w http.ResponseWriter, r *http.Request) {
|
||||
s.mu.RLock()
|
||||
svc := s.amazonService
|
||||
s.mu.RUnlock()
|
||||
|
||||
if svc == nil {
|
||||
http.Error(w, `{"error":"amazon not configured"}`, http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
code := r.URL.Query().Get("code")
|
||||
if code == "" {
|
||||
http.Error(w, `{"error":"missing code parameter"}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := svc.ExchangeCodeAndStore(code); err != nil {
|
||||
log.Printf("[Mgmt] Amazon confirm failed: %v", err)
|
||||
http.Error(w, `{"error":"token exchange failed"}`, http.StatusInternalServerError)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
accountID := r.URL.Query().Get("account")
|
||||
if accountID == "" {
|
||||
accountID = r.URL.Query().Get("state")
|
||||
}
|
||||
|
||||
s.bridgeAmazonToMarge(accountID)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"ok":true}`))
|
||||
}
|
||||
|
||||
func (s *Server) bridgeAmazonToMarge(accountID string) {
|
||||
if accountID == "" {
|
||||
accountID = "default"
|
||||
}
|
||||
|
||||
s.mu.RLock()
|
||||
svc := s.amazonService
|
||||
s.mu.RUnlock()
|
||||
|
||||
if svc == nil {
|
||||
return
|
||||
}
|
||||
|
||||
accounts := svc.GetAllAccounts()
|
||||
if len(accounts) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
for _, acc := range accounts {
|
||||
log.Printf("[Amazon Bridge] Registering Amazon user %s in Marge for account %s", acc.Email, accountID)
|
||||
|
||||
// Build the AmazonSecret credential envelope expected by the speaker firmware.
|
||||
credMap := map[string]interface{}{
|
||||
"AmazonSecret": map[string]string{
|
||||
"refresh_token": acc.RefreshToken,
|
||||
"site_id": acc.SiteID,
|
||||
},
|
||||
}
|
||||
|
||||
credJSON, err := json.Marshal(credMap)
|
||||
if err != nil {
|
||||
log.Printf("[Amazon Bridge] Failed to marshal credential: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
_, err = marge.AddSource(s.ds, accountID, acc.Email, strconv.Itoa(constants.AmazonProviderID), string(credJSON), constants.CredentialTypeToken, acc.DisplayName)
|
||||
if err != nil {
|
||||
log.Printf("[Amazon Bridge] Failed to register source in Marge: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
allDevices, err := s.ds.ListAllDevices()
|
||||
if err != nil {
|
||||
log.Printf("[Amazon Bridge] Failed to list devices: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
for i := range allDevices {
|
||||
dev := &allDevices[i]
|
||||
if dev.AccountID != accountID && accountID != "default" {
|
||||
continue
|
||||
}
|
||||
|
||||
if dev.IPAddress == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
go func(d models.ServiceDeviceInfo) {
|
||||
log.Printf("[Amazon Bridge] Notifying speaker %s (%s) about new Amazon account", d.Name, d.IPAddress)
|
||||
|
||||
cfg := client.DefaultConfig()
|
||||
cfg.Host = d.IPAddress
|
||||
cfg.Timeout = 5 * time.Second
|
||||
c := client.NewClient(cfg)
|
||||
creds := models.NewAmazonOAuthCredentials(acc.Email, string(credJSON), acc.DisplayName)
|
||||
|
||||
if err := c.SetMusicServiceOAuthAccount(creds); err != nil {
|
||||
log.Printf("[Amazon Bridge] Failed to notify speaker %s via OAuth: %v", d.Name, err)
|
||||
log.Printf("[Amazon Bridge] Speaker %s doesn't support OAuth or is unreachable, falling back to Marge sync notification", d.Name)
|
||||
|
||||
if err := c.NotifySourcesUpdated(d.DeviceID); err != nil {
|
||||
log.Printf("[Amazon Bridge] Sync notification failed for speaker %s: %v", d.Name, err)
|
||||
log.Printf("[Amazon Bridge] Falling back to legacy account creation for speaker %s", d.Name)
|
||||
|
||||
legacyCreds := models.NewAmazonMusicCredentials(acc.Email, string(credJSON))
|
||||
if err := c.SetMusicServiceAccount(legacyCreds); err != nil {
|
||||
log.Printf("[Amazon Bridge] Legacy fallback failed for speaker %s: %v", d.Name, err)
|
||||
} else {
|
||||
log.Printf("[Amazon Bridge] Legacy fallback successful for speaker %s", d.Name)
|
||||
}
|
||||
} else {
|
||||
log.Printf("[Amazon Bridge] Sync notification successful for speaker %s", d.Name)
|
||||
}
|
||||
} else {
|
||||
log.Printf("[Amazon Bridge] Successfully notified speaker %s", d.Name)
|
||||
}
|
||||
}(*dev)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// HandleMgmtAmazonAccounts returns linked Amazon accounts (tokens stripped).
|
||||
func (s *Server) HandleMgmtAmazonAccounts(w http.ResponseWriter, _ *http.Request) {
|
||||
s.mu.RLock()
|
||||
svc := s.amazonService
|
||||
s.mu.RUnlock()
|
||||
|
||||
if svc == nil {
|
||||
http.Error(w, `{"error":"amazon not configured"}`, http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
accounts := svc.GetAccounts()
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if err := json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"accounts": accounts,
|
||||
}); err != nil {
|
||||
log.Printf("[Mgmt] Failed to encode Amazon accounts: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleMgmtAmazonToken returns a fresh Amazon access token for the linked account.
|
||||
func (s *Server) HandleMgmtAmazonToken(w http.ResponseWriter, _ *http.Request) {
|
||||
s.mu.RLock()
|
||||
svc := s.amazonService
|
||||
s.mu.RUnlock()
|
||||
|
||||
if svc == nil {
|
||||
http.Error(w, `{"error":"amazon not configured"}`, http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
accessToken, username, err := svc.GetFreshToken()
|
||||
if err != nil {
|
||||
log.Printf("[Mgmt] Amazon token error: %v", err)
|
||||
http.Error(w, `{"error":"no token available"}`, http.StatusInternalServerError)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if err := json.NewEncoder(w).Encode(map[string]string{
|
||||
"access_token": accessToken,
|
||||
"username": username,
|
||||
}); err != nil {
|
||||
log.Printf("[Mgmt] Failed to encode Amazon token: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleMgmtPrimeDeviceAmazon triggers Amazon Music priming for a specific device.
|
||||
func (s *Server) HandleMgmtPrimeDeviceAmazon(w http.ResponseWriter, r *http.Request) {
|
||||
deviceID := r.URL.Query().Get("deviceId")
|
||||
|
||||
if deviceID == "" {
|
||||
http.Error(w, `{"error":"missing deviceId"}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
deviceIP, err := s.resolveDeviceIDToIP(deviceID)
|
||||
if err != nil {
|
||||
log.Printf("[Mgmt] Amazon prime failed: %v", err)
|
||||
http.Error(w, fmt.Sprintf(`{"error":"%v"}`, err), http.StatusNotFound)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
go s.PrimeDeviceWithAmazon(deviceIP)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"status":"Priming triggered"}`))
|
||||
}
|
||||
|
||||
@@ -8,20 +8,30 @@ import (
|
||||
|
||||
"strconv"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/amazon"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/constants"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/spotify"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// HandleBoseToken handles the Bose-specific token refresh request from the speaker.
|
||||
// POST /oauth/device/{deviceID}/music/musicprovider/{sourceID}/token/cs1
|
||||
// POST /oauth/device/{deviceID}/music/musicprovider/{sourceID}/token/cs3
|
||||
func (s *Server) HandleBoseToken(w http.ResponseWriter, r *http.Request) {
|
||||
sourceID := chi.URLParam(r, "sourceID")
|
||||
|
||||
for _, provider := range constants.StaticProviders {
|
||||
if strconv.Itoa(provider.ID) == sourceID && provider.Name == constants.ProviderSpotify {
|
||||
if strconv.Itoa(provider.ID) != sourceID {
|
||||
continue
|
||||
}
|
||||
|
||||
switch provider.Name {
|
||||
case constants.ProviderSpotify:
|
||||
s.HandleBoseSpotifyToken(w, r)
|
||||
return
|
||||
case constants.ProviderAmazon:
|
||||
s.HandleBoseAmazonToken(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,6 +99,102 @@ func (s *Server) HandleBoseAccountToken(w http.ResponseWriter, r *http.Request)
|
||||
s.HandleBoseSpotifyToken(w, r)
|
||||
}
|
||||
|
||||
// HandleBoseAmazonToken handles the Amazon Music token refresh request from the speaker.
|
||||
// POST /oauth/device/{deviceID}/music/musicprovider/20/token/cs1
|
||||
// The speaker sends the bare refresh token extracted from the stored AmazonSecret JSON.
|
||||
func (s *Server) HandleBoseAmazonToken(w http.ResponseWriter, r *http.Request) {
|
||||
deviceID := chi.URLParam(r, "deviceID")
|
||||
log.Printf("[Amazon] Token request for device %s", deviceID)
|
||||
|
||||
s.mu.RLock()
|
||||
svc := s.amazonService
|
||||
s.mu.RUnlock()
|
||||
|
||||
if svc == nil {
|
||||
log.Printf("[Amazon] Amazon service not configured, falling back to upstream")
|
||||
s.HandleBoseProxy(w, r)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
accounts := svc.GetAccounts()
|
||||
if len(accounts) == 0 {
|
||||
log.Printf("[Amazon] No Amazon accounts linked, falling back to upstream")
|
||||
s.HandleBoseProxy(w, r)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
_ = r.Body.Close()
|
||||
|
||||
var tokenReq struct {
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
GrantType string `json:"grant_type"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
_ = json.Unmarshal(body, &tokenReq)
|
||||
|
||||
// The speaker extracts the bare refresh token from AmazonSecret JSON and sends it here.
|
||||
secret := tokenReq.RefreshToken
|
||||
if secret == "" {
|
||||
secret = tokenReq.Code
|
||||
}
|
||||
|
||||
var (
|
||||
account *amazon.Account
|
||||
accessToken string
|
||||
userID string
|
||||
)
|
||||
|
||||
if secret != "" {
|
||||
if acc, ok := svc.GetAccountByRefreshToken(secret); ok {
|
||||
account = acc
|
||||
log.Printf("[Amazon] Found account for refresh token: %s", acc.UserID)
|
||||
}
|
||||
}
|
||||
|
||||
if account != nil {
|
||||
if err := svc.RefreshAccessToken(account); err != nil {
|
||||
log.Printf("[Amazon] Failed to refresh token for %s: %v. Falling back to upstream", account.UserID, err)
|
||||
s.HandleBoseProxy(w, r)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
accessToken = account.AccessToken
|
||||
} else {
|
||||
var err error
|
||||
|
||||
accessToken, userID, err = svc.GetFreshToken()
|
||||
if err != nil {
|
||||
log.Printf("[Amazon] Failed to get fresh token: %v. Falling back to upstream", err)
|
||||
s.HandleBoseProxy(w, r)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("[Amazon] Using default account %s", userID)
|
||||
}
|
||||
|
||||
// Omit "scope" — Amazon Music scopes are undocumented; sending invented values
|
||||
// risks firmware rejection.
|
||||
response := map[string]interface{}{
|
||||
"access_token": accessToken,
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Proxy-Origin", "self")
|
||||
|
||||
if err := json.NewEncoder(w).Encode(response); err != nil {
|
||||
log.Printf("[Amazon] Failed to encode response: %v", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleBoseSpotifyToken handles the Bose-specific Spotify token refresh request.
|
||||
// POST /oauth/device/{deviceID}/music/musicprovider/15/token/cs3
|
||||
func (s *Server) HandleBoseSpotifyToken(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -6,9 +6,11 @@ import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/amazon"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/spotify"
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -116,6 +118,164 @@ func TestHandleBoseSpotifyToken_FallbackToProxy(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleBoseAmazonToken_LocalResponse_ByRefreshToken verifies the account-lookup
|
||||
// path: speaker sends its stored refresh token, handler refreshes via a mock LWA
|
||||
// server and returns the new access token.
|
||||
func TestHandleBoseAmazonToken_LocalResponse_ByRefreshToken(t *testing.T) {
|
||||
// Mock LWA token endpoint
|
||||
tokenServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
if r.Form.Get("grant_type") != "refresh_token" {
|
||||
t.Errorf("expected grant_type=refresh_token, got %s", r.Form.Get("grant_type"))
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"access_token": "Atza|new-access-token",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
"refresh_token": "Atzr|new-refresh-token",
|
||||
})
|
||||
}))
|
||||
defer tokenServer.Close()
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
ds := datastore.NewDataStore(tmpDir)
|
||||
server := NewServer(ds, nil, "http://localhost", false, false, false)
|
||||
|
||||
amazonDir := filepath.Join(tmpDir, "amazon")
|
||||
_ = os.MkdirAll(amazonDir, 0755)
|
||||
|
||||
accounts := map[string]amazon.Account{
|
||||
"amzn1.account.USER1": {
|
||||
UserID: "amzn1.account.USER1",
|
||||
DisplayName: "Amazon User",
|
||||
AccessToken: "Atza|old-access-token",
|
||||
RefreshToken: "Atzr|stored-refresh-token",
|
||||
ExpiresAt: time.Now().Add(-1 * time.Hour).Unix(),
|
||||
},
|
||||
}
|
||||
data, err := json.Marshal(accounts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = os.WriteFile(filepath.Join(amazonDir, "accounts.json"), data, 0644)
|
||||
|
||||
as := amazon.NewAmazonService("client-id", "client-secret", "ueberboese-login://amazon", tmpDir)
|
||||
_ = as.Load()
|
||||
as.SetEndpoints(tokenServer.URL, "")
|
||||
|
||||
server.SetAmazonService(as)
|
||||
|
||||
r := chi.NewRouter()
|
||||
r.Post("/oauth/device/{deviceID}/music/musicprovider/{sourceID}/token/cs1", server.HandleBoseToken)
|
||||
|
||||
// Speaker sends its stored refresh token (extracted from AmazonSecret JSON)
|
||||
body := strings.NewReader(`{"grant_type":"refresh_token","refresh_token":"Atzr|stored-refresh-token","code":"","redirect_uri":""}`)
|
||||
req := httptest.NewRequest("POST", "/oauth/device/DEVICE123/music/musicprovider/20/token/cs1", body)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("Expected status 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if w.Header().Get("X-Proxy-Origin") != "self" {
|
||||
t.Errorf("Expected X-Proxy-Origin: self, got %s", w.Header().Get("X-Proxy-Origin"))
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("Failed to decode response: %v", err)
|
||||
}
|
||||
if resp["access_token"] != "Atza|new-access-token" {
|
||||
t.Errorf("Expected new access token, got %v", resp["access_token"])
|
||||
}
|
||||
if _, hasScope := resp["scope"]; hasScope {
|
||||
t.Error("Response must NOT include 'scope' for Amazon")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleBoseAmazonToken_LocalResponse_DefaultAccount verifies the fallback path:
|
||||
// no matching refresh token in body, handler uses GetFreshToken on the first account.
|
||||
func TestHandleBoseAmazonToken_LocalResponse_DefaultAccount(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
ds := datastore.NewDataStore(tmpDir)
|
||||
server := NewServer(ds, nil, "http://localhost", false, false, false)
|
||||
|
||||
amazonDir := filepath.Join(tmpDir, "amazon")
|
||||
_ = os.MkdirAll(amazonDir, 0755)
|
||||
|
||||
accounts := map[string]amazon.Account{
|
||||
"amzn1.account.USER1": {
|
||||
UserID: "amzn1.account.USER1",
|
||||
DisplayName: "Amazon User",
|
||||
AccessToken: "Atza|valid-access-token",
|
||||
RefreshToken: "Atzr|valid-refresh-token",
|
||||
ExpiresAt: time.Now().Add(1 * time.Hour).Unix(),
|
||||
},
|
||||
}
|
||||
data, err := json.Marshal(accounts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = os.WriteFile(filepath.Join(amazonDir, "accounts.json"), data, 0644)
|
||||
|
||||
as := amazon.NewAmazonService("client-id", "client-secret", "ueberboese-login://amazon", tmpDir)
|
||||
_ = as.Load()
|
||||
server.SetAmazonService(as)
|
||||
|
||||
r := chi.NewRouter()
|
||||
r.Post("/oauth/device/{deviceID}/music/musicprovider/{sourceID}/token/cs1", server.HandleBoseToken)
|
||||
|
||||
// No body — handler falls back to GetFreshToken (no network call needed, token is fresh)
|
||||
req := httptest.NewRequest("POST", "/oauth/device/DEVICE123/music/musicprovider/20/token/cs1", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("Expected status 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if w.Header().Get("X-Proxy-Origin") != "self" {
|
||||
t.Errorf("Expected X-Proxy-Origin: self, got %s", w.Header().Get("X-Proxy-Origin"))
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("Failed to decode response: %v", err)
|
||||
}
|
||||
if resp["access_token"] != "Atza|valid-access-token" {
|
||||
t.Errorf("Expected access_token 'Atza|valid-access-token', got %v", resp["access_token"])
|
||||
}
|
||||
if resp["token_type"] != "Bearer" {
|
||||
t.Errorf("Expected token_type 'Bearer', got %v", resp["token_type"])
|
||||
}
|
||||
if _, hasScope := resp["scope"]; hasScope {
|
||||
t.Error("Response must NOT include 'scope' for Amazon")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBoseAmazonToken_FallbackToProxy(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
ds := datastore.NewDataStore(tmpDir)
|
||||
server := NewServer(ds, nil, "http://localhost", false, false, false)
|
||||
server.SetMirrorSettings(true, nil, nil, "")
|
||||
|
||||
r := chi.NewRouter()
|
||||
r.Post("/oauth/device/{deviceID}/music/musicprovider/{sourceID}/token/cs1", server.HandleBoseToken)
|
||||
|
||||
req := httptest.NewRequest("POST", "/oauth/device/DEVICE123/music/musicprovider/20/token/cs1", nil)
|
||||
req.Host = "localhost"
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Header().Get("X-Proxy-Origin") == "self" {
|
||||
t.Error("Expected fallback to proxy, but got X-Proxy-Origin: self")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBoseLegacyToken(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
ds := datastore.NewDataStore(tmpDir)
|
||||
|
||||
@@ -104,7 +104,26 @@ func (s *Server) ServeProxy(target *url.URL) http.HandlerFunc {
|
||||
}
|
||||
|
||||
// HandleNotFound handles requests that don't match any route.
|
||||
// It always logs [UNHANDLED] so unimplemented endpoints are visible in plain output.
|
||||
// When proxyLogBody is enabled it also logs the request body (truncated to 512 bytes).
|
||||
func (s *Server) HandleNotFound(w http.ResponseWriter, r *http.Request) {
|
||||
if s.proxyLogBody && r.Body != nil {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
|
||||
preview := body
|
||||
truncated := ""
|
||||
|
||||
if len(preview) > 512 {
|
||||
preview = preview[:512]
|
||||
truncated = "…"
|
||||
}
|
||||
|
||||
log.Printf("[UNHANDLED] %s %s body(%d bytes): %s%s", r.Method, r.URL.Path, len(body), preview, truncated)
|
||||
} else {
|
||||
log.Printf("[UNHANDLED] %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
|
||||
s.HandleBoseProxy(w, r)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package handlers
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
@@ -14,6 +15,102 @@ import (
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/proxy"
|
||||
)
|
||||
|
||||
func TestHandleNotFound_UnhandledLogging(t *testing.T) {
|
||||
// backend absorbs proxied requests so the test doesn't hit the real Bose upstream
|
||||
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer backend.Close()
|
||||
|
||||
backendHost := strings.TrimPrefix(backend.URL, "http://")
|
||||
|
||||
captureLog := func(fn func()) string {
|
||||
var buf bytes.Buffer
|
||||
log.SetOutput(&buf)
|
||||
defer log.SetOutput(os.Stderr)
|
||||
fn()
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
t.Run("always logs [UNHANDLED] with method and path", func(t *testing.T) {
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
server := NewServer(ds, nil, "http://localhost", false, false, false)
|
||||
|
||||
req := httptest.NewRequest("GET", "/some/unknown/path", nil)
|
||||
req.Host = backendHost
|
||||
|
||||
logged := captureLog(func() {
|
||||
server.HandleNotFound(httptest.NewRecorder(), req)
|
||||
})
|
||||
|
||||
if !strings.Contains(logged, "[UNHANDLED]") {
|
||||
t.Errorf("expected [UNHANDLED] in log, got: %s", logged)
|
||||
}
|
||||
if !strings.Contains(logged, "GET") || !strings.Contains(logged, "/some/unknown/path") {
|
||||
t.Errorf("expected method and path in log, got: %s", logged)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("includes body in log when proxyLogBody is true", func(t *testing.T) {
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
server := NewServer(ds, nil, "http://localhost", false, true, false)
|
||||
|
||||
req := httptest.NewRequest("POST", "/marge/unknown", bytes.NewBufferString("<payload/>"))
|
||||
req.Host = backendHost
|
||||
|
||||
logged := captureLog(func() {
|
||||
server.HandleNotFound(httptest.NewRecorder(), req)
|
||||
})
|
||||
|
||||
if !strings.Contains(logged, "<payload/>") {
|
||||
t.Errorf("expected body in log when proxyLogBody=true, got: %s", logged)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("omits body from log when proxyLogBody is false", func(t *testing.T) {
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
server := NewServer(ds, nil, "http://localhost", false, false, false)
|
||||
|
||||
req := httptest.NewRequest("POST", "/marge/unknown", bytes.NewBufferString("<secret/>"))
|
||||
req.Host = backendHost
|
||||
|
||||
logged := captureLog(func() {
|
||||
server.HandleNotFound(httptest.NewRecorder(), req)
|
||||
})
|
||||
|
||||
if strings.Contains(logged, "<secret/>") {
|
||||
t.Errorf("expected body omitted when proxyLogBody=false, got: %s", logged)
|
||||
}
|
||||
if !strings.Contains(logged, "[UNHANDLED]") {
|
||||
t.Errorf("expected [UNHANDLED] even without body, got: %s", logged)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("body is still forwarded to proxy after being read for logging", func(t *testing.T) {
|
||||
var receivedBody string
|
||||
forwardCheck := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
receivedBody = string(b)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer forwardCheck.Close()
|
||||
|
||||
ds := datastore.NewDataStore(t.TempDir())
|
||||
server := NewServer(ds, nil, "http://localhost", false, true, false)
|
||||
|
||||
req := httptest.NewRequest("POST", "/marge/unknown", bytes.NewBufferString("<forwarded/>"))
|
||||
req.Host = strings.TrimPrefix(forwardCheck.URL, "http://")
|
||||
|
||||
captureLog(func() {
|
||||
server.HandleNotFound(httptest.NewRecorder(), req)
|
||||
})
|
||||
|
||||
if receivedBody != "<forwarded/>" {
|
||||
t.Errorf("expected body forwarded to proxy, got: %q", receivedBody)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestHandleProxyRequest_RequestBodyRecording(t *testing.T) {
|
||||
t.Setenv("RECORDER_ASYNC", "false")
|
||||
tmpDir, err := os.MkdirTemp("", "proxy-request-body-test")
|
||||
|
||||
@@ -161,10 +161,26 @@ func (s *Server) HandleGetSettings(w http.ResponseWriter, _ *http.Request) {
|
||||
redact, logBody, record := s.proxyRedact, s.proxyLogBody, s.recordEnabled
|
||||
shortcuts := s.shortcuts
|
||||
spotifyConfigured := s.spotifyService != nil
|
||||
spotifyClientID := s.spotifyClientID
|
||||
spotifyClientSecret := s.spotifyClientSecret
|
||||
spotifyRedirectURI := s.spotifyRedirectURI
|
||||
amazonConfigured := s.amazonService != nil
|
||||
amazonClientID := s.amazonClientID
|
||||
amazonClientSecret := s.amazonClientSecret
|
||||
amazonRedirectURI := s.amazonRedirectURI
|
||||
s.mu.RUnlock()
|
||||
|
||||
dnsRunning, actualBind := s.GetDNSRunning()
|
||||
|
||||
// Mask secrets: return "***" if set so the UI can show "configured" without exposing the value.
|
||||
if spotifyClientSecret != "" {
|
||||
spotifyClientSecret = "***"
|
||||
}
|
||||
|
||||
if amazonClientSecret != "" {
|
||||
amazonClientSecret = "***"
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"server_url": serverURL,
|
||||
"https_server_url": httpsServerURL,
|
||||
@@ -185,6 +201,13 @@ func (s *Server) HandleGetSettings(w http.ResponseWriter, _ *http.Request) {
|
||||
"record_interactions": record,
|
||||
"shortcuts": shortcuts,
|
||||
"spotify_configured": spotifyConfigured,
|
||||
"spotify_client_id": spotifyClientID,
|
||||
"spotify_client_secret": spotifyClientSecret,
|
||||
"spotify_redirect_uri": spotifyRedirectURI,
|
||||
"amazon_configured": amazonConfigured,
|
||||
"amazon_client_id": amazonClientID,
|
||||
"amazon_client_secret": amazonClientSecret,
|
||||
"amazon_redirect_uri": amazonRedirectURI,
|
||||
}); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
@@ -206,6 +229,12 @@ func (s *Server) HandleUpdateSettings(w http.ResponseWriter, r *http.Request) {
|
||||
PreferredSource string `json:"preferred_source"`
|
||||
InternalPaths []string `json:"internal_paths"`
|
||||
Shortcuts map[string]int `json:"shortcuts"`
|
||||
SpotifyClientID string `json:"spotify_client_id"`
|
||||
SpotifyClientSecret string `json:"spotify_client_secret"`
|
||||
SpotifyRedirectURI string `json:"spotify_redirect_uri"`
|
||||
AmazonClientID string `json:"amazon_client_id"`
|
||||
AmazonClientSecret string `json:"amazon_client_secret"`
|
||||
AmazonRedirectURI string `json:"amazon_redirect_uri"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&settings); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
@@ -227,11 +256,15 @@ func (s *Server) HandleUpdateSettings(w http.ResponseWriter, r *http.Request) {
|
||||
s.mu.Lock()
|
||||
s.serverURL = settings.ServerURL
|
||||
|
||||
s.discoveryEnabled = settings.DiscoveryEnabled
|
||||
if settings.DiscoveryInterval != "" {
|
||||
s.discoveryInterval = interval
|
||||
}
|
||||
|
||||
s.discoveryEnabled = settings.DiscoveryEnabled
|
||||
if s.discoveryInterval == 0 {
|
||||
s.discoveryEnabled = false
|
||||
}
|
||||
|
||||
s.dnsEnabled = settings.DNSEnabled
|
||||
|
||||
// Handle comma-separated upstream DNS servers
|
||||
@@ -263,6 +296,12 @@ func (s *Server) HandleUpdateSettings(w http.ResponseWriter, r *http.Request) {
|
||||
s.sm.ServerURL = settings.ServerURL
|
||||
}
|
||||
|
||||
// Update music service credentials (empty or "***" means "unchanged").
|
||||
s.applyMusicServiceCredentials(
|
||||
settings.SpotifyClientID, settings.SpotifyClientSecret, settings.SpotifyRedirectURI,
|
||||
settings.AmazonClientID, settings.AmazonClientSecret, settings.AmazonRedirectURI,
|
||||
)
|
||||
|
||||
// Persist to datastore
|
||||
// Access fields directly since we already hold the lock
|
||||
currentRedact := s.proxyRedact
|
||||
@@ -288,16 +327,32 @@ func (s *Server) HandleUpdateSettings(w http.ResponseWriter, r *http.Request) {
|
||||
PreferredSource: s.preferredSource,
|
||||
InternalPaths: s.internalPaths,
|
||||
Shortcuts: s.shortcuts,
|
||||
SpotifyClientID: s.spotifyClientID,
|
||||
SpotifyClientSecret: s.spotifyClientSecret,
|
||||
SpotifyRedirectURI: s.spotifyRedirectURI,
|
||||
AmazonClientID: s.amazonClientID,
|
||||
AmazonClientSecret: s.amazonClientSecret,
|
||||
AmazonRedirectURI: s.amazonRedirectURI,
|
||||
})
|
||||
|
||||
dnsEnabled := s.dnsEnabled
|
||||
dnsUpstreamStr := strings.Join(s.dnsUpstream, ",")
|
||||
dnsBindAddr := s.dnsBindAddr
|
||||
reinitSpotify := s.spotifyClientID != ""
|
||||
reinitAmazon := s.amazonClientID != ""
|
||||
|
||||
s.mu.Unlock()
|
||||
|
||||
s.SetDNSSettings(dnsEnabled, dnsUpstreamStr, dnsBindAddr)
|
||||
|
||||
if reinitSpotify {
|
||||
s.ReinitSpotifyService()
|
||||
}
|
||||
|
||||
if reinitAmazon {
|
||||
s.ReinitAmazonService()
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to save settings: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
|
||||
@@ -417,7 +417,7 @@ func (m *mockSSH) Run(command string) (string, error) {
|
||||
m.runCount++
|
||||
if m.runCount > 1 {
|
||||
// Return updated hosts for verification
|
||||
return "127.0.0.1 localhost\n192.168.1.100\tstreaming.bose.com\n192.168.1.100\tupdates.bose.com\n192.168.1.100\tstats.bose.com\n192.168.1.100\tbmx.bose.com\n192.168.1.100\tcontent.api.bose.io\n192.168.1.100\tevents.api.bosecm.com\n192.168.1.100\tbose-prod.apigee.net\n192.168.1.100\tworldwide.bose.com", nil
|
||||
return "127.0.0.1 localhost\n192.168.1.100\tstreaming.bose.com\n192.168.1.100\tupdates.bose.com\n192.168.1.100\tstats.bose.com\n192.168.1.100\tbmx.bose.com\n192.168.1.100\tcontent.api.bose.io\n192.168.1.100\tevents.api.bosecm.com\n192.168.1.100\tbose-prod.apigee.net\n192.168.1.100\tworldwide.bose.com\n192.168.1.100\tmedia.bose.io\n192.168.1.100\tdownloads.bose.com\n192.168.1.100\tvoice.api.bose.io", nil
|
||||
}
|
||||
return "127.0.0.1 localhost", nil
|
||||
}
|
||||
|
||||
@@ -58,6 +58,9 @@ func setupRouter(targetURL string, ds *datastore.DataStore) (*chi.Mux, *Server)
|
||||
r.Get("/account/{account}/device/{device}/group/", server.HandleMargeDeviceGroup)
|
||||
r.Get("/account/{account}/device/{device}/group/server", server.HandleMargeDeviceGroupServer)
|
||||
r.Get("/account/{account}/device/{device}/group/member", server.HandleMargeDeviceGroupMember)
|
||||
r.Post("/account/{account}/group", server.HandleMargeAddGroup)
|
||||
r.Post("/account/{account}/group/{groupId}", server.HandleMargeModifyGroup)
|
||||
r.Delete("/account/{account}/group/{groupId}", server.HandleMargeDeleteGroup)
|
||||
r.Post("/device_setting/account/{account}/device/{device}/device_settings", server.HandleMargeUpdateDeviceSettings)
|
||||
r.Get("/account/{account}/emailaddress", server.HandleMargeGetEmailAddress)
|
||||
r.Get("/account/{account}/full", server.HandleMargeAccountFull)
|
||||
@@ -87,6 +90,9 @@ func setupRouter(targetURL string, ds *datastore.DataStore) (*chi.Mux, *Server)
|
||||
r.Get("/{account}/devices/{device}/group/", server.HandleMargeDeviceGroup)
|
||||
r.Get("/{account}/devices/{device}/group/server", server.HandleMargeDeviceGroupServer)
|
||||
r.Get("/{account}/devices/{device}/group/member", server.HandleMargeDeviceGroupMember)
|
||||
r.Post("/{account}/group", server.HandleMargeAddGroup)
|
||||
r.Post("/{account}/group/{groupId}", server.HandleMargeModifyGroup)
|
||||
r.Delete("/{account}/group/{groupId}", server.HandleMargeDeleteGroup)
|
||||
}
|
||||
|
||||
// Setup Marge for tests
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -15,6 +14,7 @@ import (
|
||||
|
||||
"github.com/gesellix/bose-soundtouch/pkg/discovery"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/models"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/amazon"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/datastore"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/proxy"
|
||||
"github.com/gesellix/bose-soundtouch/pkg/service/setup"
|
||||
@@ -57,6 +57,10 @@ type Server struct {
|
||||
spotifyClientSecret string
|
||||
spotifyRedirectURI string
|
||||
spotifyService *spotify.Service
|
||||
amazonClientID string
|
||||
amazonClientSecret string
|
||||
amazonRedirectURI string
|
||||
amazonService *amazon.Service
|
||||
}
|
||||
|
||||
// RequestSnapshot represents an immutable snapshot of an HTTP request.
|
||||
@@ -312,6 +316,100 @@ func (s *Server) SetSpotifyConfig(clientID, clientSecret, redirectURI string) {
|
||||
s.spotifyRedirectURI = redirectURI
|
||||
}
|
||||
|
||||
// SetAmazonConfig sets the Amazon LWA OAuth configuration.
|
||||
func (s *Server) SetAmazonConfig(clientID, clientSecret, redirectURI string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.amazonClientID = clientID
|
||||
s.amazonClientSecret = clientSecret
|
||||
s.amazonRedirectURI = redirectURI
|
||||
}
|
||||
|
||||
// GetSpotifyConfig returns the current Spotify OAuth configuration.
|
||||
func (s *Server) GetSpotifyConfig() (clientID, clientSecret, redirectURI string) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
return s.spotifyClientID, s.spotifyClientSecret, s.spotifyRedirectURI
|
||||
}
|
||||
|
||||
// GetAmazonConfig returns the current Amazon LWA OAuth configuration.
|
||||
func (s *Server) GetAmazonConfig() (clientID, clientSecret, redirectURI string) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
return s.amazonClientID, s.amazonClientSecret, s.amazonRedirectURI
|
||||
}
|
||||
|
||||
// applyMusicServiceCredentials updates music service credential fields on the server.
|
||||
// Must be called with s.mu held. Empty string or "***" (the masked GET value) means "unchanged".
|
||||
func (s *Server) applyMusicServiceCredentials(spotifyID, spotifySecret, spotifyURI, amazonID, amazonSecret, amazonURI string) {
|
||||
if spotifyID != "" {
|
||||
s.spotifyClientID = spotifyID
|
||||
}
|
||||
|
||||
if spotifySecret != "" && spotifySecret != "***" {
|
||||
s.spotifyClientSecret = spotifySecret
|
||||
}
|
||||
|
||||
if spotifyURI != "" {
|
||||
s.spotifyRedirectURI = spotifyURI
|
||||
}
|
||||
|
||||
if amazonID != "" {
|
||||
s.amazonClientID = amazonID
|
||||
}
|
||||
|
||||
if amazonSecret != "" && amazonSecret != "***" {
|
||||
s.amazonClientSecret = amazonSecret
|
||||
}
|
||||
|
||||
if amazonURI != "" {
|
||||
s.amazonRedirectURI = amazonURI
|
||||
}
|
||||
}
|
||||
|
||||
// ReinitSpotifyService creates a new Spotify service from current config and replaces the running one.
|
||||
func (s *Server) ReinitSpotifyService() {
|
||||
clientID, clientSecret, redirectURI := s.GetSpotifyConfig()
|
||||
if clientID == "" {
|
||||
return
|
||||
}
|
||||
|
||||
if redirectURI == "" {
|
||||
redirectURI = s.serverURL + "/mgmt/spotify/callback"
|
||||
}
|
||||
|
||||
svc := spotify.NewSpotifyService(clientID, clientSecret, redirectURI, s.ds.DataDir)
|
||||
if err := svc.Load(); err != nil {
|
||||
log.Printf("[Spotify] Failed to load accounts during reinit: %v", err)
|
||||
}
|
||||
|
||||
s.SetSpotifyService(svc)
|
||||
log.Printf("[Spotify] Service reinitialized")
|
||||
}
|
||||
|
||||
// ReinitAmazonService creates a new Amazon service from current config and replaces the running one.
|
||||
func (s *Server) ReinitAmazonService() {
|
||||
clientID, clientSecret, redirectURI := s.GetAmazonConfig()
|
||||
if clientID == "" {
|
||||
return
|
||||
}
|
||||
|
||||
if redirectURI == "" {
|
||||
redirectURI = s.serverURL + "/mgmt/amazon/callback"
|
||||
}
|
||||
|
||||
svc := amazon.NewAmazonService(clientID, clientSecret, redirectURI, s.ds.DataDir)
|
||||
if err := svc.Load(); err != nil {
|
||||
log.Printf("[Amazon] Failed to load accounts during reinit: %v", err)
|
||||
}
|
||||
|
||||
s.SetAmazonService(svc)
|
||||
log.Printf("[Amazon] Service reinitialized")
|
||||
}
|
||||
|
||||
// SetMgmtConfig sets the management API authentication credentials.
|
||||
func (s *Server) SetMgmtConfig(username, password string) {
|
||||
s.mu.Lock()
|
||||
@@ -340,6 +438,22 @@ func (s *Server) SetInternalPaths(paths []string) {
|
||||
s.internalPaths = paths
|
||||
}
|
||||
|
||||
// SetAmazonService sets the Amazon OAuth service.
|
||||
func (s *Server) SetAmazonService(as *amazon.Service) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.amazonService = as
|
||||
}
|
||||
|
||||
// IsAmazonConfigured returns whether Amazon Music integration is configured.
|
||||
func (s *Server) IsAmazonConfigured() bool {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
return s.amazonService != nil
|
||||
}
|
||||
|
||||
// SetSpotifyService sets the Spotify OAuth service.
|
||||
func (s *Server) SetSpotifyService(ss *spotify.Service) {
|
||||
s.mu.Lock()
|
||||
@@ -465,40 +579,55 @@ func (s *Server) PrimeDeviceWithSpotify(deviceIP string) {
|
||||
}
|
||||
|
||||
func (s *Server) pushSpotifyTokenToDevice(deviceIP, username, accessToken string) error {
|
||||
// ZeroConf API endpoint on the speaker
|
||||
var zcURL string
|
||||
if _, _, err := net.SplitHostPort(deviceIP); err == nil {
|
||||
// If port is specified (e.g. in tests), keep it but usually it's just IP
|
||||
zcURL = fmt.Sprintf("http://%s/zc", deviceIP)
|
||||
} else {
|
||||
// If no port specified, default to 8200
|
||||
zcURL = fmt.Sprintf("http://%s:8200/zc", deviceIP)
|
||||
}
|
||||
|
||||
data := url.Values{}
|
||||
data.Set("action", "addUser")
|
||||
data.Set("userName", username)
|
||||
data.Set("blob", accessToken)
|
||||
data.Set("clientKey", "")
|
||||
data.Set("tokenType", "accesstoken")
|
||||
return spotify.PushSpotifyCredentials(zcURL, username, accessToken)
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
// PrimeDeviceWithAmazon triggers an Amazon Music priming of the speaker if an Amazon account is linked.
|
||||
func (s *Server) PrimeDeviceWithAmazon(deviceIP string) {
|
||||
s.mu.RLock()
|
||||
svc := s.amazonService
|
||||
s.mu.RUnlock()
|
||||
|
||||
if svc == nil {
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.PostForm(zcURL, data)
|
||||
accounts := svc.GetAccounts()
|
||||
if len(accounts) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
accessToken, username, err := svc.GetFreshToken()
|
||||
if err != nil {
|
||||
return fmt.Errorf("POST to %s failed: %w", zcURL, err)
|
||||
log.Printf("[Amazon Watchdog] Failed to get fresh token for %s: %v", deviceIP, err)
|
||||
return
|
||||
}
|
||||
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
log.Printf("[Amazon Watchdog] Proactively priming %s with Amazon user %s", deviceIP, username)
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("POST to %s returned status %d: %s", zcURL, resp.StatusCode, string(body))
|
||||
if err := s.pushAmazonTokenToDevice(deviceIP, username, accessToken); err != nil {
|
||||
log.Printf("[Amazon Watchdog] Failed to prime %s: %v", deviceIP, err)
|
||||
} else {
|
||||
log.Printf("[Amazon Watchdog] Successfully primed %s", deviceIP)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) pushAmazonTokenToDevice(deviceIP, username, accessToken string) error {
|
||||
var zcURL string
|
||||
if _, _, err := net.SplitHostPort(deviceIP); err == nil {
|
||||
zcURL = fmt.Sprintf("http://%s/zc", deviceIP)
|
||||
} else {
|
||||
zcURL = fmt.Sprintf("http://%s:8200/zc", deviceIP)
|
||||
}
|
||||
|
||||
return nil
|
||||
return amazon.PushAmazonCredentials(zcURL, username, accessToken)
|
||||
}
|
||||
|
||||
func (s *Server) handleDiscoveredDevice(d models.DiscoveredDevice) {
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<INDEX REVISION="02.11.00">
|
||||
|
||||
<!-- SoundTouch 20 -->
|
||||
<DEVICE ID="0x0923" PRODUCTNAME="SoundTouch 20">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/s/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="105879988" CRC="0x2d5a971e" FILENAME="Update_ti_27.0.6.46330.5043500.scm.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch 30 -->
|
||||
<DEVICE ID="0x0924" PRODUCTNAME="SoundTouch 30">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/s/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="105879988" CRC="0x2d5a971e" FILENAME="Update_ti_27.0.6.46330.5043500.scm.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch Portable -->
|
||||
<DEVICE ID="0x0925" PRODUCTNAME="SoundTouch Portable">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/s/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="105879988" CRC="0x2d5a971e" FILENAME="Update_ti_27.0.6.46330.5043500.scm.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch App HTML5 -->
|
||||
<DEVICE ID="0x0931" PRODUCTNAME="SoundTouch App HTML5">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.13" HTTPHOST="downloads.bose.com" URLPATH="/ced/soundtouch/mr4_22097fe2/" DOCVERSION="MjAxOC0wMi0xNQ==">
|
||||
<IMAGE SUBID="0" LENGTH="18377810" CRC="0xaa8209b0" FILENAME="Stockholm_27.0.13-4277-8963611.zip" />
|
||||
<NOTES URL="https://downloads.bose.com/ced/soundtouch/mr4_22097fe2/relnotes/releasenotes_##LANG##.xml" />
|
||||
<FEATURE NAME="TRIO" STATUS="OFF" />
|
||||
<FEATURE NAME="ASTREAM" STATUS="OFF" />
|
||||
<FEATURE NAME="RVT" STATUS="ON" />
|
||||
<FEATURE NAME="AD" STATUS="OFF" />
|
||||
</RELEASE>
|
||||
<PROTOCOL REVISION="67">
|
||||
<IMAGE PLATFORM="IOS" URL="https://itunes.apple.com/us/app/soundtouch-controller/id708379313" />
|
||||
<IMAGE PLATFORM="ANDROID" URL="https://play.google.com/store/apps/details?id=com.bose.soundtouch" />
|
||||
<IMAGE PLATFORM="KINDLE" URL="http://www.amazon.com/gp/mas/dl/android?asin=B00R4VJMMU"/>
|
||||
<IMAGE PLATFORM="PC" URL="http://www.bose.com/soundtouch_app_update" />
|
||||
</PROTOCOL>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- Wave SoundTouch -->
|
||||
<DEVICE ID="0x0932" PRODUCTNAME="Wave SoundTouch">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/n/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="112367416" CRC="0x49d88de4" FILENAME="Update_ti_27.0.6.46330.5043500.nelson.scm.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- VideoWave (Developer Keys) -->
|
||||
<DEVICE ID="0x0944" PRODUCTNAME="VideoWave">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2">
|
||||
<IMAGE SUBID="0" LENGTH="215402464" CRC="0xf39b7005" FILENAME="Update_ti_27.0.6.46330.5043500.marconidev.scm.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- Lifestyle (Developer Keys) -->
|
||||
<DEVICE ID="0x0945" PRODUCTNAME="Lifestyle">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2">
|
||||
<IMAGE SUBID="0" LENGTH="215402464" CRC="0xf39b7005" FILENAME="Update_ti_27.0.6.46330.5043500.marconidev.scm.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch Stereo JC -->
|
||||
<DEVICE ID="0x0935" PRODUCTNAME="SoundTouch Stereo JC">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/l/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="110991796" CRC="0x01e35713" FILENAME="Update_ti_27.0.6.46330.5043500.lisa.scm.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch SA-4 -->
|
||||
<DEVICE ID="0x0936" PRODUCTNAME="SoundTouch SA-4">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/l/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="110991796" CRC="0x01e35713" FILENAME="Update_ti_27.0.6.46330.5043500.lisa.scm.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- Cinemate -->
|
||||
<DEVICE ID="0x0938" PRODUCTNAME="Cinemate">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/t/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="114125624" CRC="0x562de6f1" FILENAME="Update_ti_27.0.6.46330.5043500.triode.scm.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch 10 -->
|
||||
<DEVICE ID="0x0939" PRODUCTNAME="SoundTouch 10">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/r/sm2/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="95906856" CRC="0xf18fe026" FILENAME="Update_ti_27.0.6.46330.5043500.rhino.sm2.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch SA-5 -->
|
||||
<DEVICE ID="0x093A" PRODUCTNAME="SoundTouch SA-5">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/b/sm2/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="100957944" CRC="0x0b99190b" FILENAME="Update_ti_27.0.6.46330.5043500.burns.sm2.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch 20 -->
|
||||
<DEVICE ID="0x093B" PRODUCTNAME="SoundTouch 20">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/s/sm2/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="99445800" CRC="0x536e6d6f" FILENAME="Update_ti_27.0.6.46330.5043500.sm2.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch 30 -->
|
||||
<DEVICE ID="0x093C" PRODUCTNAME="SoundTouch 30">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/s/sm2/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="99445800" CRC="0x536e6d6f" FILENAME="Update_ti_27.0.6.46330.5043500.sm2.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- Wave SoundTouch -->
|
||||
<DEVICE ID="0x093D" PRODUCTNAME="Wave SoundTouch">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/n/sm2/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="100297132" CRC="0x2e2fd417" FILENAME="Update_ti_27.0.6.46330.5043500.nelson.sm2.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- VideoWave (Developer Keys) -->
|
||||
<DEVICE ID="0x0946" PRODUCTNAME="VideoWave">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2">
|
||||
<IMAGE SUBID="0" LENGTH="203977300" CRC="0x1858fa51" FILENAME="Update_ti_27.0.6.46330.5043500.marconidev.sm2.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- Lifestyle (Developer Keys) -->
|
||||
<DEVICE ID="0x0947" PRODUCTNAME="Lifestyle">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2">
|
||||
<IMAGE SUBID="0" LENGTH="203977300" CRC="0x1858fa51" FILENAME="Update_ti_27.0.6.46330.5043500.marconidev.sm2.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch Stereo JC -->
|
||||
<DEVICE ID="0x0940" PRODUCTNAME="SoundTouch Stereo JC">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/l/sm2/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="98921512" CRC="0x07521bda" FILENAME="Update_ti_27.0.6.46330.5043500.lisa.sm2.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch SA-4 -->
|
||||
<DEVICE ID="0x0941" PRODUCTNAME="SoundTouch SA-4">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/l/sm2/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="98921512" CRC="0x07521bda" FILENAME="Update_ti_27.0.6.46330.5043500.lisa.sm2.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- Cinemate -->
|
||||
<DEVICE ID="0x0942" PRODUCTNAME="Cinemate">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/t/sm2/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="102700460" CRC="0xfbcab635" FILENAME="Update_ti_27.0.6.46330.5043500.triode.sm2.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- VideoWave (Production Keys) -->
|
||||
<DEVICE ID="0x0933" PRODUCTNAME="VideoWave">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/m/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="215402464" CRC="0xd48b1181" FILENAME="Update_ti_27.0.6.46330.5043500.marconiprod.scm.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- Lifestyle (Production Keys) -->
|
||||
<DEVICE ID="0x0934" PRODUCTNAME="Lifestyle">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/m/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="215402464" CRC="0xd48b1181" FILENAME="Update_ti_27.0.6.46330.5043500.marconiprod.scm.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- VideoWave (Production Keys) -->
|
||||
<DEVICE ID="0x093E" PRODUCTNAME="VideoWave">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/m/sm2/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="203977300" CRC="0x3f489bd5" FILENAME="Update_ti_27.0.6.46330.5043500.marconiprod.sm2.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- Lifestyle (Production Keys) -->
|
||||
<DEVICE ID="0x093F" PRODUCTNAME="Lifestyle">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/m/sm2/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="203977300" CRC="0x3f489bd5" FILENAME="Update_ti_27.0.6.46330.5043500.marconiprod.sm2.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- Lifestyle -->
|
||||
<DEVICE ID="0x094B" PRODUCTNAME="Lifestyle">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.5043530" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/Update.avu">
|
||||
<IMAGE SUBID="0" LENGTH="475186323" CRC="0x523be82b" FILENAME="Update_signed_27.0.6.5043530.avu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- Lifestyle -->
|
||||
<DEVICE ID="0x0948" PRODUCTNAME="Lifestyle">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2">
|
||||
<IMAGE SUBID="0" LENGTH="105878364" CRC="0xc0b3d401" FILENAME="Update_ti_27.0.6.46330.5043500.bardeen.sm2.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch 300 -->
|
||||
<DEVICE ID="0x0949" PRODUCTNAME="SoundTouch 300">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/g/sm2/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="102384736" CRC="0xed21efd3" FILENAME="Update_ti_27.0.6.46330.5043500.ginger.sm2.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch Wireless Link adapter -->
|
||||
<DEVICE ID="0x094A" PRODUCTNAME="SoundTouch Wireless Link adapter">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.6.46330.5043500" HTTPHOST="https://downloads.bose.com" URLPATH="ced/soundtouch/mr4_22097fe2" USBPATH="/ced/soundtouch/mr4_22097fe2/stu/s/sm2/Update.stu">
|
||||
<IMAGE SUBID="0" LENGTH="99445800" CRC="0x536e6d6f" FILENAME="Update_ti_27.0.6.46330.5043500.sm2.stu" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch App for Android -->
|
||||
<DEVICE ID="0x000A" PRODUCTNAME="SoundTouch App-A" SUPPORTEDOS="4.4.0">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.1" HTTPHOST="downloads.bose.com" URLPATH="/ced/soundtouch/mr4_22097fe2/">
|
||||
<IMAGE SUBID="0" LENGTH="23351636" CRC="0x425b2109" FILENAME="SoundTouch-release_27.0.1-3345-bafe54d.apk" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch App for iOS -->
|
||||
<DEVICE ID="0x000B" PRODUCTNAME="SoundTouch App-I" SUPPORTEDOS="8.0.0">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.1" HTTPHOST="downloads.bose.com" URLPATH="/ced/soundtouch/mr4_22097fe2/">
|
||||
<IMAGE SUBID="0" LENGTH="47413805" CRC="0xe4bf4961" FILENAME="SoundTouch-27.0.1-3498-699a15c.ipa" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch App for Mac (pre OS X 10.9) -->
|
||||
<DEVICE ID="0x000C" PRODUCTNAME="SoundTouch App-M" SUPPORTEDOS="mac_10_8">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.0" HTTPHOST="downloads.bose.com" URLPATH="/ced/soundtouch/mr4_22097fe2/">
|
||||
<IMAGE SUBID="0" LENGTH="117483653" CRC="0xd6ca482b" FILENAME="SoundTouch-app-installer-27.0.0-3377-1037583.dmg" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch App for Mac (OS X 10.9 & later) -->
|
||||
<DEVICE ID="0x000E" PRODUCTNAME="SoundTouch App-M" SUPPORTEDOS="mac_10_8">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.0" HTTPHOST="downloads.bose.com" URLPATH="/ced/soundtouch/mr4_22097fe2/">
|
||||
<IMAGE SUBID="0" LENGTH="117483653" CRC="0xd6ca482b" FILENAME="SoundTouch-app-installer-27.0.0-3377-1037583.dmg" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
<!-- SoundTouch App for PC -->
|
||||
<DEVICE ID="0x000D" PRODUCTNAME="SoundTouch App-W" SUPPORTEDOS="windows_6_0">
|
||||
<HARDWARE REVISION="00.01.00">
|
||||
<RELEASE REVISION="27.0.0.3377" HTTPHOST="downloads.bose.com" URLPATH="/ced/soundtouch/mr4_22097fe2/">
|
||||
<IMAGE SUBID="0" LENGTH="120307712" CRC="0x3e97da1f" FILENAME="SoundTouch-app-installer-27.0.0.3377.msi" />
|
||||
</RELEASE>
|
||||
</HARDWARE>
|
||||
</DEVICE>
|
||||
|
||||
</INDEX>
|
||||
@@ -0,0 +1,101 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<releases>
|
||||
<release revision="27.0.0">
|
||||
<feature>Fixed bugs and did some general cleaning up under the hood</feature>
|
||||
</release>
|
||||
<release revision="26.0.0">
|
||||
<feature>Fixed bugs and did some general cleaning up under the hood</feature>
|
||||
</release>
|
||||
<release revision="25.0.0">
|
||||
<feature>Airplay2 support arrives for SoundTouch Wireless Link adapter!</feature>
|
||||
<feature>Added improvements to the setup experience</feature>
|
||||
<feature>General bug fixes and improvements</feature>
|
||||
</release>
|
||||
<release revision="24.0.0">
|
||||
<feature>As usual, this release includes bug fixes and performance improvements</feature>
|
||||
</release>
|
||||
<release revision ="23.0.0">
|
||||
<feature platform="IOS">Added lots of under the hood changes to improve the app experience on iOS13</feature>
|
||||
<feature platform="ANDROID">Fixed an issue with Wi-Fi setup on certain Android devices</feature>
|
||||
<feature>Additional bug fixes and performance improvements</feature>
|
||||
</release>
|
||||
<release revision ="22.0.0">
|
||||
<feature>We've added RadioPlayer to our family of music services! Enjoy thousands of regional stations and on demand programs right at your fingertips. Available in select regions</feature>
|
||||
<feature>You can now disable the automatic power save mode in the app for your SoundTouch 10, SoundTouch 20 and SoundTouch 30</feature>
|
||||
<feature>Additional bug fixes & enhancements</feature>
|
||||
</release>
|
||||
<release revision ="21.0.0">
|
||||
<feature>Save more music — you can now save Favorites along with your 6 presets</feature>
|
||||
<feature>We improved Spotify search so you can get grooving faster</feature>
|
||||
<feature>It's now easier to access Recently Played</feature>
|
||||
<feature>Little tweaks here and there to make the app better for you</feature>
|
||||
</release>
|
||||
<release revision="20.0.0">
|
||||
<feature>Say hello to TuneIn (and goodbye to Internet Radio)</feature>
|
||||
<feature>Easily browse through your favorite artists in Spotify</feature>
|
||||
<feature>We made it easier to create an account and reset your password</feature>
|
||||
<feature>General improvements made with our special app-tuning forks</feature>
|
||||
</release>
|
||||
<release revision="19.0.0">
|
||||
<feature>Security related updates to improve application configuration and operation</feature>
|
||||
<feature>Many other bug fixes and enhancements</feature>
|
||||
</release>
|
||||
<release revision="18.0.0">
|
||||
<feature>By updating, you agree to our new Privacy Policy and Terms of Use available at https://worldwide.bose.com/privacypolicy and https://worldwide.bose.com/termsofuse</feature>
|
||||
<feature>Security related updates to improve application configuration and operation</feature>
|
||||
<feature>We tuned the app to include some major performance and stability improvements</feature>
|
||||
</release>
|
||||
<release revision="17.0.0">
|
||||
<feature>Enhanced broadcasting performance of AUX/wired input to other SoundTouch speakers</feature>
|
||||
<feature>Search enabled in Amazon Music</feature>
|
||||
<feature>Many other bug fixes and enhancements</feature>
|
||||
</release>
|
||||
<release revision="16.0.0">
|
||||
<feature><![CDATA[By updating the app, you agree to our new Privacy Policy, available at <a href="https://www.soundtouch.com/privacy">SoundTouch.com/privacy</a>]]></feature>
|
||||
<feature>Broadcasting of AUX/wired input to other SoundTouch speakers</feature>
|
||||
<feature>Volume and grouping enhancements</feature>
|
||||
<feature>New "Just for You" section</feature>
|
||||
<feature>Many other bug fixes and enhancements</feature>
|
||||
</release>
|
||||
<release revision="15.0.0">
|
||||
<feature>As usual, this release includes bug fixes and performance improvements</feature>
|
||||
</release>
|
||||
<release revision="14.0.0">
|
||||
<feature>We made your SoundTouch® experience better, with a completely redesigned app that's easier to use and nicer to look at</feature>
|
||||
<feature>Stereo pairing for SoundTouch® 10 speakers</feature>
|
||||
<feature>QQ Music QPlay streaming support (China only)</feature>
|
||||
<feature platform="IOS">Now you can control your speaker from your Apple Watch® – just open the Watch app and add SoundTouch®</feature>
|
||||
<feature platform="IOS">There’s a new SoundTouch® widget available for iOS – add it in the Today View so you can control your speaker even while your device is locked</feature>
|
||||
<feature>We made speaker selection and volume control more reliable</feature>
|
||||
<feature>The app now shows Pandora’s new logo</feature>
|
||||
<feature>Plus, we fixed some bugs and made things more stable</feature>
|
||||
</release>
|
||||
<release revision="13.0.0">
|
||||
<feature>Updated music library experience with faster navigation, easier search, and more album art</feature>
|
||||
<feature platform="ANDROID">Improved Android Wear support</feature>
|
||||
<feature>Bug fixes</feature>
|
||||
</release>
|
||||
<release revision="12.0.0">
|
||||
<feature>Added Amazon Prime Music (US Only)</feature>
|
||||
<feature platform="ANDROID">Android Wear notifications support</feature>
|
||||
<feature platform="ANDROID">Android lock-screen controls</feature>
|
||||
<feature>SiriusXM® Business Account support</feature>
|
||||
<feature>Over 30 bug fixes</feature>
|
||||
</release>
|
||||
<release revision="7.0.0">
|
||||
<feature>Support for additional music services (where available)</feature>
|
||||
<feature>Search for a track, album, or artist in your stored music library</feature>
|
||||
<feature>Adjust the bass performance of your SoundTouch® system</feature>
|
||||
<feature>Additional bug fixes and performance improvements</feature>
|
||||
</release>
|
||||
<release revision="6.0.0">
|
||||
<feature>Enables wireless setup of SoundTouch® products</feature>
|
||||
<feature>Faster connection to speakers on your network</feature>
|
||||
</release>
|
||||
<release revision="4.0.0">
|
||||
<feature>Enhanced detection of speakers on your network</feature>
|
||||
</release>
|
||||
<release revision="3.0.0">
|
||||
<feature>Improved system discovery</feature>
|
||||
</release>
|
||||
</releases>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<page id="bose_account_create_1"><item><topic>Why do I need to create an account?</topic><answer><![CDATA[<p>A SoundTouch<sup>®</sup> account is required to keep track of your speakers, presets and music service. In addition, an account helps us better support your speaker and troubleshoot problems.</p> <p>If you are setting up multiple SoundTouch<sup>®</sup> speakers, we strongly recommend that you set them up on the same SoundTouch<sup>®</sup> account. Also, any time you install the SoundTouch<sup>®</sup> app on another mobile device or computer, you are required to sign in using your SoundTouch<sup>®</sup> account info.</p>]]></answer></item><item><topic>Why do I have to provide my email address?</topic><answer><![CDATA[<p>Each SoundTouch<sup>®</sup> account is uniquely identified by an email address. Notifications of software and service updates are sent to this address. When you provide your email address, you can choose (or decline) to receive emails from Bose<sup>®</sup> about new products, events and other announcements. Please read our privacy policy to learn more about how we use your email address by selecting <strong>Settings > About > LEGAL</strong>.</p> <p>If you prefer not to provide your email address, you can set up your speaker anonymously by providing a single-purpose or even non-working email address. In this case, your speaker will continue to receive system software updates, but you will not receive email notifications explaining the new features when these updates are available.</p>]]></answer></item><item><topic>Is there a minimum character or format requirement for the password?</topic><answer><![CDATA[<p>Your password must be at least six characters in length. The password field is case sensitive.</p>]]></answer></item><item><topic>Why should I provide my name and address?</topic><answer><![CDATA[<p>We use your name and address to improve your customer service experience should you need assistance. Please read our privacy policy to understand other ways we may use your name and address by selecting <strong>Settings > About > LEGAL.</strong></p>]]></answer></item></page>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<page id="gabbo_ios_settings"><item><topic>How do I change my network?</topic><answer><![CDATA[<p>Change your network from the Settings menu on your mobile device.</p><ol><li><p>On your mobile device, tap the <strong>Home</strong> button.</p></li><li><p>Tap <strong>Settings > Wi-Fi</strong>.</p> <p><strong>Note</strong>: By default, the Settings menu is on the Home screen.</p></li><li><p>Select the Wi-Fi<sup>®</sup> network starting with <strong>Bose</strong>.</p></li><li><p>Tap the <strong>Home</strong> button.</p></li><li><p>Tap the SoundTouch<sup>®</sup> icon to return to the SoundTouch<sup>®</sup> app.</p></li></ol>]]></answer></item><item><topic>Why do I need to connect to the "Bose" Wi-Fi<sup>®</sup> network?</topic><answer><![CDATA[<p>Connecting to the "Bose" Wi-Fi<sup>®</sup> network enables your speaker to be set up on your home Wi-Fi<sup>®</sup> network. Connecting to this network is temporary. After you set up the speaker, you reconnect to your home network.</p>]]></answer></item><item><topic>I can't find the "Bose" Wi-Fi<sup>®</sup> network.</topic><answer><![CDATA[<p>Make sure that you're looking for the Wi-Fi<sup>®</sup> network starting with Bose. It may take up to 30 seconds for the network to appear on the list.</p><p>If the network does not appear after 30 seconds, select <strong>I Don't See This Network</strong> to put the system into setup mode and continue with setup.</p>]]></answer></item><item><topic>How do I return to the app from my mobile device's Settings menu?</topic><answer><![CDATA[<ol><li><p>On your mobile device, tap the <strong>Home</strong> button.</p><p>On the Home screen, tap the SoundTouch<sup>®</sup> icon.</p></li></ol>]]></answer></item></page>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<page id="gabbo_recovery_lisa"><item><topic>The Wi-Fi<sup>®</sup> indicator isn't glowing amber. What do I do now?</topic><answer><![CDATA[<p>If the Wi-Fi<sup>®</sup> indicator is not glowing solid amber, your system is not in setup mode.</p><ol><li><p>Power on your system.</p></li><li><p>Press and hold the <strong>Control</strong> button on the back of the SoundTouch<sup>®</sup> wireless adapter for 1-8 seconds.</p> <p><strong>Note</strong>: If the Wi-Fi<sup>®</sup> indicator does not glow solid amber, press and hold the <strong>Control</strong> button again, making sure to release the button before 8 seconds elapses.</p></li></ol>]]></answer></item><item><topic>Where is the Control button?</topic><answer><![CDATA[<p>The Control button is on the SoundTouch<sup>®</sup> wireless adapter's connector panel.</p>]]></answer></item><item><topic>Where is the Wi-Fi<sup>®</sup> indicator?</topic><answer><![CDATA[<p>The Wi-Fi<sup>®</sup> indicator is on the SoundTouch<sup>®</sup> wireless adapter's connector panel.</p>]]></answer></item></page>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<page id="gabbo_recovery_nelson"><item><topic>The Wi-Fi<sup>®</sup> indicator isn't glowing amber. What do I do now?</topic><answer><![CDATA[<p>If the Wi-Fi<sup>®</sup> indicator is not glowing solid amber, your system is not in setup mode.</p><ol><li><p>Power on your system.</p></li><li><p>Press and hold the <strong>Control</strong> button on the back of the SoundTouch<sup>®</sup> pedestal for 1-8 seconds.</p> <p>The Wi-Fi<sup>®</sup> indicator glows solid amber.</p> <p>The message <em>SETUP SEE INSTRUCTIONS</em> appears on the display.</p> <p>Your system is now in setup mode.</p></li></ol><p><strong>Note</strong>: If the Wi-Fi<sup>®</sup> indicator does not glow solid amber and the message does not appear on the display, press and hold the <strong>Control</strong> button again, making sure to release the button before 8 seconds elapses.</p>]]></answer></item><item><topic>Where is the Control button?</topic><answer><![CDATA[<p>The Control button is on the SoundTouch<sup>®</sup> pedestal’s connector panel.</p>]]></answer></item><item><topic>Where is the Wi-Fi<sup>®</sup> indicator?</topic><answer><![CDATA[<p>The Wi-Fi<sup>®</sup> indicator is on the SoundTouch<sup>®</sup> pedestal’s connector panel.</p>]]></answer></item></page>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<page id="gabbo_recovery_select_system">
|
||||
<item>
|
||||
<topic>What is the name of my speaker?</topic>
|
||||
<answer>
|
||||
<![CDATA[<p>Check the carton or the owner's guide that shipped with your speaker. You may also find the name of the speaker on a label on the back or bottom of the speaker.</p>]]>
|
||||
</answer></item>
|
||||
<item>
|
||||
<topic>What is the "Bose" Wi-Fi<sup>®</sup> network?</topic>
|
||||
<answer>
|
||||
<![CDATA[<p>Your speaker has its own built-in Wi-Fi network that you use to set up your speaker. You will temporarily connect to this network on the device you are using, set the speaker up on your network and then reconnect to your home Wi-Fi network.</p>]]>
|
||||
</answer>
|
||||
</item>
|
||||
</page>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<page id="gabbo_recovery_smt"><item><topic>The Wi-Fi<sup>®</sup> indicator isn't glowing amber. What do I do now?</topic><answer><![CDATA[<p>If the Wi-Fi<sup>®</sup> indicator is not glowing solid amber, your speaker is not in setup mode.</p><ol><li><p>Power on your speaker.</p></li><li><p>On the button pad, press and hold the <strong>2</strong> and <strong>Volume -</strong> buttons until the countdown reaches 1 and a message similar to "Setup" appears on the display.</p> <p>The Wi-Fi<sup>®</sup> indicator glows solid amber.</p> <p>Your system is now in Setup mode.</p></li></ol>]]></answer></item><item><topic>Where is the Wi-Fi<sup>®</sup> indicator?</topic><answer><![CDATA[<p>The Wi-Fi<sup>®</sup> indicator is on the front of the speaker.</p>]]></answer></item></page>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<page id="name_device"><item><topic>Why should I name my speaker?</topic><answer><![CDATA[<p>Naming the speaker makes it easy to recognize in the app when you have multiple speakers. You can use a name that identifies the space where the speaker is placed, for example, such as Living Room.</p>]]></answer></item><item><topic>Can I rename this speaker later?</topic><answer><![CDATA[<p>Yes, you can rename the speaker from the Settings menu. Select <strong>Settings > Speaker Settings</strong>, then select your speaker.</p>]]></answer></item></page>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<page id="prompt_other_devices"><item><topic>Can I set up another speaker later?</topic><answer><![CDATA[<p>Yes. Select <strong>Settings > Add or Reconnect Speaker</strong>.</p>]]></answer></item><item><topic>How many speakers can I add to my network?</topic><answer><![CDATA[<p>You can add as many speakers to your network as determined by the capacity of your home Wi-Fi<sup>®</sup> network.</p>]]></answer></item></page>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<page id="setup_done"/>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<page id="wifi_or_ethernet_ask"><item><topic>How should I connect my speaker to my network?</topic><answer><![CDATA[<p>You can connect your speaker to your network using a Wi-Fi<sup>®</sup> or Ethernet connection. If you select Ethernet, make sure the Ethernet cable from your router can reach your speaker.</p> <p><strong>Note</strong>: If you are setting up a SoundTouch<sup>®</sup> 10 speaker, SoundTouch<sup>®</sup> Wireless Link or SoundTouch<sup>®</sup> Portable Wi-Fi<sup>®</sup> music system, you must select <strong>WI-FI</strong>.</p>]]></answer></item><item><topic>Will there be a difference in performance between a wired and a wireless setup?</topic><answer><![CDATA[<p>Performance varies depending on the number of devices on your network and how the devices are connected. A wireless connection provides more flexibility when placing your system. A wired connection is better when your wireless router's signal is weak or can't be received.</p>]]></answer></item></page>
|
||||
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 4.6 KiB |
|
After Width: | Height: | Size: 2.6 KiB |