From 4759e15be270420dfee64afc121cc819b030eb2f Mon Sep 17 00:00:00 2001 From: Tumelo Rathebe <96668318+AlphadogRSA@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:57:21 +0200 Subject: [PATCH 1/7] Add opt-in Hush TV companion and signed native-session bridge --- .github/workflows/test.yml | 38 +++++ .gitignore | 2 + .gitmodules | 3 + HANDOFF.md | 6 +- HUSH.md | 39 +++++ README.md | 8 +- assets/HUSH-NOTICE.txt | 12 ++ build.ps1 | 10 +- docs/superpowers/plans/2026-10-27-hush-tv.md | 43 +++++ .../specs/2026-10-27-hush-tv-design.md | 9 ++ hush/build.ps1 | 49 ++++++ .../java/io/coldmew/hush/TvActivity.java | 94 +++++++++++ .../java/io/coldmew/hush/TvBridge.java | 98 ++++++++++++ .../java/io/coldmew/hush/TvReceiver.java | 23 +++ .../java/io/coldmew/hush/TvService.java | 33 ++++ .../java/io/coldmew/hush/TvSkipPolicy.java | 16 ++ hush/prepare.py | 147 ++++++++++++++++++ hush/tests/TvSkipPolicyTest.java | 18 +++ hush/tests/test_prepare.py | 35 +++++ hush/upstream | 1 + install.ps1 | 9 +- revanced/build.gradle.kts | 4 +- .../kotlin/dev/aurora/patches/TvPatches.kt | 13 +- src/dev/aurora/tvpatch/Hooks.java | 37 ++++- src/dev/aurora/tvpatch/HushClient.java | 50 ++++++ src/dev/aurora/tvpatch/SleepDeadline.java | 7 + tests/SleepDeadlineTest.java | 14 ++ 27 files changed, 801 insertions(+), 17 deletions(-) create mode 100644 .gitmodules create mode 100644 HUSH.md create mode 100644 assets/HUSH-NOTICE.txt create mode 100644 docs/superpowers/plans/2026-10-27-hush-tv.md create mode 100644 docs/superpowers/specs/2026-10-27-hush-tv-design.md create mode 100644 hush/build.ps1 create mode 100644 hush/overlay/java/io/coldmew/hush/TvActivity.java create mode 100644 hush/overlay/java/io/coldmew/hush/TvBridge.java create mode 100644 hush/overlay/java/io/coldmew/hush/TvReceiver.java create mode 100644 hush/overlay/java/io/coldmew/hush/TvService.java create mode 100644 hush/overlay/java/io/coldmew/hush/TvSkipPolicy.java create mode 100644 hush/prepare.py create mode 100644 hush/tests/TvSkipPolicyTest.java create mode 100644 hush/tests/test_prepare.py create mode 160000 hush/upstream create mode 100644 src/dev/aurora/tvpatch/HushClient.java create mode 100644 src/dev/aurora/tvpatch/SleepDeadline.java create mode 100644 tests/SleepDeadlineTest.java diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fb4b359..3fc0620 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -30,6 +30,10 @@ jobs: java -ea -cp test-classes AudioSessionsTest javac -d test-classes src/dev/aurora/tvpatch/AudioEffectPlan.java tests/AudioEffectPlanTest.java java -ea -cp test-classes AudioEffectPlanTest + javac -d test-classes src/dev/aurora/tvpatch/SleepDeadline.java tests/SleepDeadlineTest.java + java -ea -cp test-classes SleepDeadlineTest + javac -d test-classes hush/overlay/java/io/coldmew/hush/TvSkipPolicy.java hush/tests/TvSkipPolicyTest.java + java -ea -cp test-classes TvSkipPolicyTest - name: Test modular fingerprints run: bash revanced/gradlew -p revanced testFingerprints - name: Check source tools @@ -54,3 +58,37 @@ jobs: node tests/presentation.test.cjs node tests/theme-regression.test.cjs node tests/presentation-performance.test.cjs + hush-tv: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + - uses: android-actions/setup-android@v3 + - name: Prepare pinned Hush TV sources + run: | + python3 -m unittest discover -s hush/tests -v + python3 hush/prepare.py + - name: Install pinned Android build platform + run: sdkmanager 'platforms;android-35' 'build-tools;35.0.0' + - name: Compile the complete TV extension and build its DEX + run: | + mkdir -p .tools/extension-classes .tools/extension-dex + javac -encoding UTF-8 -source 8 -target 8 -cp "$ANDROID_HOME/platforms/android-35/android.jar" -d .tools/extension-classes src/dev/aurora/tvpatch/*.java + jar cf .tools/extension.jar -C .tools/extension-classes . + "$ANDROID_HOME/build-tools/35.0.0/d8" --min-api 26 --lib "$ANDROID_HOME/platforms/android-35/android.jar" --output .tools/extension-dex .tools/extension.jar + - name: Test and build the Hush companion + env: + HUSH_SIGNING: /tmp/no-upstream-signing.properties + run: bash hush/build/android/gradlew -p hush/build/android testDebugUnitTest assembleRelease + - uses: actions/upload-artifact@v4 + with: + name: Hush-TV-unsigned + path: | + hush/build/android/app/build/outputs/apk/release/app-release-unsigned.apk + hush/build/android/app/build/outputs/mapping/release/mapping.txt + if-no-files-found: error diff --git a/.gitignore b/.gitignore index 9e217f6..44c1cff 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,5 @@ __pycache__/ .jvm-temp/ .gradle/ !revanced/gradle/wrapper/gradle-wrapper.jar + +!hush/upstream/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..e1f0eaf --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "hush/upstream"] + path = hush/upstream + url = https://github.com/coldMEW/Hush.git diff --git a/HANDOFF.md b/HANDOFF.md index 253d94b..355e5cd 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1,6 +1,10 @@ # Handoff -## Current release: 0.5 +## Current source version: 0.6 (Hush TV integration; device verification pending) + +The Hush feature is in the TV menu. A pinned upstream companion, reproducible TV adaptations and same-key build/install support are under `hush/`; see HUSH.md. Native session/ad signals use a signature-protected bridge. The companion keeps restart recovery alive in a foreground service; player-local muting remains the fallback. The existing 0.5 device observations below are historical and do not verify 0.6. Original proprietary APKs and the retained private signing key are not available in this workspace, so no new signed Spotify installation set or TV deployment is claimed. + +## Previously device-tested release: 0.5 The 0.5 follow-up fixes themes against verified TV class selectors, expands promotion/Upgrade hiding and optimizes DOM scanning, playback callbacks, dialog cleanup and DSP writes. See VERIFICATION.md for the measured checks. It keeps all 0.4 functions and persisted settings. The remote theme cycle and Spotify-only audio activation were observed after installing 0.5. diff --git a/HUSH.md b/HUSH.md new file mode 100644 index 0000000..be7cde6 --- /dev/null +++ b/HUSH.md @@ -0,0 +1,39 @@ +# Hush · Spotify+ TV + +Version 0.6 adds **Hush · ad-break skipping** to the TV remote menu. It opens an optional companion adapted from [coldMEW/Hush 2.0.2](https://github.com/coldMEW/Hush), pinned to `4e9ded397338de5c69b1784c636feb3d34a8de01`. + +Hush attempts to drop an ad break by restarting Spotify and resuming its new media session. Upstream measurements are for the phone client; they do not establish that Spotify TV will drop ads, keep the queue, or recover in the same time. This TV integration needs testing on the actual TV. Keep **Mute detected ads** on for player-local muting when restarting is unavailable or fails. A failed automatic attempt imposes a two-minute cooldown, with one attempt per break until real music resumes. + +## Build and install + +1. Clone this repository with `git clone --recurse-submodules`, or run `git submodule update --init --recursive` in an existing checkout. +2. Run the existing `build.ps1` with the original four Spotify TV 1.134.2 APKs, Android SDK 35/build-tools 35.0.0, a JDK 17 installation, and the same retained signing key used for your existing TV installation. Gradle and Maven dependency access is required. The build now also creates `signed/Hush-TV.apk`. Set `SPTV_STORE_PASSWORD` and, if needed, `SPTV_KEY_PASSWORD` outside the repository. `-WithoutHush` builds only the four Spotify splits. +3. Run `install.ps1 -ApkDirectory -Serial `. This installs the companion first and then updates all four Spotify splits. There is no uninstall or data reset. Use `-WithoutHush` for a TV-only update. +4. In Spotify+ TV, press Menu or hold OK, choose **Hush · ad-break skipping**, then enable Hush. +5. Set up Hush's own helper using Wireless debugging on Android 11+, or authorize an already-running Shizuku on Android 8+. The original setup screens remain available; some TV firmware lacks the required Wireless debugging/pairing UI. On those TVs use Shizuku started with its documented computer/ADB setup. Helper availability after a reboot must be checked again. +6. Return to Spotify and start playback. The status screen should report a connected session. **Test Spotify restart** asks before interrupting playback. Check that the correct playlist resumes. Then test with a real ad. + +The GitHub Actions `Hush-TV-unsigned` artifact is an unsigned companion build. It must be signed using your TV key before installation. It is not an installable update to the proprietary Spotify APK set. No original APKs or signing keys are stored in this repository. + +## What crosses between the apps + +The extension sends its own media-session token, native `is_ad_playing` flag, monotonic timestamp and sleep deadline to an explicit receiver. Both directions check the matching signing identity; the receiver also requires a signature permission. Old signals are rejected. No credentials, account entitlements or arbitrary shell commands are transmitted. The companion uses its native-session capability instead of requiring notification access on TV. + +Hush is off by default. Enable/disable it in its TV screen. The companion never uses the upstream phone-wide ad-mute path: muting remains inside Spotify's player. Resume kicks target only Spotify's forwarded media session. The TV sleep deadline survives a Spotify process restart and is cleared after a TV reboot. If it expires during recovery, Hush stops attempting to resume playback. + +DNS filtering is not required and stays off by default. The upstream optional VPN implementation remains in the separate companion; it is not activated by the TV feature or build/install scripts. + +## Source and license + +The upstream `hush/upstream` gitlink is unmodified. `hush/prepare.py` verifies that exact commit and clean tracked source, copies only tracked Android files into a new build directory, retargets Spotify's package, replaces the global-mute watcher path, connects native TV sessions, and adds `hush/overlay`. All adaptation is visible in these tracked files. Generated source is under `hush/build/android` and ignored by git. + +Hush and the companion adaptations are GPL-3.0. The companion embeds the full upstream license and a source notice. The independent TV protocol adapter remains part of the MIT extension; no Hush implementation is linked into it. The ReVanced host retains its existing GPL license. None of these licenses relicense Spotify binaries. + +## Device checks still required + +- Pairing/helper setup and D-pad navigation on the actual firmware. +- New-session delivery and playback recovery after a test restart and a real ad. +- Playlist/queue behavior, ad-return failure, and the two-minute failure cooldown. +- Local mute restoration and whether EQ reattaches to the new Spotify audio session. +- Sleep expiry before/during restart, a background Spotify session, helper loss, and reboot recovery. +- Same-key updates preserve existing pairing, settings, lyrics and app data. diff --git a/README.md b/README.md index f473501..b2a0beb 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,10 @@ -# Spotify+ TV 0.5 +# Spotify+ TV 0.6 · Hush integration + +Adds **Hush · ad-break skipping** to the remote menu, backed by a separately installed Hush TV companion. The companion is opt-in, uses the native TV ad flag and matching-signature session bridge, and keeps restart recovery outside Spotify’s process. Existing local ad muting remains the fallback. The TV sleep timer now survives Spotify process restarts. See [HUSH.md](HUSH.md) for setup, builds, GPL source attribution and required TV checks. + +This is a source integration; actual TV ad skipping and queue recovery still require device verification. + +## Version 0.5 presentation improvements Version 0.5 fixes themes across the actual TV interface: class-based focus outlines, primary actions, playback progress, playing-track labels and context menus. Aurora, Midnight and Ember colors now use the TV selectors verified on the installed UI; Spotify Original restores the original colors. Artwork/layout and existing player functions remain in place. diff --git a/assets/HUSH-NOTICE.txt b/assets/HUSH-NOTICE.txt new file mode 100644 index 0000000..a77f960 --- /dev/null +++ b/assets/HUSH-NOTICE.txt @@ -0,0 +1,12 @@ +Hush companion integration + +The MIT Spotify+ TV extension communicates with a separately installed Hush TV companion. +The companion is derived from coldMEW/Hush 2.0.2, commit +4e9ded397338de5c69b1784c636feb3d34a8de01, under GPL-3.0. + +Upstream: https://github.com/coldMEW/Hush +Adaptation, pinned source, modifications and build instructions: +https://github.com/AlphadogRSA/spotifyplus-tv-patch/tree/feat/hush-tv/hush + +The companion includes the full upstream GPL license and a source notice. +The companion's license does not relicense Spotify's proprietary binaries. diff --git a/build.ps1 b/build.ps1 index b16ca34..bdca1bc 100644 --- a/build.ps1 +++ b/build.ps1 @@ -6,7 +6,8 @@ param( [Parameter(Mandatory)][string]$KeyStore, [Parameter(Mandatory)][string]$OutputDirectory, [string]$KeyAlias = 'androiddebugkey', - [string]$GradleExecutable + [string]$GradleExecutable, + [switch]$WithoutHush ) $ErrorActionPreference = 'Stop' if (-not $env:SPTV_STORE_PASSWORD) { throw 'Set SPTV_STORE_PASSWORD for your own keystore; never commit the key or password.' } @@ -40,7 +41,7 @@ Check-Exit 'Verified patcher download' if (-not $GradleExecutable) { $GradleExecutable = Join-Path $patchProject 'gradlew.bat' } & $GradleExecutable -p $patchProject testFingerprints bundle "-PextensionDex=$(Join-Path $out 'dex/classes.dex')" Check-Exit 'Kotlin patch compilation and fingerprint tests' -$bundle = Join-Path $patchProject 'build/libs/spotifyplus-tv-0.5.rvp' +$bundle = Join-Path $patchProject 'build/libs/spotifyplus-tv-0.6.rvp' $classpath = $bundle + [IO.Path]::PathSeparator + (Join-Path $patchProject '.tools/revanced-cli-6.0.0-all.jar') & (Join-Path $jdk 'bin/java.exe') -cp $classpath dev.aurora.patches.RunnerKt apply $bundle (Join-Path $original 'base.apk') (Join-Path $out 'patched-unsigned.apk') (Join-Path $out 'patch') (Join-Path $tools 'aapt2.exe') Check-Exit 'Modular patching and APK rebuild' @@ -58,5 +59,8 @@ foreach ($entry in $hashes.PSObject.Properties) { & (Join-Path $tools 'apksigner.bat') verify --min-sdk-version 26 $signed Check-Exit 'Signature verification' } +if (-not $WithoutHush) { + & (Join-Path $PSScriptRoot 'hush/build.ps1') -AndroidSdk $sdk -JavaHome $jdk -KeyStore $signingKey -KeyAlias $KeyAlias -OutputApk (Join-Path $out 'signed/Hush-TV.apk') +} Compress-Archive -Path (Join-Path $out 'signed/*.apk') -DestinationPath (Join-Path $out 'SpotifyPlus-TV-patched.zip') -Write-Output "Verified four-APK installation set: $(Join-Path $out 'signed')" +Write-Output "Verified installation set (Spotify splits plus optional Hush companion): $(Join-Path $out 'signed')" diff --git a/docs/superpowers/plans/2026-10-27-hush-tv.md b/docs/superpowers/plans/2026-10-27-hush-tv.md new file mode 100644 index 0000000..fd6d039 --- /dev/null +++ b/docs/superpowers/plans/2026-10-27-hush-tv.md @@ -0,0 +1,43 @@ +# Hush TV Implementation Plan + +> **For agentic workers:** Use superpowers:executing-plans to implement task-by-task. + +**Goal:** Add opt-in Hush restart skipping to the existing TV application. + +**Architecture:** A pinned upstream Hush companion receives trusted native ad flags and session tokens from the MIT TV extension. The companion owns restart/recovery; the extension retains player-local mute and persists its timer. + +**Tech Stack:** Java 8 extension, Java 17 Android companion, Android SDK 35, Python preparation script, Kotlin ReVanced patches. + +**Spec:** ../specs/2026-10-27-hush-tv-design.md + +## Global Constraints +- Spotify TV 1.134.2; Android 8+; same signing key for companion and TV app. +- Pin upstream 4e9ded397338de5c69b1784c636feb3d34a8de01; retain GPL notices. +- No global-volume mute, arbitrary external commands, private keys or original APKs in git. + +## Review Focus +- Duplicate native callbacks must not trigger restart loops. +- Late/stale tokens must not replace an active new session. +- Missing companion or helper leaves player-local muting usable. +- Sleep deadline expiry must suppress restart and survive Spotify process death. +- Signature checks must guard both incoming commands and outgoing session tokens. + +### Task 1: Companion preparation and skip policy +Files: `hush/prepare.py`, `hush/overlay/`, `hush/tests/`, upstream gitlink. +Interfaces: `prepare(destination)` creates an adapted Android project; `TvSkipPolicy.shouldSkip(...)` latches attempts until real music resumes. +- [ ] Add and run failing preparation and policy tests. +- [ ] Implement reproducible pinned preparation, native-signal receiver, remote setup and session adapter around Hush's skipper. +- [ ] Run preparation/policy tests and Android Gradle tests/build. + +### Task 2: TV integration and timer continuity +Files: `HushClient.java`, `Hooks.java`, `SleepDeadline.java`, manifest patch, `tests/SleepDeadlineTest.java`. +Interfaces: `HushClient.signal(context, token, ad, sleepAt)` sends trusted state; `HushClient.open(activity)` opens companion; `SleepDeadline` validates persisted deadlines. +- [ ] Test deadline expiry and restart restoration before implementation. +- [ ] Add companion launch, session/ad forwarding and persisted timer. +- [ ] Compile extension and run original deterministic/presentation tests. + +### Task 3: Build, installation, documentation and CI +Files: `build.ps1`, `install.ps1`, Hush build script, `.github/workflows/test.yml`, `HUSH.md`, notices/handoff. +- [ ] Build/sign companion with same retained key; install before Spotify splits, with no uninstall/data reset. +- [ ] CI prepares pinned upstream, runs all companion unit tests and builds an APK artifact. +- [ ] Record measured checks separately from pending device tests; review diff and publish a reviewable PR. diff --git a/docs/superpowers/specs/2026-10-27-hush-tv-design.md b/docs/superpowers/specs/2026-10-27-hush-tv-design.md new file mode 100644 index 0000000..da17c10 --- /dev/null +++ b/docs/superpowers/specs/2026-10-27-hush-tv-design.md @@ -0,0 +1,9 @@ +# Hush support for Spotify+ TV + +The user approved adding Hush as a TV app feature, using a companion to survive Spotify restarts. Add a remote-friendly Hush menu entry and an independently installed companion derived from coldMEW/Hush 2.0.2 at `4e9ded397338de5c69b1784c636feb3d34a8de01`. Preserve themes, lyrics, EQ and player-local muting. Persist the TV sleep deadline across process restarts. + +The companion uses Hush's existing helper/Shizuku restart engine. TV native ad flags and own-session tokens cross an explicit, signature-protected receiver; both APKs must be signed with the user's existing key. No arbitrary shell commands or account changes are added. Native session forwarding avoids depending on TV notification access. Restart skipping is opt-in, deduplicated, and falls back to existing local muting when unavailable. Never use Hush's phone-wide volume mute on TV. + +Approaches considered: embedding everything loses the helper on each Spotify restart; a separately signed companion survives and keeps GPL code separate from the MIT extension. The user chose the companion approach. Keep upstream as a pinned submodule and apply explicit reproducible TV changes in a build preparation script, with attribution and GPL source available. Do not copy GPL implementation into the MIT extension. + +The first version exposes the existing Hush wireless-debugging setup and Shizuku authorization from a D-pad screen; device-specific pairing and TV restart behavior require real-device checks. DNS remains off by default and is available only in advanced upstream settings. CI builds the companion; rebuilding the proprietary Spotify splits still requires the user's original four APKs and private key, neither available here. diff --git a/hush/build.ps1 b/hush/build.ps1 new file mode 100644 index 0000000..495a301 --- /dev/null +++ b/hush/build.ps1 @@ -0,0 +1,49 @@ +param( + [Parameter(Mandatory)][string]$AndroidSdk, + [Parameter(Mandatory)][string]$JavaHome, + [Parameter(Mandatory)][string]$KeyStore, + [Parameter(Mandatory)][string]$OutputApk, + [string]$KeyAlias = 'androiddebugkey' +) +$ErrorActionPreference = 'Stop' +if (-not $env:SPTV_STORE_PASSWORD) { throw 'Set SPTV_STORE_PASSWORD for the same private key used by Spotify+ TV.' } +if (Test-Path -LiteralPath $OutputApk) { throw 'OutputApk must be new.' } +$sdk = (Resolve-Path -LiteralPath $AndroidSdk).Path +$jdk = (Resolve-Path -LiteralPath $JavaHome).Path +$key = (Resolve-Path -LiteralPath $KeyStore).Path +$tools = Join-Path $sdk 'build-tools/35.0.0' +$project = Join-Path $PSScriptRoot 'build/android' +function Check-Exit([string]$Stage) { if ($LASTEXITCODE -ne 0) { throw "$Stage failed ($LASTEXITCODE)" } } +$oldJava = $env:JAVA_HOME +$oldSdk = $env:ANDROID_HOME +$oldSigning = $env:HUSH_SIGNING +try { + $env:JAVA_HOME = $jdk + $env:ANDROID_HOME = $sdk + # Keep upstream signing config out of this build; sign explicitly using the TV key below. + $env:HUSH_SIGNING = Join-Path $PSScriptRoot 'build/no-upstream-signing.properties' + if (Test-Path -LiteralPath $env:HUSH_SIGNING) { throw 'Unexpected upstream signing properties file; remove it first.' } + git -C $PSScriptRoot submodule update --init --recursive -- upstream + Check-Exit 'Pinned Hush checkout' + # This is a generated build directory only, never the pinned source or signing material. + if (Test-Path -LiteralPath $project) { Remove-Item -LiteralPath $project -Recurse -Force } + python (Join-Path $PSScriptRoot 'prepare.py') --output $project + Check-Exit 'TV adaptation' + & (Join-Path $project 'gradlew.bat') -p $project testDebugUnitTest assembleRelease + Check-Exit 'Hush tests and Android build' + $unsigned = Join-Path $project 'app/build/outputs/apk/release/app-release-unsigned.apk' + $aligned = Join-Path $PSScriptRoot 'build/Hush-TV-aligned.apk' + & (Join-Path $tools 'zipalign.exe') -P 16 -f 4 $unsigned $aligned + Check-Exit 'Hush alignment' + $signArgs = @('sign','--ks',$key,'--ks-key-alias',$KeyAlias,'--ks-pass','env:SPTV_STORE_PASSWORD','--out',$OutputApk) + if ($env:SPTV_KEY_PASSWORD) { $signArgs += @('--key-pass','env:SPTV_KEY_PASSWORD') } + $signArgs += $aligned + & (Join-Path $tools 'apksigner.bat') @signArgs + Check-Exit 'Hush signing' + & (Join-Path $tools 'apksigner.bat') verify --min-sdk-version 26 $OutputApk + Check-Exit 'Hush signature verification' +} finally { + $env:JAVA_HOME = $oldJava + $env:ANDROID_HOME = $oldSdk + $env:HUSH_SIGNING = $oldSigning +} diff --git a/hush/overlay/java/io/coldmew/hush/TvActivity.java b/hush/overlay/java/io/coldmew/hush/TvActivity.java new file mode 100644 index 0000000..0c2fa08 --- /dev/null +++ b/hush/overlay/java/io/coldmew/hush/TvActivity.java @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: GPL-3.0-only +package io.coldmew.hush; + +import android.Manifest; +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; +import android.widget.Toast; + +/** A D-pad-first entry point. The upstream setup screens remain available for pairing. */ +public class TvActivity extends Activity { + private final Handler ui = new Handler(Looper.getMainLooper()); + private TextView status; + private Button power; + private final Runnable refresh = new Runnable() { + @Override public void run() { + Prefs p = new Prefs(TvActivity.this); + power.setText(p.enabled() ? "Hush skipping: on · select to turn off" : "Hush skipping: off · select to turn on"); + boolean signed = getPackageManager().checkSignatures(getPackageName(), Hush.SPOTIFY) == PackageManager.SIGNATURE_MATCH; + status.setText(!signed ? "Install Spotify+ TV and this companion signed with the same key." + : !Shell.ready() ? "Helper is not ready. Ads can still be muted by Spotify+ TV. Set up the helper below." + : !TvBridge.hasSession() ? "Helper ready. Open Spotify+ TV and start playback to connect its session." + : p.enabled() ? "Hush is enabled. TV restart skipping needs device verification." + : "Connected. Turn on Hush to attempt restart skipping during ads."); + ui.postDelayed(this, 1000); + } + }; + + @Override protected void onCreate(Bundle state) { + super.onCreate(state); + ScrollView scroll = new ScrollView(this); + LinearLayout body = new LinearLayout(this); + body.setOrientation(LinearLayout.VERTICAL); + body.setPadding(64, 32, 64, 32); + scroll.setBackgroundColor(0xff10191f); + scroll.addView(body); + TextView title = new TextView(this); + title.setText("Hush · Spotify+ TV"); title.setTextColor(0xff91e7cf); title.setTextSize(28); + body.addView(title); + status = new TextView(this); status.setTextColor(0xffeeeeee); status.setTextSize(18); + status.setPadding(0, 20, 0, 20); body.addView(status); + power = add(body, "Hush skipping", () -> { + Prefs p = new Prefs(this); p.mode(Prefs.MODE_RESTART); + Hush.setEnabled(this, !p.enabled()); TvBridge.recheck(); + if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) + requestPermissions(new String[]{Manifest.permission.POST_NOTIFICATIONS}, 1); + }); + add(body, "Set up Hush helper · Android 11+", () -> open(new Intent(this, HelperSetupActivity.class))); + add(body, "Authorize running Shizuku · Android 8+", () -> { + if (Shell.running()) Shell.requestPermission(); + else open(new Intent(this, ShizukuSetupActivity.class)); + }); + add(body, "Test Spotify restart", () -> { + if (!new Prefs(this).enabled() || !Shell.ready() || !TvBridge.hasSession() || !TvBridge.mayResume(this)) { + Toast.makeText(this, "Enable Hush, start its helper and play Spotify first. Check the sleep timer too.", Toast.LENGTH_LONG).show(); + return; + } + new AlertDialog.Builder(this).setTitle("Restart Spotify now?") + .setMessage("This interrupts current playback to test recovery. Queue behavior must be checked on your TV.") + .setPositiveButton("Test restart", (d, w) -> Skipper.start(this, true)) + .setNegativeButton("Cancel", null).show(); + }); + add(body, "Return to Spotify+ TV", () -> { + Intent launch = getPackageManager().getLeanbackLaunchIntentForPackage(Hush.SPOTIFY); + if (launch == null) launch = getPackageManager().getLaunchIntentForPackage(Hush.SPOTIFY); + if (launch != null) open(launch); else Toast.makeText(this, "Spotify TV is not installed", Toast.LENGTH_LONG).show(); + }); + TextView notes = new TextView(this); + notes.setText("Keep ‘Mute detected ads’ on in Spotify+ TV for the fallback. Hush needs Wireless debugging or Shizuku after a reboot. DNS filtering is off by default.\n\nAdapted from coldMEW/Hush 2.0.2 · GPL-3.0. Source and changes: github.com/AlphadogRSA/spotifyplus-tv-patch/tree/feat/hush-tv/hush"); + notes.setTextColor(0xffb9c7d0); notes.setTextSize(15); notes.setPadding(0, 24, 0, 12); body.addView(notes); + setContentView(scroll); power.requestFocus(); + } + + private Button add(LinearLayout parent, String label, Runnable action) { + Button button = new Button(this); button.setText(label); button.setAllCaps(false); + button.setOnClickListener(v -> action.run()); parent.addView(button); + return button; + } + private void open(Intent intent) { + try { startActivity(intent); } + catch (RuntimeException e) { Toast.makeText(this, "This setup screen is unavailable on your TV", Toast.LENGTH_LONG).show(); } + } + @Override protected void onResume() { super.onResume(); ui.post(refresh); } + @Override protected void onPause() { ui.removeCallbacks(refresh); super.onPause(); } +} diff --git a/hush/overlay/java/io/coldmew/hush/TvBridge.java b/hush/overlay/java/io/coldmew/hush/TvBridge.java new file mode 100644 index 0000000..ced3287 --- /dev/null +++ b/hush/overlay/java/io/coldmew/hush/TvBridge.java @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: GPL-3.0-only +package io.coldmew.hush; + +import android.content.Context; +import android.media.MediaMetadata; +import android.media.session.MediaController; +import android.media.session.MediaSession; +import android.media.session.PlaybackState; +import android.os.Handler; +import android.os.Looper; +import android.os.SystemClock; +import java.util.Collections; +import java.util.List; + +/** Native TV tokens are capabilities for one Spotify session; no notification access is needed. */ +final class TvBridge { + private static final Handler UI = new Handler(Looper.getMainLooper()); + private static final TvSkipPolicy POLICY = new TvSkipPolicy(); + private static volatile MediaController current; + private static MediaController.Callback callback; + private static volatile boolean nativeAd; + private static long stamp; + private static Context app; + + private TvBridge() {} + + static void accept(Context c, MediaSession.Token token, boolean ad, long sentAt, long sleepAt) { + if (sentAt <= 0 || sentAt < stamp || sentAt > SystemClock.elapsedRealtime() + || SystemClock.elapsedRealtime() - sentAt > 15000) return; + MediaController candidate = new MediaController(c, token); + if (!Hush.SPOTIFY.equals(candidate.getPackageName())) return; + stamp = sentAt; + app = c.getApplicationContext(); + app.getSharedPreferences("tv_bridge", 0).edit().putLong("sleep_at", sleepAt).apply(); + nativeAd = ad; + if (current == null || !current.getSessionToken().equals(token)) { + if (current != null && callback != null) current.unregisterCallback(callback); + current = candidate; + callback = new MediaController.Callback() { + @Override public void onPlaybackStateChanged(PlaybackState s) { recheck(); } + @Override public void onMetadataChanged(MediaMetadata m) { recheck(); } + @Override public void onSessionDestroyed() { + if (current != candidate) return; + candidate.unregisterCallback(this); + current = null; + nativeAd = false; + } + }; + candidate.registerCallback(callback, UI); + } + recheck(); + } + + static void acceptController(Context c, MediaController controller) { + // The native bridge is authoritative for TV. An optional notification listener may + // refresh metadata, but must never replace a newer native session or mute the device. + if (current != null && current.getSessionToken().equals(controller.getSessionToken())) recheck(); + } + + static boolean isNativeAd(MediaController mc) { + MediaController active = current; + return nativeAd && active != null && active.getSessionToken().equals(mc.getSessionToken()); + } + + static List sessions(Context c) { + MediaController active = current; + return active == null ? Collections.emptyList() : Collections.singletonList(active); + } + + static boolean mayResume(Context c) { + long end = c.getSharedPreferences("tv_bridge", 0).getLong("sleep_at", 0); + return new Prefs(c).enabled() && (end <= 0 || System.currentTimeMillis() < end); + } + + static boolean hasSession() { return current != null; } + + static void recheck() { + if (Looper.myLooper() != Looper.getMainLooper()) { UI.post(TvBridge::recheck); return; } + Context c = app; + MediaController mc = current; + if (c == null || mc == null) return; + Prefs p = new Prefs(c); + if (!p.enabled() || !Prefs.MODE_RESTART.equals(p.mode())) return; + PlaybackState ps = mc.getPlaybackState(); + boolean active = ps != null && (ps.getState() == PlaybackState.STATE_PLAYING + || ps.getState() == PlaybackState.STATE_BUFFERING || ps.getState() == PlaybackState.STATE_CONNECTING); + MediaMetadata m = mc.getMetadata(); + boolean ad = AdWatcher.isAd(mc); + if (!ad && m != null && !Skipper.busy()) { + AdWatcher.lastTrack = m.getString(MediaMetadata.METADATA_KEY_MEDIA_ID); + AdWatcher.lastContext = m.getString(AdWatcher.KEY_CONTEXT); + } + long now = System.currentTimeMillis(); + long end = c.getSharedPreferences("tv_bridge", 0).getLong("sleep_at", 0); + boolean ready = Shell.ready() && (Skipper.lastFailAt <= 0 || now - Skipper.lastFailAt >= 120000); + if (POLICY.shouldSkip(ad, active, ready, Skipper.busy(), now, end)) Skipper.start(c, false); + } +} diff --git a/hush/overlay/java/io/coldmew/hush/TvReceiver.java b/hush/overlay/java/io/coldmew/hush/TvReceiver.java new file mode 100644 index 0000000..5a8dcb4 --- /dev/null +++ b/hush/overlay/java/io/coldmew/hush/TvReceiver.java @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-3.0-only +package io.coldmew.hush; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.media.session.MediaSession; + +/** Manifest signature permission protects this endpoint; the peer must also share our signer. */ +public class TvReceiver extends BroadcastReceiver { + public static final String ACTION = "dev.aurora.hushtv.TV_STATE"; + @Override public void onReceive(Context c, Intent i) { + if (!ACTION.equals(i.getAction())) return; + if (c.getPackageManager().checkSignatures(c.getPackageName(), Hush.SPOTIFY) + != PackageManager.SIGNATURE_MATCH) return; + try { + MediaSession.Token token = i.getParcelableExtra("session"); + if (token != null) TvBridge.accept(c, token, i.getBooleanExtra("ad", false), + i.getLongExtra("stamp", 0), i.getLongExtra("sleep_at", 0)); + } catch (RuntimeException ignored) { /* Invalid parcel or dead session: keep local muting. */ } + } +} diff --git a/hush/overlay/java/io/coldmew/hush/TvService.java b/hush/overlay/java/io/coldmew/hush/TvService.java new file mode 100644 index 0000000..41c96b2 --- /dev/null +++ b/hush/overlay/java/io/coldmew/hush/TvService.java @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-3.0-only +package io.coldmew.hush; + +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.os.Handler; +import android.os.IBinder; +import android.os.Looper; + +/** Keeps restart/recovery alive after the broadcast returns and Spotify has been stopped. */ +public class TvService extends Service { + private final Handler ui = new Handler(Looper.getMainLooper()); + private final Runnable tick = new Runnable() { + @Override public void run() { + if (!new Prefs(TvService.this).enabled()) { stopSelf(); return; } + TvBridge.recheck(); + ui.postDelayed(this, 2000); + } + }; + static void enabled(Context c, boolean on) { + Intent intent = new Intent(c, TvService.class); + if (on) c.startForegroundService(intent); else c.stopService(intent); + } + @Override public int onStartCommand(Intent intent, int flags, int startId) { + if (!new Prefs(this).enabled()) { stopSelf(); return START_NOT_STICKY; } + startForeground(Hush.NOTIF_STATUS, Hush.statusNotification(this)); + ui.removeCallbacks(tick); ui.post(tick); + return START_STICKY; + } + @Override public IBinder onBind(Intent intent) { return null; } + @Override public void onDestroy() { ui.removeCallbacks(tick); super.onDestroy(); } +} diff --git a/hush/overlay/java/io/coldmew/hush/TvSkipPolicy.java b/hush/overlay/java/io/coldmew/hush/TvSkipPolicy.java new file mode 100644 index 0000000..0fdd363 --- /dev/null +++ b/hush/overlay/java/io/coldmew/hush/TvSkipPolicy.java @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: GPL-3.0-only +package io.coldmew.hush; + +/** One restart attempt per ad break. A running restart cannot clear the latch. */ +public final class TvSkipPolicy { + private boolean attempted; + + public synchronized boolean shouldSkip(boolean ad, boolean active, boolean ready, + boolean busy, long now, long sleepAt) { + if (busy) return false; + if (!ad && active) attempted = false; + if (!ad || !active || !ready || attempted || (sleepAt > 0 && now >= sleepAt)) return false; + attempted = true; + return true; + } +} diff --git a/hush/prepare.py b/hush/prepare.py new file mode 100644 index 0000000..8e0429e --- /dev/null +++ b/hush/prepare.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +"""Prepare an auditable TV adaptation from the exact upstream gitlink; never edit the submodule.""" +from pathlib import Path +import argparse +import shutil +import subprocess +import xml.etree.ElementTree as ET + +ROOT = Path(__file__).resolve().parent +PIN = '4e9ded397338de5c69b1784c636feb3d34a8de01' +ANDROID = 'http://schemas.android.com/apk/res/android' +ET.register_namespace('android', ANDROID) +ET.register_namespace('tools', 'http://schemas.android.com/tools') + +def replace(path, old, new): + text = path.read_text(encoding='utf-8') + if text.count(old) != 1: + raise ValueError(f'Upstream changed: expected one replacement in {path.name}: {old[:60]}') + path.write_text(text.replace(old, new), encoding='utf-8') + +def prepare(destination): + upstream = ROOT / 'upstream' + actual = subprocess.check_output(['git', '-C', str(upstream), 'rev-parse', 'HEAD'], text=True).strip() + if actual != PIN: + raise ValueError(f'Expected Hush {PIN}, got {actual}') + subprocess.run(['git', '-C', str(upstream), 'diff', '--exit-code', 'HEAD', '--'], check=True, stdout=subprocess.DEVNULL) + # Untracked files are excluded too: copy only paths recorded in the pinned source tree. + if destination.exists(): + raise ValueError('Destination must be new; refusing to overwrite an existing project') + paths = subprocess.check_output(['git', '-C', str(upstream), 'ls-files', '-z', 'android'], text=True).split('\0') + for name in filter(None, paths): + relative = Path(name).relative_to('android') + target = destination / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(upstream / name, target) + + source = destination / 'app/src/main/java/io/coldmew/hush' + for path in (destination / 'app/src').rglob('*'): + if path.suffix not in ('.java', '.xml'): + continue + text = path.read_text(encoding='utf-8') + text = text.replace('com.spotify.music', 'com.spotify.tv.android') + # This metadata key belongs to Spotify's protocol, not its install package. + text = text.replace('com.spotify.tv.android.extra.CONTEXT_URI', 'com.spotify.music.extra.CONTEXT_URI') + text = text.replace('com.spotify.tv.android/.MainActivity', 'com.spotify.tv.android/.SpotifyTVActivity') + path.write_text(text, encoding='utf-8') + + gradle = destination / 'app/build.gradle.kts' + replace(gradle, 'applicationId = "io.coldmew.hush"', 'applicationId = "dev.aurora.hushtv"') + replace(gradle, 'versionName = "2.0.2"', 'versionName = "2.0.2-tv.1"') + # Keep one stable package for the signature-protected Spotify protocol in every variant. + replace(gradle, 'applicationIdSuffix = ".debug"', '// Stable companion package for debug builds.') + + watcher = source / 'AdWatcher.java' + replace(watcher, 'static boolean isAd(MediaController c) { return isAd(c.getMetadata()); }', + 'static boolean isAd(MediaController c) { return TvBridge.isNativeAd(c) || isAd(c.getMetadata()); }') + replace(watcher, 'AdWatcher w = instance;\n if (w != null && w.spotify != null) w.check(w.spotify);', + 'TvBridge.recheck();') + text = watcher.read_text(encoding='utf-8') + start = text.index(' private void checkLocked(MediaController c) {') + watcher.write_text(text[:start] + ' private void checkLocked(MediaController c) {\n' + ' TvBridge.acceptController(this, c);\n }\n}\n', encoding='utf-8') + + skipper = source / 'Skipper.java' + replace(skipper, 'return c.getSystemService(MediaSessionManager.class).getActiveSessions(new ComponentName(c, AdWatcher.class));', + 'return TvBridge.sessions(c);') + replace(skipper, 'Hush.SPOTIFY + "/.MainActivity"', 'Hush.SPOTIFY + "/.SpotifyTVActivity"') + replace(skipper, 'Intent i = c.getPackageManager().getLaunchIntentForPackage(Hush.SPOTIFY);', + 'Intent i = c.getPackageManager().getLeanbackLaunchIntentForPackage(Hush.SPOTIFY);\n' + ' if (i == null) i = c.getPackageManager().getLaunchIntentForPackage(Hush.SPOTIFY);') + replace(skipper, ''' switch (n % 3) { + case 0: Shell.run(Commands.MEDIA_PLAY); break; + case 1: mc.getTransportControls().play(); break; + default: Shell.run(Commands.KEY_PLAY); break; + }''', ' mc.getTransportControls().play(); // Only the forwarded Spotify TV session.') + replace(skipper, 'MediaController mc = latest(c, old);\n PlaybackState ps = mc == null ? null : mc.getPlaybackState();', + 'MediaController mc = latest(c, old);\n' + ' if (!TvBridge.mayResume(c)) {\n' + ' if (mc != null) mc.getTransportControls().pause();\n' + ' return Result.NOT_PLAYING;\n' + ' }\n' + ' PlaybackState ps = mc == null ? null : mc.getPlaybackState();') + # Repair must not send global media keys that could control another TV app. + replace(skipper, 'Shell.run(Commands.REPAIR_MUTE);', + 'Shell.run(Commands.ALLOW_AUDIO);\n' + ' if (mc != null) mc.getTransportControls().play();') + + # Hush's optional advanced timer can also use the native session without notification access. + timer = source / 'SleepTimer.java' + text = timer.read_text(encoding='utf-8') + text = text.replace('c.getSystemService(MediaSessionManager.class)\n .getActiveSessions(new ComponentName(c, AdWatcher.class))', 'TvBridge.sessions(c)') + text = text.replace(''' AudioManager am = c.getSystemService(AudioManager.class); + am.dispatchMediaKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PAUSE)); + am.dispatchMediaKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PAUSE));''', + ' // No global media keys: another TV app may now be playing.') + timer.write_text(text, encoding='utf-8') + + hush = source / 'Hush.java' + replace(hush, 'p.enabled(on);', 'p.enabled(on);\n TvService.enabled(c, on);') + replace(hush, 'if (p.enabled()) { applyDns(c); refreshNotification(c); }', + 'if (p.enabled()) { applyDns(c); refreshNotification(c); TvService.enabled(c, true); }') + + for path in (ROOT / 'overlay/java').rglob('*.java'): + target = destination / 'app/src/main/java' / path.relative_to(ROOT / 'overlay/java') + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, target) + + manifest_path = destination / 'app/src/main/AndroidManifest.xml' + tree = ET.parse(manifest_path) + manifest = tree.getroot() + key = lambda name: '{' + ANDROID + '}' + name + permission = 'dev.aurora.hushtv.permission.TV_BRIDGE' + manifest.insert(0, ET.Element('permission', {key('name'): permission, key('protectionLevel'): 'signature'})) + manifest.insert(1, ET.Element('uses-permission', {key('name'): permission})) + manifest.insert(2, ET.Element('uses-feature', {key('name'): 'android.hardware.touchscreen', key('required'): 'false'})) + manifest.insert(3, ET.Element('uses-feature', {key('name'): 'android.software.leanback', key('required'): 'false'})) + app = manifest.find('application') + app.set(key('label'), 'Hush · Spotify+ TV') + app.set(key('banner'), '@drawable/tv_banner') + activity = ET.SubElement(app, 'activity', {key('name'): '.TvActivity', key('exported'): 'true'}) + intent = ET.SubElement(activity, 'intent-filter') + ET.SubElement(intent, 'action', {key('name'): 'android.intent.action.MAIN'}) + ET.SubElement(intent, 'category', {key('name'): 'android.intent.category.LEANBACK_LAUNCHER'}) + ET.SubElement(app, 'receiver', {key('name'): '.TvReceiver', key('exported'): 'true', key('permission'): permission}) + service = ET.SubElement(app, 'service', {key('name'): '.TvService', key('exported'): 'false', key('foregroundServiceType'): 'specialUse'}) + ET.SubElement(service, 'property', {key('name'): 'android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE', + key('value'): 'User-enabled Spotify TV ad detection and restart recovery'}) + tree.write(manifest_path, encoding='utf-8', xml_declaration=True) + assets = destination / 'app/src/main/assets' + assets.mkdir(parents=True, exist_ok=True) + shutil.copyfile(upstream / 'LICENSE', assets / 'HUSH-COPYING.txt') + (assets / 'HUSH-SOURCE.txt').write_text('Hush 2.0.2 by coldMEW, GPL-3.0\n' + f'Upstream https://github.com/coldMEW/Hush commit {PIN}\n' + 'TV changes and reproducible source: https://github.com/AlphadogRSA/spotifyplus-tv-patch\n', encoding='utf-8') + drawable = destination / 'app/src/main/res/drawable' + drawable.mkdir(exist_ok=True) + (drawable / 'tv_banner.xml').write_text(''' + + + ''', encoding='utf-8') + return destination + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--output', type=Path, default=ROOT / 'build/android') + print(prepare(parser.parse_args().output)) diff --git a/hush/tests/TvSkipPolicyTest.java b/hush/tests/TvSkipPolicyTest.java new file mode 100644 index 0000000..3dfcde3 --- /dev/null +++ b/hush/tests/TvSkipPolicyTest.java @@ -0,0 +1,18 @@ +import io.coldmew.hush.TvSkipPolicy; + +public class TvSkipPolicyTest { + static void check(boolean value) { if (!value) throw new AssertionError(); } + public static void main(String[] args) { + TvSkipPolicy p = new TvSkipPolicy(); + check(!p.shouldSkip(true, false, true, false, 1000, 0)); // paused ad + check(!p.shouldSkip(true, true, false, false, 1000, 0)); // helper missing + check(p.shouldSkip(true, true, true, false, 1000, 0)); + check(!p.shouldSkip(true, true, true, false, 1001, 0)); // repeated flag + check(!p.shouldSkip(false, true, true, true, 1002, 0)); // transient music while restarting + check(!p.shouldSkip(true, true, true, false, 1003, 0)); + check(!p.shouldSkip(false, true, true, false, 2000, 0)); // actual music resets latch + check(!p.shouldSkip(true, true, true, false, 2001, 2000)); // timer expired + check(p.shouldSkip(true, true, true, false, 2002, 10000)); + System.out.println("TvSkipPolicyTest passed"); + } +} diff --git a/hush/tests/test_prepare.py b/hush/tests/test_prepare.py new file mode 100644 index 0000000..608df52 --- /dev/null +++ b/hush/tests/test_prepare.py @@ -0,0 +1,35 @@ +import importlib.util +import tempfile +import unittest +from pathlib import Path +import xml.etree.ElementTree as ET + +ROOT = Path(__file__).resolve().parents[1] + +class PreparationTest(unittest.TestCase): + def test_tv_project_is_separate_and_bridge_is_signature_protected(self): + self.assertTrue((ROOT / 'prepare.py').exists(), 'TV preparation feature is missing') + spec = importlib.util.spec_from_file_location('prepare', ROOT / 'prepare.py') + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + with tempfile.TemporaryDirectory() as directory: + out = Path(directory) / 'android' + module.prepare(out) + manifest = ET.parse(out / 'app/src/main/AndroidManifest.xml').getroot() + android = '{http://schemas.android.com/apk/res/android}' + self.assertEqual(manifest.find('permission').get(android + 'protectionLevel'), 'signature') + receiver = next(x for x in manifest.findall('application/receiver') if x.get(android + 'name') == '.TvReceiver') + self.assertEqual(receiver.get(android + 'permission'), 'dev.aurora.hushtv.permission.TV_BRIDGE') + self.assertTrue(any(x.get(android+'name') == 'android.intent.category.LEANBACK_LAUNCHER' for x in manifest.findall('.//category'))) + self.assertIn('applicationId = "dev.aurora.hushtv"', (out / 'app/build.gradle.kts').read_text()) + source = out / 'app/src/main/java/io/coldmew/hush' + self.assertIn('com.spotify.tv.android', (source / 'Hush.java').read_text()) + self.assertIn('TvBridge.sessions(c)', (source / 'Skipper.java').read_text()) + self.assertNotIn('am.adjustStreamVolume', (source / 'AdWatcher.java').read_text()) + self.assertTrue((out / 'app/src/main/assets/HUSH-COPYING.txt').exists()) + service = next(x for x in manifest.findall('application/service') if x.get(android+'name') == '.TvService') + self.assertEqual(service.get(android+'exported'), 'false') + self.assertEqual(service.get(android+'foregroundServiceType'), 'specialUse') + +if __name__ == '__main__': + unittest.main() diff --git a/hush/upstream b/hush/upstream new file mode 160000 index 0000000..4e9ded3 --- /dev/null +++ b/hush/upstream @@ -0,0 +1 @@ +Subproject commit 4e9ded397338de5c69b1784c636feb3d34a8de01 diff --git a/install.ps1 b/install.ps1 index 59245f3..ce2a423 100644 --- a/install.ps1 +++ b/install.ps1 @@ -1,12 +1,19 @@ param( [Parameter(Mandatory)][string]$ApkDirectory, [Parameter(Mandatory)][string]$Serial, - [string]$Adb = 'adb' + [string]$Adb = 'adb', + [switch]$WithoutHush ) $ErrorActionPreference = 'Stop' $apks = @('base.apk','split_config.armeabi_v7a.apk','split_config.en.apk','split_config.tvdpi.apk') | ForEach-Object { (Resolve-Path -LiteralPath (Join-Path $ApkDirectory $_)).Path } +# Install the permission-defining companion first. An existing matching signing key is required. +if (-not $WithoutHush) { + $hush = (Resolve-Path -LiteralPath (Join-Path $ApkDirectory 'Hush-TV.apk')).Path + & $Adb -s $Serial install -r $hush + if ($LASTEXITCODE -ne 0) { throw 'Hush installation failed; no uninstall or app data reset was attempted.' } +} & $Adb -s $Serial install-multiple -r @apks if ($LASTEXITCODE -ne 0) { throw 'Installation failed; no uninstall or app data reset was attempted.' } # Development diagnostic permission: identifies only this process’s positive audio session IDs. diff --git a/revanced/build.gradle.kts b/revanced/build.gradle.kts index d1e4578..55465d5 100644 --- a/revanced/build.gradle.kts +++ b/revanced/build.gradle.kts @@ -1,7 +1,7 @@ plugins { kotlin("jvm") version "2.3.10" } group = "dev.aurora.tvpatch" -version = "0.5.0" +version = "0.6.0" kotlin { jvmToolchain(17) // The pinned official Patcher is built with experimental context/backing-field metadata. @@ -28,7 +28,7 @@ tasks.processResources { } val bundle by tasks.registering(Jar::class) { dependsOn(tasks.classes) - archiveFileName.set("spotifyplus-tv-0.5.rvp") + archiveFileName.set("spotifyplus-tv-0.6.rvp") from(sourceSets.main.get().output) doFirst { require(extensionDex.isPresent && file(extensionDex.get()).isFile) { "Pass -PextensionDex=/absolute/path/to/classes.dex from the compiled MIT runtime extension" } } manifest { attributes("Main-Class" to "dev.aurora.patches.RunnerKt") } diff --git a/revanced/src/main/kotlin/dev/aurora/patches/TvPatches.kt b/revanced/src/main/kotlin/dev/aurora/patches/TvPatches.kt index d7a941a..85276ae 100644 --- a/revanced/src/main/kotlin/dev/aurora/patches/TvPatches.kt +++ b/revanced/src/main/kotlin/dev/aurora/patches/TvPatches.kt @@ -29,7 +29,7 @@ val tvManifestPatch = resourcePatch(name = "TV app label and local lyric import" if (node.getAttributeNS(android, "name") == "com.spotify.tv.android.SpotifyTVActivity") node.setAttributeNS(android, "android:label", "Spotify+ TV") } - for (permission in listOf("android.permission.MODIFY_AUDIO_SETTINGS", "android.permission.DUMP")) { + for (permission in listOf("android.permission.MODIFY_AUDIO_SETTINGS", "android.permission.DUMP", "dev.aurora.hushtv.permission.TV_BRIDGE")) { if ((0 until doc.getElementsByTagName("uses-permission").length).none { (doc.getElementsByTagName("uses-permission").item(it) as Element).getAttributeNS(android, "name") == permission }) { @@ -38,6 +38,15 @@ val tvManifestPatch = resourcePatch(name = "TV app label and local lyric import" doc.documentElement.insertBefore(element, app) } } + val queries = (doc.getElementsByTagName("queries").item(0) as? Element) + ?: doc.createElement("queries").also { doc.documentElement.insertBefore(it, app) } + if ((0 until queries.getElementsByTagName("package").length).none { + (queries.getElementsByTagName("package").item(it) as Element).getAttributeNS(android, "name") == "dev.aurora.hushtv" + }) { + queries.appendChild(doc.createElement("package").also { + it.setAttributeNS(android, "android:name", "dev.aurora.hushtv") + }) + } } } } @@ -45,7 +54,7 @@ val tvManifestPatch = resourcePatch(name = "TV app label and local lyric import" val tvAssetsPatch = rawResourcePatch(name = "TV theme assets and notices", use = false) { compatibleWith(PACKAGE(VERSION)) apply { - for (name in listOf("spotifyplus-tv.js", "TV-PATCH-LICENSE.txt", "SPOTIFYPLUS-LICENSE.txt", "INSPIRATION.md")) { + for (name in listOf("spotifyplus-tv.js", "TV-PATCH-LICENSE.txt", "SPOTIFYPLUS-LICENSE.txt", "INSPIRATION.md", "HUSH-NOTICE.txt")) { val target = get("assets/$name", false) target.parentFile.mkdirs() requireNotNull(object {}.javaClass.classLoader.getResourceAsStream(name)) { "Missing bundled asset $name" }.use { input -> diff --git a/src/dev/aurora/tvpatch/Hooks.java b/src/dev/aurora/tvpatch/Hooks.java index 13caaa3..e78e0b8 100644 --- a/src/dev/aurora/tvpatch/Hooks.java +++ b/src/dev/aurora/tvpatch/Hooks.java @@ -66,6 +66,7 @@ public final class Hooks { private static long nextLookupAt; private static Button fetchButton, plainButton; private static long sleepAt; + private static boolean detectedAd; private static String script; private static boolean longSelect; private static boolean forwardingKey; @@ -78,15 +79,21 @@ public final class Hooks { private static final Runnable ticker = new Runnable() { @Override public void run() { try { - if (sleepAt > 0 && SystemClock.elapsedRealtime() >= sleepAt) { + if (controller != null && SleepDeadline.expired(sleepAt, System.currentTimeMillis())) { + controller.getTransportControls().pause(); sleepAt = 0; - if (controller != null) controller.getTransportControls().pause(); + Activity owner = activity.get(); + if (owner != null) { + prefs(owner).edit().remove("sleepAt").apply(); + HushClient.signal(owner, token, detectedAd, sleepAt, true); + } toast("Sleep timer finished"); } if (lyricDialog != null && lyricDialog.isShowing()) updateLyrics(); applyAdVolume(); Activity current = activity.get(); if (current != null) { + HushClient.signal(current, token, detectedAd, sleepAt, false); PlaybackState playback = cachedPlayback; AudioDsp.tick(current, playback != null && playback.getState() == PlaybackState.STATE_PLAYING); } @@ -117,6 +124,9 @@ private static WebView find(View root) { public static void attach(Activity a) { try { activity = new WeakReference<>(a); + int boot = android.provider.Settings.Global.getInt(a.getContentResolver(), android.provider.Settings.Global.BOOT_COUNT, -1); + sleepAt = prefs(a).getInt("sleepBoot", boot) == boot ? prefs(a).getLong("sleepAt", 0) : 0; + if (sleepAt == 0) prefs(a).edit().remove("sleepAt").apply(); AD_MUTE.enabled(prefs(a).getBoolean("muteAds", true)); WebView view = find(a.getWindow().getDecorView()); web = new WeakReference<>(view); @@ -167,6 +177,7 @@ private static void connectController(Context context) { }; next.registerCallback(controllerCallback, UI); cachedPlayback = next.getPlaybackState(); cachedMetadata = next.getMetadata(); + HushClient.signal(context, token, detectedAd, sleepAt, true); } private static void clearLyricViews() { lyricTitle = null; lyricStatus = null; fetchButton = null; plainButton = null; @@ -193,7 +204,12 @@ public static void page(WebView view) { } /** Observe the existing ad flag without altering the ad-break timeline. */ public static void adState(boolean playing) { - UI.post(() -> { AD_MUTE.ad(playing, SystemClock.elapsedRealtime()); applyAdVolume(); }); + UI.post(() -> { + detectedAd = playing; + AD_MUTE.ad(playing, SystemClock.elapsedRealtime()); applyAdVolume(); + Activity a = activity.get(); + if (a != null) HushClient.signal(a, token, detectedAd, sleepAt, true); + }); } /** Intercept TVBridge's native player volume; never Android's device volume. */ public static synchronized void playbackEvent(Object router, int event, int volume, int remote) { @@ -378,18 +394,25 @@ public static void showMenu(Activity a) { AD_MUTE.enabled(value); applyAdVolume(); mute.setText("Mute detected ads: " + (value ? "on" : "off")); }); add(body, mute); + add(body, button(a, "Hush · ad-break skipping", () -> { + HushClient.signal(a, token, detectedAd, sleepAt, true); + HushClient.open(a); + })); add(body, button(a, "Audio · Equalizer & Boost", () -> { menu.dismiss(); showAudio(a); })); add(body, button(a, "Lyrics · local / LRCLIB", () -> { menu.dismiss(); showLyrics(a); })); add(body, button(a, "Sleep timer" + (sleepAt > 0 ? " · active" : ""), () -> { menu.dismiss(); trackDialog(new AlertDialog.Builder(a).setTitle("Pause this Spotify session after…") .setItems(new String[]{"15 minutes", "30 minutes", "60 minutes", "Cancel timer"}, (dialog, which) -> { - sleepAt = which == 3 ? 0 : SystemClock.elapsedRealtime() + new long[]{900000,1800000,3600000}[which]; - toast(which == 3 ? "Sleep timer cancelled" : "Sleep timer set. Keep Spotify running."); + sleepAt = which == 3 ? 0 : System.currentTimeMillis() + new long[]{900000,1800000,3600000}[which]; + int boot = android.provider.Settings.Global.getInt(a.getContentResolver(), android.provider.Settings.Global.BOOT_COUNT, -1); + p.edit().putLong("sleepAt", sleepAt).putInt("sleepBoot", boot).apply(); + HushClient.signal(a, token, detectedAd, sleepAt, true); + toast(which == 3 ? "Sleep timer cancelled" : "Sleep timer set. It survives Spotify restarts."); }).create()).show(); })); add(body, button(a, "About", () -> trackDialog(new AlertDialog.Builder(a) - .setTitle("Spotify+ TV · 0.5") - .setMessage("Made for your TV remote.\n\nArtwork blur, accent colors, lyrics, sleep timer, ad muting and audio controls.\n\nInspired by SpotifyPlus (MIT, © 2025 Devon Shoutz), Eevee's lyrics features and Spicetify's UI customization. Original Android TV implementation.\n\nOptional lyrics lookup sends track title, artist, album and duration to LRCLIB. Full source and license notices are included in the project and APK assets.") + .setTitle("Spotify+ TV · 0.6") + .setMessage("Made for your TV remote.\n\nArtwork blur, accent colors, lyrics, sleep timer, ad muting, optional Hush companion support and audio controls.\n\nInspired by SpotifyPlus (MIT, © 2025 Devon Shoutz), Eevee's lyrics features and Spicetify's UI customization. Original Android TV implementation.\n\nOptional lyrics lookup sends track title, artist, album and duration to LRCLIB. Full source and license notices are included in the project and APK assets.") .setPositiveButton("Close", null).create()).show())); add(body, button(a, "Return to Spotify", () -> menu.dismiss())); ScrollView scroll = new ScrollView(a); scroll.setBackgroundColor(Color.TRANSPARENT); scroll.addView(body); diff --git a/src/dev/aurora/tvpatch/HushClient.java b/src/dev/aurora/tvpatch/HushClient.java new file mode 100644 index 0000000..3778769 --- /dev/null +++ b/src/dev/aurora/tvpatch/HushClient.java @@ -0,0 +1,50 @@ +package dev.aurora.tvpatch; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.media.session.MediaSession; +import android.os.SystemClock; + +/** Independent protocol adapter; the GPL Hush implementation lives in a separate APK. */ +public final class HushClient { + private static final String PACKAGE = "dev.aurora.hushtv"; + private static final String PERMISSION = PACKAGE + ".permission.TV_BRIDGE"; + private static long lastSent; + private HushClient() {} + + private static boolean trusted(Context c) { + return c.getPackageManager().checkSignatures(c.getPackageName(), PACKAGE) == PackageManager.SIGNATURE_MATCH; + } + + public static void signal(Context c, MediaSession.Token token, boolean ad, long sleepAt, boolean force) { + if (token == null) return; + long now = SystemClock.elapsedRealtime(); + if (!force && now - lastSent < 10000) return; + lastSent = now; + if (!trusted(c)) return; + try { + c.sendBroadcast(new Intent(PACKAGE + ".TV_STATE") + .setComponent(new ComponentName(PACKAGE, "io.coldmew.hush.TvReceiver")) + .addFlags(Intent.FLAG_RECEIVER_FOREGROUND) + .putExtra("session", token).putExtra("ad", ad) + .putExtra("stamp", now).putExtra("sleep_at", sleepAt), PERMISSION); + } catch (RuntimeException ignored) { /* Existing per-player muting continues. */ } + } + + public static void open(Activity a) { + if (!trusted(a)) { + new AlertDialog.Builder(a).setTitle("Hush companion setup") + .setMessage("Install the Hush-TV.apk built with this Spotify+ TV release and the same signing key. Then set up Hush’s helper or authorize Shizuku.\n\nMute detected ads remains available while Hush is not ready.") + .setPositiveButton("OK", null).show(); + return; + } + try { a.startActivity(new Intent().setComponent(new ComponentName(PACKAGE, "io.coldmew.hush.TvActivity"))); } + catch (RuntimeException ignored) { + new AlertDialog.Builder(a).setMessage("Hush could not open. Reinstall the matching companion APK.").setPositiveButton("OK", null).show(); + } + } +} diff --git a/src/dev/aurora/tvpatch/SleepDeadline.java b/src/dev/aurora/tvpatch/SleepDeadline.java new file mode 100644 index 0000000..28875dd --- /dev/null +++ b/src/dev/aurora/tvpatch/SleepDeadline.java @@ -0,0 +1,7 @@ +package dev.aurora.tvpatch; + +/** Persisted wall-clock deadline, shared across Spotify process restarts. */ +public final class SleepDeadline { + private SleepDeadline() {} + public static boolean expired(long deadline, long now) { return deadline > 0 && now >= deadline; } +} diff --git a/tests/SleepDeadlineTest.java b/tests/SleepDeadlineTest.java new file mode 100644 index 0000000..4efe656 --- /dev/null +++ b/tests/SleepDeadlineTest.java @@ -0,0 +1,14 @@ +import dev.aurora.tvpatch.SleepDeadline; + +public class SleepDeadlineTest { + public static void main(String[] args) { + assert !SleepDeadline.expired(0, 1000); + assert !SleepDeadline.expired(2000, 1000); + assert SleepDeadline.expired(2000, 2000); + assert SleepDeadline.expired(2000, 3000); + // Re-creating the process at a later wall-clock time keeps the same deadline. + assert !SleepDeadline.expired(1801000, 1701000); + assert SleepDeadline.expired(1801000, 1801001); + System.out.println("SleepDeadlineTest passed"); + } +} From 4fc2b9ee025c8e36a4152aeadf083e0961c722b4 Mon Sep 17 00:00:00 2001 From: Tumelo Rathebe <96668318+AlphadogRSA@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:19:14 +0200 Subject: [PATCH 2/7] Build 1.3.0.1 with embedded Hush, native Spotify settings and graphic EQ --- .github/workflows/test.yml | 39 +- HANDOFF.md | 35 +- HUSH.md | 43 +- README.md | 130 +--- assets/HUSH-COPYING.txt | 674 ++++++++++++++++++ assets/HUSH-NOTICE.txt | 17 +- assets/spotifyplus-settings.js | 97 +++ build.ps1 | 16 +- docs/superpowers/plans/2026-10-27-hush-tv.md | 71 +- .../specs/2026-10-27-hush-tv-design.md | 12 +- hush/build.ps1 | 49 -- .../java/io/coldmew/hush/TvActivity.java | 94 --- .../java/io/coldmew/hush/TvBridge.java | 98 --- .../java/io/coldmew/hush/TvReceiver.java | 23 - .../java/io/coldmew/hush/TvService.java | 33 - .../java/io/coldmew/hush/TvSkipPolicy.java | 16 - hush/prepare.py | 169 +---- hush/tests/TvSkipPolicyTest.java | 18 - hush/tests/test_prepare.py | 45 +- install.ps1 | 12 +- rebuild_release.py | 80 +++ revanced/build.gradle.kts | 4 +- .../kotlin/dev/aurora/patches/TvPatches.kt | 20 +- sign-apk.ps1 | 25 + src/dev/aurora/tvpatch/AudioDsp.java | 6 +- src/dev/aurora/tvpatch/AudioEffectPlan.java | 18 +- src/dev/aurora/tvpatch/GraphicEq.java | 31 + src/dev/aurora/tvpatch/GraphicEqSettings.java | 20 + src/dev/aurora/tvpatch/GraphicEqView.java | 165 +++++ src/dev/aurora/tvpatch/Hooks.java | 187 +++-- src/dev/aurora/tvpatch/HushClient.java | 50 -- src/dev/aurora/tvpatch/HushIntegration.java | 107 +++ src/dev/aurora/tvpatch/HushPolicy.java | 13 + src/dev/aurora/tvpatch/NativeSettings.java | 57 ++ start-hush.ps1 | 21 + tests/GraphicEqTest.java | 38 + tests/HushPolicyTest.java | 16 + tests/native-settings.test.cjs | 28 + 38 files changed, 1649 insertions(+), 928 deletions(-) create mode 100644 assets/HUSH-COPYING.txt create mode 100644 assets/spotifyplus-settings.js delete mode 100644 hush/build.ps1 delete mode 100644 hush/overlay/java/io/coldmew/hush/TvActivity.java delete mode 100644 hush/overlay/java/io/coldmew/hush/TvBridge.java delete mode 100644 hush/overlay/java/io/coldmew/hush/TvReceiver.java delete mode 100644 hush/overlay/java/io/coldmew/hush/TvService.java delete mode 100644 hush/overlay/java/io/coldmew/hush/TvSkipPolicy.java delete mode 100644 hush/tests/TvSkipPolicyTest.java create mode 100644 rebuild_release.py create mode 100644 sign-apk.ps1 create mode 100644 src/dev/aurora/tvpatch/GraphicEq.java create mode 100644 src/dev/aurora/tvpatch/GraphicEqSettings.java create mode 100644 src/dev/aurora/tvpatch/GraphicEqView.java delete mode 100644 src/dev/aurora/tvpatch/HushClient.java create mode 100644 src/dev/aurora/tvpatch/HushIntegration.java create mode 100644 src/dev/aurora/tvpatch/HushPolicy.java create mode 100644 src/dev/aurora/tvpatch/NativeSettings.java create mode 100644 start-hush.ps1 create mode 100644 tests/GraphicEqTest.java create mode 100644 tests/HushPolicyTest.java create mode 100644 tests/native-settings.test.cjs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 3fc0620..0d72020 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -28,12 +28,13 @@ jobs: java -ea -cp test-classes AdMuteStateTest javac -d test-classes src/dev/aurora/tvpatch/AudioSessions.java tests/AudioSessionsTest.java java -ea -cp test-classes AudioSessionsTest - javac -d test-classes src/dev/aurora/tvpatch/AudioEffectPlan.java tests/AudioEffectPlanTest.java + javac -d test-classes src/dev/aurora/tvpatch/GraphicEq.java src/dev/aurora/tvpatch/AudioEffectPlan.java tests/AudioEffectPlanTest.java tests/GraphicEqTest.java java -ea -cp test-classes AudioEffectPlanTest + java -ea -cp test-classes GraphicEqTest javac -d test-classes src/dev/aurora/tvpatch/SleepDeadline.java tests/SleepDeadlineTest.java java -ea -cp test-classes SleepDeadlineTest - javac -d test-classes hush/overlay/java/io/coldmew/hush/TvSkipPolicy.java hush/tests/TvSkipPolicyTest.java - java -ea -cp test-classes TvSkipPolicyTest + javac -d test-classes src/dev/aurora/tvpatch/SleepDeadline.java src/dev/aurora/tvpatch/HushPolicy.java tests/HushPolicyTest.java + java -ea -cp test-classes HushPolicyTest - name: Test modular fingerprints run: bash revanced/gradlew -p revanced testFingerprints - name: Check source tools @@ -58,7 +59,8 @@ jobs: node tests/presentation.test.cjs node tests/theme-regression.test.cjs node tests/presentation-performance.test.cjs - hush-tv: + node tests/native-settings.test.cjs + rebuild-apk: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -69,26 +71,31 @@ jobs: distribution: temurin java-version: '17' - uses: android-actions/setup-android@v3 - - name: Prepare pinned Hush TV sources + with: + packages: platform-tools + log-accepted-android-sdk-licenses: false + - name: Prepare and test embedded helper sources run: | python3 -m unittest discover -s hush/tests -v python3 hush/prepare.py - - name: Install pinned Android build platform - run: sdkmanager 'platforms;android-35' 'build-tools;35.0.0' - - name: Compile the complete TV extension and build its DEX + sdkmanager 'platforms;android-35' 'build-tools;35.0.0' + - name: Compile single-app runtime run: | mkdir -p .tools/extension-classes .tools/extension-dex - javac -encoding UTF-8 -source 8 -target 8 -cp "$ANDROID_HOME/platforms/android-35/android.jar" -d .tools/extension-classes src/dev/aurora/tvpatch/*.java + javac -encoding UTF-8 -source 8 -target 8 -cp "$ANDROID_HOME/platforms/android-35/android.jar" -d .tools/extension-classes src/dev/aurora/tvpatch/*.java hush/build/generated/dev/aurora/tvpatch/hush/*.java jar cf .tools/extension.jar -C .tools/extension-classes . "$ANDROID_HOME/build-tools/35.0.0/d8" --min-api 26 --lib "$ANDROID_HOME/platforms/android-35/android.jar" --output .tools/extension-dex .tools/extension.jar - - name: Test and build the Hush companion - env: - HUSH_SIGNING: /tmp/no-upstream-signing.properties - run: bash hush/build/android/gradlew -p hush/build/android testDebugUnitTest assembleRelease + - name: Fetch verified prior release and build tools + run: | + curl --fail --location --output .tools/current.apks https://github.com/AlphadogRSA/spotifyplus-tv-patch/releases/download/v0.5.0/SpotifyPlus-TV-1.134.2-v0.5.apks + curl --fail --location --output .tools/apktool.jar https://github.com/iBotPeaches/Apktool/releases/download/v3.0.3/apktool_3.0.3.jar + curl --fail --location --output .tools/apkeditor.jar https://github.com/REAndroid/APKEditor/releases/download/V1.4.9/APKEditor-1.4.9.jar + - name: Rebuild one unsigned APK + run: python3 rebuild_release.py --input .tools/current.apks --dex .tools/extension-dex/classes.dex --apktool .tools/apktool.jar --apkeditor .tools/apkeditor.jar --output build/release-1.3.0.1 - uses: actions/upload-artifact@v4 with: - name: Hush-TV-unsigned + name: SpotifyPlus-TV-1.3.0.1-unsigned path: | - hush/build/android/app/build/outputs/apk/release/app-release-unsigned.apk - hush/build/android/app/build/outputs/mapping/release/mapping.txt + build/release-1.3.0.1/SpotifyPlus-TV-1.3.0.1-unsigned.apk + build/release-1.3.0.1/SHA256.txt if-no-files-found: error diff --git a/HANDOFF.md b/HANDOFF.md index 355e5cd..3fa49a4 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1,34 +1,9 @@ -# Handoff +# Handoff · Spotify+ TV 1.3.0.1 -## Current source version: 0.6 (Hush TV integration; device verification pending) +User requirements: one Spotify APK, integrated Hush functionality, reference-style graphic EQ, and all custom controls inside Spotify’s existing settings panel. -The Hush feature is in the TV menu. A pinned upstream companion, reproducible TV adaptations and same-key build/install support are under `hush/`; see HUSH.md. Native session/ad signals use a signature-protected bridge. The companion keeps restart recovery alive in a foreground service; player-local muting remains the fallback. The existing 0.5 device observations below are historical and do not verify 0.6. Original proprietary APKs and the retained private signing key are not available in this workspace, so no new signed Spotify installation set or TV deployment is claimed. +Implemented: native `/profile` settings host integration using observed `profile-menu`/`profile-menu-item` and `top-menu--settings` selectors; restricted JavaScript settings bridge; native graphic EQ and migration; embedded pinned Hush helper/provider with fixed restart command; persisted sleep/recovery state; single unsigned APK rebuild and retained-key signing/install scripts. -## Previously device-tested release: 0.5 +The rebuilt file still targets the inspected ARMv7/English/TV-density installation, with versionName `1.3.0.1` and original versionCode `2340200`. The source repo excludes private signing material. An unsigned build is not an installable same-key update. No installation or live-TV verification for this version is claimed. Earlier 0.5 observations remain historical in VERIFICATION.md. -The 0.5 follow-up fixes themes against verified TV class selectors, expands promotion/Upgrade hiding and optimizes DOM scanning, playback callbacks, dialog cleanup and DSP writes. See VERIFICATION.md for the measured checks. It keeps all 0.4 functions and persisted settings. The remote theme cycle and Spotify-only audio activation were observed after installing 0.5. - -The default build now uses modular Kotlin ReVanced patches and a precompiled MIT extension DEX. It adds default-on recognized-ad muting, Upgrade-button hiding, Spotify-style accents and background blur, polished TV labels, and per-process/session EQ plus 0–6 dB boost. There is no shared-output/session-0 effect path. See AUDIO.md for one-time ADB diagnostic permission setup. `install.ps1` installs all four APKs, grants that permission and launches the client. The same retained private key was used for updates; no uninstall was used for 0.4. The user paired Spotify again during testing. - -The final four-APK build is specific to the inspected Spotify TV 1.134.2 ARMv7/English/TV-density installation. Source archives and the private GitHub release exclude the local signing key, original-install backup, account data, fetched lyrics and user screenshots. The release installation archive necessarily includes the patched proprietary app and required splits for this personal installation; the MIT license does not relicense those binaries. - -This repository contains only the original TV extension and build/test tools. The proprietary original APKs, patched APK set, account data, signing key and fetched lyrics are intentionally excluded. - -## Completed - -- Version-pinned injection into the inspected Spotify TV 1.134.2 client. -- Native D-pad menu, three themes, cinematic motion toggle, own-session sleep timer and private local LRC import. -- Lyrics update 0.2: manual public LRCLIB lookup, timed and plain results, per-track in-memory cache, local-file precedence, font sizes and timing offset. -- Background lookup, bounded response size, request cooldown, connect/read timeouts and an overall watchdog. -- Reproducible four-APK build/signing script, original input hashes, deterministic tests and CI workflow. -- Independent source/attribution notices; no Eevee implementation or assets copied. - -## Next device checks - -The new **Lyrics · local / LRCLIB** panel was observed fetching and displaying timed lyrics for a real signed-in track. Continue testing provider coverage, track changes while fetching, local precedence, pause/seek/resume, timing offsets, long-running drift and D-pad scrolling of plain lyrics. See VERIFICATION.md for exactly which checks ran. - -## Building and updating - -Use the original four installation APKs from your own TV and the private signing key retained locally. `build.ps1` verifies their hashes and produces a fully signed four-APK set. Updating with the same key preserves the current app's data; a different key normally requires reinstalling and signing in again. Do not install just the base APK or mix certificates across splits. - -The extension's added network request is only the explicit LRCLIB lookup; no Spotify login credentials or entitlement values are processed by it. The runtime and its tests remain MIT licensed; the ReVanced host module is GPL-3.0-only under revanced/COPYING. See README.md, LYRICS.md and assets/INSPIRATION.md for scope and notices. +Read HUSH.md for setup and recovery limitations, README.md for build/install scope, and the current plan/spec under docs/superpowers. The native Settings selectors were verified against Spotify’s delivered Android TV web UI `ad3ec52`; future remotely delivered UI changes may need selector updates. diff --git a/HUSH.md b/HUSH.md index be7cde6..76bded6 100644 --- a/HUSH.md +++ b/HUSH.md @@ -1,39 +1,22 @@ -# Hush · Spotify+ TV +# Integrated Hush · one Spotify app -Version 0.6 adds **Hush · ad-break skipping** to the TV remote menu. It opens an optional companion adapted from [coldMEW/Hush 2.0.2](https://github.com/coldMEW/Hush), pinned to `4e9ded397338de5c69b1784c636feb3d34a8de01`. +Hush’s helper ships inside Spotify+ TV 1.3.0.1. There is no companion APK, extra launcher icon, notification-listener permission or Shizuku dependency. The shell-owned helper survives the Spotify process being stopped; Spotify’s next process resumes its own session. This adapts the restart strategy from coldMEW/Hush to the TV app’s native `is_ad_playing` signal. -Hush attempts to drop an ad break by restarting Spotify and resuming its new media session. Upstream measurements are for the phone client; they do not establish that Spotify TV will drop ads, keep the queue, or recover in the same time. This TV integration needs testing on the actual TV. Keep **Mute detected ads** on for player-local muting when restarting is unavailable or fails. A failed automatic attempt imposes a two-minute cooldown, with one attempt per break until real music resumes. +## Setup -## Build and install +1. Build/sign with the same retained private key as the existing TV installation, then update without uninstalling. The generated unsigned APK cannot be installed until signed. +2. Launch Spotify once. The app writes a private, token-bound startup script for its embedded helper. +3. Run `start-hush.ps1 -Serial TV_IP:5555` over your authorized ADB connection. The command stays private; the script does not print its token. Repeat after a TV reboot or APK update. The app remains debuggable as in the existing personal build so the installer can read this app-private startup command through `run-as`. +4. Open Spotify’s own Settings/profile screen. Under Spotify+ TV, check **Hush helper setup**, then turn **Hush ad-break skipping** on. Keep **Mute detected ads** on for the fallback. -1. Clone this repository with `git clone --recurse-submodules`, or run `git submodule update --init --recursive` in an existing checkout. -2. Run the existing `build.ps1` with the original four Spotify TV 1.134.2 APKs, Android SDK 35/build-tools 35.0.0, a JDK 17 installation, and the same retained signing key used for your existing TV installation. Gradle and Maven dependency access is required. The build now also creates `signed/Hush-TV.apk`. Set `SPTV_STORE_PASSWORD` and, if needed, `SPTV_KEY_PASSWORD` outside the repository. `-WithoutHush` builds only the four Spotify splits. -3. Run `install.ps1 -ApkDirectory -Serial `. This installs the companion first and then updates all four Spotify splits. There is no uninstall or data reset. Use `-WithoutHush` for a TV-only update. -4. In Spotify+ TV, press Menu or hold OK, choose **Hush · ad-break skipping**, then enable Hush. -5. Set up Hush's own helper using Wireless debugging on Android 11+, or authorize an already-running Shizuku on Android 8+. The original setup screens remain available; some TV firmware lacks the required Wireless debugging/pairing UI. On those TVs use Shizuku started with its documented computer/ADB setup. Helper availability after a reboot must be checked again. -6. Return to Spotify and start playback. The status screen should report a connected session. **Test Spotify restart** asks before interrupting playback. Check that the correct playlist resumes. Then test with a real ad. +The helper provider accepts only Android’s shell UID, requires the privileged cross-user permission and validates a random token from private app storage. Its adapted command builder accepts only the fixed restart action for `com.spotify.tv.android/.SpotifyTVActivity`; it rejects arbitrary actions/components. It does not install or control another application. -The GitHub Actions `Hush-TV-unsigned` artifact is an unsigned companion build. It must be signed using your TV key before installation. It is not an installable update to the proprietary Spotify APK set. No original APKs or signing keys are stored in this repository. +## Recovery and limits -## What crosses between the apps +Before requesting a restart, Spotify commits its recovery state. The helper executes the whole stop/allowlist/start sequence outside the dying app process. The new process waits for its own media session, retries play for at most 20 seconds, honors the sleep deadline even if the visible timer has already cleared, and falls back after failure. Attempts have a 30-second minimum interval; failed recovery imposes a two-minute cooldown. Paused ads are left alone. -The extension sends its own media-session token, native `is_ad_playing` flag, monotonic timestamp and sleep deadline to an explicit receiver. Both directions check the matching signing identity; the receiver also requires a signature permission. Old signals are rejected. No credentials, account entitlements or arbitrary shell commands are transmitted. The companion uses its native-session capability instead of requiring notification access on TV. +Whether restarting actually drops an ad break or preserves the queue depends on Spotify TV. Upstream phone timings do not establish TV behavior. This release needs real-device tests for ad-return behavior, queue context, helper loss, screen/background behavior, sleep expiry during restart, EQ reattachment and same-key updating. No calibrated audio or guaranteed ad-removal claim is made. -Hush is off by default. Enable/disable it in its TV screen. The companion never uses the upstream phone-wide ad-mute path: muting remains inside Spotify's player. Resume kicks target only Spotify's forwarded media session. The TV sleep deadline survives a Spotify process restart and is cleared after a TV reboot. If it expires during recovery, Hush stops attempting to resume playback. +## Reproducible source -DNS filtering is not required and stays off by default. The upstream optional VPN implementation remains in the separate companion; it is not activated by the TV feature or build/install scripts. - -## Source and license - -The upstream `hush/upstream` gitlink is unmodified. `hush/prepare.py` verifies that exact commit and clean tracked source, copies only tracked Android files into a new build directory, retargets Spotify's package, replaces the global-mute watcher path, connects native TV sessions, and adds `hush/overlay`. All adaptation is visible in these tracked files. Generated source is under `hush/build/android` and ignored by git. - -Hush and the companion adaptations are GPL-3.0. The companion embeds the full upstream license and a source notice. The independent TV protocol adapter remains part of the MIT extension; no Hush implementation is linked into it. The ReVanced host retains its existing GPL license. None of these licenses relicense Spotify binaries. - -## Device checks still required - -- Pairing/helper setup and D-pad navigation on the actual firmware. -- New-session delivery and playback recovery after a test restart and a real ad. -- Playlist/queue behavior, ad-return failure, and the two-minute failure cooldown. -- Local mute restoration and whether EQ reattaches to the new Spotify audio session. -- Sleep expiry before/during restart, a background Spotify session, helper loss, and reboot recovery. -- Same-key updates preserve existing pairing, settings, lyrics and app data. +`hush/upstream` is an unchanged pinned submodule. `hush/prepare.py` verifies its commit and clean tracked source, then extracts/adapts eight helper classes under `dev.aurora.tvpatch.hush` into a new generated source directory. The command restriction, TV target, provider authority and protocol version changes are visible in that script. These helper portions are GPL-3.0; their full license and source notice are included in the APK. No phone UI, VPN/DNS filtering, notification watcher, global-volume mute or account handling is imported. diff --git a/README.md b/README.md index b2a0beb..aeb5268 100644 --- a/README.md +++ b/README.md @@ -1,126 +1,24 @@ -# Spotify+ TV 0.6 · Hush integration +# Spotify+ TV 1.3.0.1 -Adds **Hush · ad-break skipping** to the remote menu, backed by a separately installed Hush TV companion. The companion is opt-in, uses the native TV ad flag and matching-signature session bridge, and keeps restart recovery outside Spotify’s process. Existing local ad muting remains the fallback. The TV sleep timer now survives Spotify process restarts. See [HUSH.md](HUSH.md) for setup, builds, GPL source attribution and required TV checks. +A personal modification of the inspected Spotify TV 1.134.2 ARMv7 client. **One installed Spotify app**, with the custom controls integrated into Spotify’s existing Settings/profile menu. -This is a source integration; actual TV ad skipping and queue recovery still require device verification. +- **Native settings:** appearance, artwork blur, motion, promotion hiding, player-local ad muting, Hush, EQ, lyrics and sleep timer. The existing Spotify rows stay in place. Menu/F1 or hold OK opens Spotify’s own Settings screen. +- **Graphic EQ:** dark rounded panel, blue vertical controls and connected curve inspired by the supplied reference. Ten frequency points from 31 Hz to 16 kHz map logarithmically onto the output’s available hardware bands. EQ stays ±6 dB; post-gain stays 0–6 dB. Existing five-band settings migrate once. Left/Right selects, Up/Down adjusts, OK moves to post-gain and then toolbar, Back closes. +- **Integrated Hush:** the helper code ships inside Spotify’s APK. An authorized ADB setup starts a shell-owned helper process, which can survive Spotify’s force-stop and relaunch it. No companion app or Shizuku installation is required. Hush is opt-in; helper setup is required after a TV reboot or APK update. See [HUSH.md](HUSH.md). +- **Existing features:** Spotify-only audio effects, local/LRCLIB lyrics, Aurora/Midnight/Ember appearance, artwork blur, motion, promotion hiding and sleep timer. The timer survives Spotify process restarts and clears on a TV reboot. -## Version 0.5 presentation improvements +## Build and install -Version 0.5 fixes themes across the actual TV interface: class-based focus outlines, primary actions, playback progress, playing-track labels and context menus. Aurora, Midnight and Ember colors now use the TV selectors verified on the installed UI; Spotify Original restores the original colors. Artwork/layout and existing player functions remain in place. +The rebuilt **single APK** is labeled `1.3.0.1`. It retains Android versionCode `2340200` from the inspected client. This is a personal extension version, not an upstream Spotify release. The build merges the inspected ARMv7/English/TV-density splits into one file; it is not an all-architecture universal package. -Promotion hiding now covers Upgrade text, navigation offers, banners, options and accessible labels, rather than only exact button captions. The extension's own setting is called **Hide promotions**. Reused controls are restored when their content changes; containers with unrelated playback controls are preserved. +`rebuild_release.py` verifies the exact previous v0.5 installation archive, replaces only the extension definitions/assets, adds the guarded embedded helper provider, updates the version name and merges the split resources/libraries. It produces an **unsigned APK**, which must be signed with the existing retained key to update your installed app. The original key is not stored here. Use `sign-apk.ps1`; do not uninstall or clear data to work around a mismatched key. -The extension keeps one presentation controller per page, coalesces relevant DOM changes, batches artwork reads/writes and skips layout scans for unchanged settings, focus/progress changes and opacity-only fades. Audio configuration and hardware band mappings are cached, unchanged EQ settings perform no repeated hardware writes, playback/metadata use callbacks, closed dialogs release their views, and lyrics keep 250 ms updates while idle work drops to once per second. Existing lyrics, artwork blur, motion, sleep timer, recognized-ad muting and Spotify-session EQ/boost remain available. Your saved settings are retained by a same-key update. +GitHub Actions builds the unsigned APK and runs source/helper, native-settings, presentation, audio, lyrics and patch-fingerprint checks. Actual TV install, D-pad behavior, ad skipping, recovery/queue behavior and audio output still need device verification for this release. Earlier 0.5 device observations are documented separately in [VERIFICATION.md](VERIFICATION.md). -Version 0.4 adds **Spotify-session EQ and volume boost**, keeps the original artwork-driven appearance with optional blur and accent colors, hides the visible Upgrade button by default, and simplifies the native TV interface. See [audio setup](AUDIO.md). The audio engine never attaches to the shared output mix. A one-time ADB diagnostic permission is required on this inspected Android 10 TV to identify only the current Spotify process's active audio sessions. New installs leave EQ/boost off; updates retain your settings. +The original four-APK source build is also supported by `build.ps1` with your own original inputs and key. `install.ps1` installs that set, grants the existing audio diagnostic permission, launches Spotify and starts the embedded helper. For a signed single APK use `adb install -r`, grant `android.permission.DUMP`, launch Spotify, then run `start-hush.ps1`. -Spicetify CLI (https://github.com/spicetify/cli) inspired the CSS/presentation approach. It targets desktop clients. No Spicetify source, extension, ad blocker or asset is copied or bundled. This extension does not include an ad SDK, DNS/VPN service, or WebView network-request blocker. Its WebView changes affect presentation; native recognized ad breaks can be muted, and their duration still passes. +## Source and attribution -The injected Java runtime and original JavaScript remain MIT licensed under LICENSE. The separate Kotlin ReVanced host module uses GPL-3.0-only under revanced/COPYING; its host dependencies are not injected into Spotify. +Original UI, lyrics and audio implementation is MIT licensed. The helper sources/adaptations from [coldMEW/Hush](https://github.com/coldMEW/Hush), pinned to `4e9ded397338de5c69b1784c636feb3d34a8de01`, are GPL-3.0 and embedded with their full license/source notice. The ReVanced build host retains its GPL license. Clone with `--recurse-submodules` to obtain the pinned helper source. None of these licenses relicense Spotify’s proprietary code, assets or recordings. -Version 0.3 adds **detected-ad muting, enabled by default**, and a modular Kotlin ReVanced patch bundle. Muting observes the native `is_ad_playing` signal and changes Spotify's player-local volume. It remembers requested volume and restores it when the break ends, the setting is disabled, or the signal becomes stale after three minutes. It does not skip ad time, remove ads from the stream, or change subscription status. If player volume has not been observed, it does not guess a volume. Use **Mute detected ads** in the native settings menu to turn it off. - -See [modular patching](revanced/README.md) for patch types, fingerprints, dependencies, extensions, and license boundaries. The old `patch.py` is a legacy 0.2 path and does not install ad muting; use `build.ps1` for 0.3. - -This is an actual extension injected into the user's Spotify Android TV **1.134.2** installation (`com.spotify.tv.android`), rather than the separate Aurora companion. It is version-specific and intended for personal testing on the inspected Android 10 TV. - -## Included - -- An in-app native TV settings panel opened with **Menu**, **F1**, or **hold OK/Select and release**. -- Spotify original colors or Aurora/Midnight/Ember accents, following existing focus styles and artwork-derived page colors. -- Optional blur/blending of fullscreen background artwork and decorative images, preserving text, controls and foreground album covers. Where appropriate, a backdrop uses artwork already loaded by the page. Motion has an on/off control and respects reduced-motion preferences. -- Upgrade-button presentation filtering, enabled by default; this does not grant subscription features or remove the ad-break timeline. -- Five EQ controls and 0 to +6 dB LoudnessEnhancer boost, attached only to this process's verified positive audio sessions. See AUDIO.md. -- A sleep timer (15/30/60 minutes/cancel), using the current Spotify process's **own Android media-session token** and `MediaController.TransportControls.pause()`. -- A native line-synchronized lyrics overlay for **your own or licensed local LRC files**, with a Play/Pause button targeting the same Spotify session. Timing reads the native media session and interpolates progress. -- Optional **Fetch from LRCLIB** lookup for the current track, timed lyrics when available, and a scrollable plain-lyrics fallback. Lookups are manual, use HTTPS and send only track title, artist, album and duration to `lrclib.net`. -- Lyrics text sizes of 24/30/36 sp and a persistent timing correction from −1000 to +1000 ms. Positive timing advances the highlighted line. -- Larger existing TV lyric text where Spotify's own web UI uses compatible lyric markers. - -The patch keeps Spotify's login, audio engine, entitlements and DRM. It adds no streaming implementation, private Spotify API requests, premium bypass or token harvesting. No developer Client ID is needed: use Spotify's normal TV login. LRCLIB is an optional external service; its lyrics remain subject to rightsholders' rights and provider availability. - -## What is not ported - -This is a first TV-specific subset, **not the full mobile SpotifyPlus module**. It does not supply a commercial lyrics catalog, word-by-word vocals, translations, animated album-art catalog, Last.fm integration, persistent private-session enforcement, restored mobile Like button, or modified queue/history behavior. Original playback and queue features remain Spotify's own. Local LRC synchronization is line-level and depends on the metadata/progress Spotify exposes to its media session. - -## On the TV - -Open **Spotify+ TV**, sign in through Spotify, then press Menu or hold OK and release. Short OK presses are forwarded as a balanced down/up pair to the original app. Use D-pad and OK to choose settings; Back closes a dialog. Themes and motion settings persist; the sleep timer is process-local and does not survive a Spotify process restart. Keep Spotify running until it expires. - -This installation required replacing the signed official package. Its previous local sign-in was not preserved. Signing in again is expected. Future Play Store updates cannot normally update this build because the certificate differs; restoring the official client also requires reinstalling it. The Play Store/native platform can reject a modified build or limit certificate-bound features such as Cast; those are not bypassed here. - -## Import local lyrics - -Open **Lyrics · local / LRCLIB** from the injected menu. Press **Fetch from LRCLIB** to request lyrics for the current song. Timed results use the existing playback clock; if only plain lyrics are available, choose **Plain lyrics** and use Up/Down to scroll, Back to close. Valid local LRC files take priority. A request cooldown and overall timeout prevent repeated or indefinitely pending lookups. No lookup happens automatically on track changes. - -Only the most recent 12 fetched records are kept in process memory. They disappear when Spotify's process exits. No Spotify token or account identifier is sent to LRCLIB. See [lyrics behavior and handoff notes](LYRICS.md). - -Start the desired song, open **Lyrics · local / LRCLIB**, and note the exact filename shown when no local lyrics are loaded. Usually it is the Spotify track's 22-character ID plus `.lrc`; if no ID is exposed, the overlay shows a `track-...lrc` fallback derived from title and artist. - -Create a UTF-8 `.lrc` using words you have permission to use: - -```lrc -[offset:0] -[00:00.00]The room is still -[00:05.00]The night unfolds -[00:10.00]A little light to lead us home -``` - -With ADB authorized: - -```powershell -python import_lyrics.py "C:\My Lyrics\song.lrc" --name EXACT_FILENAME.lrc --serial TV_IP:5555 --adb "C:\platform-tools\adb.exe" -``` - -The helper writes atomically into the app-private `files/sptv-lyrics` directory using debug `run-as`. It does not write to shared TV storage or read login data. This personal build is deliberately debuggable to support this import; disable TV debugging when not in use and authorize only trusted PCs. - -## Package and restore - -The `.apks` download is a ZIP containing **four APKs**: patched base, ARMv7 native-library split, English split, and TV-density split. It is specific to the installation that was inspected. Do not install only the base APK or mix differently signed splits. It is not a universal standalone APK for other devices. - -Extract and install all four with Platform Tools: - -```powershell -adb install-multiple -r base.apk split_config.armeabi_v7a.apk split_config.en.apk split_config.tvdpi.apk -``` - -For a first install over the official package, Android's signing rules require removing that package first. **Uninstalling clears local login/settings.** To restore the official client, uninstall the patched package and install Spotify again from the TV's store, or extract the separately saved original-installation backup ZIP and install its four original APKs together. That backup contains installation files, not the previous account session. - -## Rebuild the patch - -The checked Windows build entrypoint is `build.ps1`. It checks all four input APK hashes, compiles the Java extension, runs D8, invokes the version-pinned patcher, aligns and signs each APK, and verifies the signatures. It requires a new output directory and makes no TV changes: - -```powershell -$env:SPTV_STORE_PASSWORD = 'YOUR_KEYSTORE_PASSWORD' -# Set SPTV_KEY_PASSWORD too if the key password differs. -.\build.ps1 -OriginalDirectory C:\private\original-apks -AndroidSdk C:\Android\sdk -JavaHome C:\Java\jdk-17 -KeyStore C:\private\signing.keystore -KeyAlias YOUR_ALIAS -OutputDirectory C:\builds\sptv-04 -``` - -Keep your signing key private and out of GitHub. The existing personal build's key was retained locally, and is not in this repository. A new signing key requires reinstalling the package and signing into Spotify again. - -Inputs: original four APKs from your own TV, JDK 17, Android SDK Platform 35/Build Tools 35.0.0, Python 3.10+, and [Apktool 2.11.1](https://github.com/iBotPeaches/Apktool/releases/tag/v2.11.1). No proprietary original APK is included in this source ZIP. The original backup and patched installation set are separate personal deliverables; do not publish them as MIT software. - -1. Compile `src/dev/aurora/tvpatch/*.java` with `javac -encoding UTF-8 -source 8 -target 8 -cp ANDROID_SDK/platforms/android-35/android.jar -d classes`. -2. Package these classes with `jar cf extension.jar -C classes .` and run SDK D8 with `--min-api 26 --lib android.jar --output dex extension.jar`. -3. Run `python patch.py --base ORIGINAL/base.apk --apktool apktool.jar --java PATH_TO_JAVA --work NEW_BUILD_DIRECTORY --dex dex/classes.dex --framework FRAMEWORK_CACHE_DIRECTORY`. -4. The script verifies the inspected base APK SHA-256, decodes it, inserts five version-specific hook locations, adds the extension dex and assets, and rebuilds an unsigned APK. Mismatched original inputs are rejected. `--work` must be new; nothing is recursively overwritten. -5. Zip-align the modified base and all original splits (`zipalign -P 16 -f 4`), then sign **all four with the same personal key** using `apksigner`. Verify every APK before installing. Retain that key privately if you want to update your patched installation without uninstalling it. - -Local parser/timing tests: - -```powershell -javac -encoding UTF-8 -d test-classes src/dev/aurora/tvpatch/Lyrics.java tests/LyricsTest.java -java -ea -cp test-classes LyricsTest -``` - -Provider parser/query tests are in `tests/ProviderTest.java`; they use JSON-java 20240303 as a **test-only** dependency. The runtime uses Android's built-in JSON implementation. `.github/workflows/test.yml` downloads the test JAR from Maven Central, verifies its SHA-256, then runs both deterministic test programs. `ProviderLiveTest` is an optional online smoke test and is excluded from normal CI. - -## Privacy and licensing - -The extension's only added network operation is a user-initiated HTTPS lookup to LRCLIB with song metadata. It does not read OAuth/session secrets. Spotify's original networking/analytics remain those of the original application. Local preferences and imported LRC files remain app-private. Fetched records are held in bounded process memory. Clearing app data or uninstalling removes local files/settings. The own-session token stays in process memory and is never exported or printed. Extension diagnostic logs contain only attach/capture state and its own CSS result, not account data or lyric text. - -The original extension source is MIT licensed. It is inspired by [LeNerd46/SpotifyPlus](https://github.com/LeNerd46/SpotifyPlus), MIT, © 2025 Devon Shoutz; the notice is preserved in `assets/SPOTIFYPLUS-LICENSE.txt`. No upstream fonts, artwork, commercial lyrics, or mobile hook implementation are bundled. Spotify's app, native libraries, artwork and branding retain their own rights. The MIT license applies only to the extension's original source, not the patched proprietary application. - -The lyrics update is also inspired by [EeveeSpotifyReincarnated](https://github.com/SideloadLabs/EeveeSpotifyReincarnated). Eevee is GPL-3.0 licensed and targets iOS. No Eevee source, assets or hooks are incorporated. The LRCLIB client is independently written against [LRCLIB's documented API](https://lrclib.net/docs). See `assets/INSPIRATION.md`. - -See VERIFICATION.md for actual checks and outstanding account/playback testing. +The build does not edit Spotify credentials, subscriptions or account entitlements. The local volume fallback affects only Spotify’s player; the graphic EQ attaches only to positive audio sessions owned by Spotify. There is no shared-output effect fallback. Optional manual LRCLIB lookup sends song title, artist, album and duration to that provider; see [LYRICS.md](LYRICS.md). Audio diagnostics remain in memory; see [AUDIO.md](AUDIO.md). diff --git a/assets/HUSH-COPYING.txt b/assets/HUSH-COPYING.txt new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/assets/HUSH-COPYING.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/assets/HUSH-NOTICE.txt b/assets/HUSH-NOTICE.txt index a77f960..602035a 100644 --- a/assets/HUSH-NOTICE.txt +++ b/assets/HUSH-NOTICE.txt @@ -1,12 +1,9 @@ -Hush companion integration - -The MIT Spotify+ TV extension communicates with a separately installed Hush TV companion. -The companion is derived from coldMEW/Hush 2.0.2, commit -4e9ded397338de5c69b1784c636feb3d34a8de01, under GPL-3.0. +Integrated Hush helper · Spotify+ TV 1.3.0.1 +Eight helper source files adapted from coldMEW/Hush 2.0.2, commit +4e9ded397338de5c69b1784c636feb3d34a8de01, are embedded in Spotify's APK. +The helper/adaptations are GPL-3.0; full license: HUSH-COPYING.txt. +Source and reproducible adaptations: https://github.com/AlphadogRSA/spotifyplus-tv-patch Upstream: https://github.com/coldMEW/Hush -Adaptation, pinned source, modifications and build instructions: -https://github.com/AlphadogRSA/spotifyplus-tv-patch/tree/feat/hush-tv/hush - -The companion includes the full upstream GPL license and a source notice. -The companion's license does not relicense Spotify's proprietary binaries. +The original UI/lyrics/EQ source retains its MIT license. No license here +relicenses Spotify's proprietary binaries or artwork. diff --git a/assets/spotifyplus-settings.js b/assets/spotifyplus-settings.js new file mode 100644 index 0000000..91ed751 --- /dev/null +++ b/assets/spotifyplus-settings.js @@ -0,0 +1,97 @@ +function(config) { + 'use strict'; + var old = window.__sptvSettings; + if (old) return old.configure(config); + var cfg = config, section = null, host = null, previous = null, scheduled = false; + var rows = [ + ['theme','Appearance','theme'], ['blur','Artwork blur','blurArtwork'], + ['motion','Cinematic motion','motion'], ['promotions','Hide promotions','hideUpgrade'], + ['mute','Mute detected ads','muteAds'], ['hush','Hush ad-break skipping','hushEnabled'], + ['hushSetup','Hush helper setup','hushStatus'], ['audio','Graphic equalizer','audioStatus'], + ['lyrics','Lyrics','Local files / LRCLIB'], ['sleep','Sleep timer','sleep'], + ['about','About Spotify+ TV','version'] + ]; + var style = document.createElement('style'); style.id = 'sptv-native-settings-style'; + style.textContent = '.sptv-settings-host{max-height:calc(100vh - 20rem);overflow-y:auto;padding-right:1rem;scrollbar-width:thin}' + + '#sptv-native-settings{color:inherit;font:inherit;padding-bottom:3rem}' + + '#sptv-native-settings h2{font:inherit;font-weight:700;margin:3rem 0 2rem}' + + '#sptv-native-settings .profile-menu-item{min-height:8rem;box-sizing:border-box}' + + '#sptv-native-settings button{display:block;width:100%;background:transparent;color:inherit;border:0;text-align:left;font:inherit;padding:1rem;border-radius:.5rem}' + + '#sptv-native-settings button:focus{outline:.4rem solid var(--sptv-settings-accent,#1ed760);outline-offset:.5rem}' + + '#sptv-native-settings .profile-menu-item__subtitle{font-size:.75em;opacity:.7;margin-top:1rem}'; + (document.head || document.documentElement).appendChild(style); + function invoke(action) { + if (window.SpotifyPlusSettings && window.SpotifyPlusSettings.action) window.SpotifyPlusSettings.action(action); + } + function label(row) { + if (row[0] === 'theme') return ['Spotify original','Aurora','Midnight','Ember'][Math.abs(Number(cfg.theme)||0)%4]; + if (row[0] === 'sleep') return cfg.sleep || 'Off'; + if (Object.prototype.hasOwnProperty.call(cfg,row[2])) { + var value = cfg[row[2]]; return typeof value === 'boolean' ? value ? 'On' : 'Off' : String(value); + } + return row[2]; + } + function sync() { + scheduled = false; + var next = document.querySelector('[data-testid="profile-menu"],.profile__menu'); + if (!next) { if(section && section.parentNode)section.remove(); section=null;host=null;return; } + if (!section || section.parentNode !== next) { + if(section)section.remove(); + host=next; host.classList.add('sptv-settings-host'); + section=document.createElement('section'); section.id='sptv-native-settings'; section.setAttribute('aria-label','Spotify+ TV settings'); + var title=document.createElement('h2'); title.textContent='Spotify+ TV'; section.appendChild(title); + var nativeControl=host.querySelector('.profile-menu-item > :first-child'); + rows.forEach(function(row) { + var item=document.createElement('div'); item.className='profile-menu-item sptv-setting-row'; + var button=document.createElement('button'); button.type='button';button.tabIndex=0;button.dataset.sptvAction=row[0]; + if(nativeControl)button.className=String(nativeControl.className||'').replace(/\S*--focused\S*/g,'').trim(); + var name=document.createElement('span');name.textContent=row[1];button.appendChild(name); + var value=document.createElement('p');value.className='profile-menu-item__subtitle';button.appendChild(value); + button.addEventListener('click',function(event){event.preventDefault();event.stopPropagation();invoke(row[0]);}); + button.addEventListener('focus',function(){button.scrollIntoView({block:'nearest'});}); + item.appendChild(button);section.appendChild(item); + }); + host.appendChild(section); + } + section.style.setProperty('--sptv-settings-accent',['#ffffff','#91e7cf','#bbb3ff','#ffffbf98'][Math.abs(Number(cfg.theme)||0)%4]); + rows.forEach(function(row) { + var button=section.querySelector('[data-sptv-action="'+row[0]+'"]'), value=label(row); + var subtitle=button.querySelector('p'); if(subtitle.textContent!==value)subtitle.textContent=value; + button.setAttribute('aria-label',row[1]+': '+value); + }); + } + function defer(records) { + if(records.every(function(record){return record.target.nodeType===1 && record.target.closest('#sptv-native-settings');}))return; + if(!scheduled){scheduled=true;Promise.resolve().then(sync);} + } + var observer=new MutationObserver(defer);observer.observe(document.documentElement,{childList:true,subtree:true}); + function key(event) { + if(!section)return; + var key=event.key, button=event.target.closest && event.target.closest('#sptv-native-settings button'); + var controls=Array.prototype.slice.call(section.querySelectorAll('button')); + if(!button) { + if(key!=='ArrowDown')return; + var nativeRows=Array.prototype.slice.call(host.querySelectorAll('.profile-menu-item')).filter(function(row){return !section.contains(row);}); + var last=nativeRows[nativeRows.length-1]; + if(!last || !(last.contains(document.activeElement)||last.querySelector('[class*="--focused"]')))return; + previous=last.querySelector('button,[tabindex],[role="button"]')||document.activeElement; + controls[0].focus(); + } else { + var index=controls.indexOf(button); + if(key==='ArrowDown')controls[Math.min(controls.length-1,index+1)].focus(); + else if(key==='ArrowUp') { + if(index===0 && previous && previous.isConnected){previous.focus();previous.scrollIntoView({block:'nearest'});} + else controls[Math.max(0,index-1)].focus(); + } else if(key==='Enter' || key===' ' || key==='ArrowRight' || key==='ArrowLeft')invoke(button.dataset.sptvAction); + else return; + } + event.preventDefault();event.stopImmediatePropagation(); + } + document.addEventListener('keydown',key,true); + var api={configure:function(next){cfg=next;sync();return !!section;},open:function(){ + var nativeButton=document.querySelector('[data-testid="top-menu--settings"]'); + if(nativeButton){nativeButton.click();return true;} + return !!document.querySelector('[data-testid="profile-menu"],.profile__menu'); + },dispose:function(){observer.disconnect();document.removeEventListener('keydown',key,true);if(section)section.remove();if(host)host.classList.remove('sptv-settings-host');style.remove();}}; + window.__sptvSettings=api;sync();return !!section; +} diff --git a/build.ps1 b/build.ps1 index bdca1bc..b30c6e0 100644 --- a/build.ps1 +++ b/build.ps1 @@ -6,8 +6,7 @@ param( [Parameter(Mandatory)][string]$KeyStore, [Parameter(Mandatory)][string]$OutputDirectory, [string]$KeyAlias = 'androiddebugkey', - [string]$GradleExecutable, - [switch]$WithoutHush + [string]$GradleExecutable ) $ErrorActionPreference = 'Stop' if (-not $env:SPTV_STORE_PASSWORD) { throw 'Set SPTV_STORE_PASSWORD for your own keystore; never commit the key or password.' } @@ -28,7 +27,13 @@ $out = (Resolve-Path -LiteralPath $OutputDirectory).Path foreach ($name in @('classes','dex','framework','aligned','signed')) { New-Item -ItemType Directory -Path (Join-Path $out $name) | Out-Null } $env:JAVA_HOME = $jdk function Check-Exit([string]$Stage) { if ($LASTEXITCODE -ne 0) { throw "$Stage failed ($LASTEXITCODE)" } } +git -C $PSScriptRoot submodule update --init --recursive +Check-Exit 'Pinned Hush helper source' +$generated = Join-Path $out 'hush-generated' +python (Join-Path $PSScriptRoot 'hush/prepare.py') --output $generated +Check-Exit 'Hush helper preparation' $sources = Get-ChildItem -LiteralPath (Join-Path $PSScriptRoot 'src/dev/aurora/tvpatch') -Filter '*.java' | ForEach-Object FullName +$sources += Get-ChildItem -LiteralPath $generated -Recurse -Filter '*.java' | ForEach-Object FullName & (Join-Path $jdk 'bin/javac.exe') -encoding UTF-8 -source 8 -target 8 -cp $androidJar -d (Join-Path $out 'classes') @sources Check-Exit 'Java compilation' & (Join-Path $jdk 'bin/jar.exe') cf (Join-Path $out 'extension.jar') -C (Join-Path $out 'classes') . @@ -41,7 +46,7 @@ Check-Exit 'Verified patcher download' if (-not $GradleExecutable) { $GradleExecutable = Join-Path $patchProject 'gradlew.bat' } & $GradleExecutable -p $patchProject testFingerprints bundle "-PextensionDex=$(Join-Path $out 'dex/classes.dex')" Check-Exit 'Kotlin patch compilation and fingerprint tests' -$bundle = Join-Path $patchProject 'build/libs/spotifyplus-tv-0.6.rvp' +$bundle = Join-Path $patchProject 'build/libs/spotifyplus-tv-1.3.0.1.rvp' $classpath = $bundle + [IO.Path]::PathSeparator + (Join-Path $patchProject '.tools/revanced-cli-6.0.0-all.jar') & (Join-Path $jdk 'bin/java.exe') -cp $classpath dev.aurora.patches.RunnerKt apply $bundle (Join-Path $original 'base.apk') (Join-Path $out 'patched-unsigned.apk') (Join-Path $out 'patch') (Join-Path $tools 'aapt2.exe') Check-Exit 'Modular patching and APK rebuild' @@ -59,8 +64,5 @@ foreach ($entry in $hashes.PSObject.Properties) { & (Join-Path $tools 'apksigner.bat') verify --min-sdk-version 26 $signed Check-Exit 'Signature verification' } -if (-not $WithoutHush) { - & (Join-Path $PSScriptRoot 'hush/build.ps1') -AndroidSdk $sdk -JavaHome $jdk -KeyStore $signingKey -KeyAlias $KeyAlias -OutputApk (Join-Path $out 'signed/Hush-TV.apk') -} Compress-Archive -Path (Join-Path $out 'signed/*.apk') -DestinationPath (Join-Path $out 'SpotifyPlus-TV-patched.zip') -Write-Output "Verified installation set (Spotify splits plus optional Hush companion): $(Join-Path $out 'signed')" +Write-Output "Verified four-APK installation set: $(Join-Path $out 'signed')" diff --git a/docs/superpowers/plans/2026-10-27-hush-tv.md b/docs/superpowers/plans/2026-10-27-hush-tv.md index fd6d039..d152c13 100644 --- a/docs/superpowers/plans/2026-10-27-hush-tv.md +++ b/docs/superpowers/plans/2026-10-27-hush-tv.md @@ -1,43 +1,48 @@ -# Hush TV Implementation Plan +# Spotify+ TV 1.3.0.1 Implementation Plan -> **For agentic workers:** Use superpowers:executing-plans to implement task-by-task. +> **For agentic workers:** Use superpowers:executing-plans task-by-task. -**Goal:** Add opt-in Hush restart skipping to the existing TV application. +**Goal:** One Spotify APK with embedded Hush, native settings and graphic EQ. -**Architecture:** A pinned upstream Hush companion receives trusted native ad flags and session tokens from the MIT TV extension. The companion owns restart/recovery; the extension retains player-local mute and persists its timer. +**Architecture:** A pinned shell-owned Hush helper survives Spotify force-stop. The current process commits recovery state; the new process resumes its own session. Native profile settings host the restricted controls. The target EQ curve maps to actual output bands. -**Tech Stack:** Java 8 extension, Java 17 Android companion, Android SDK 35, Python preparation script, Kotlin ReVanced patches. +**Tech Stack:** Java 8/Android SDK 35, Python tooling, Kotlin/ReVanced, Playwright. **Spec:** ../specs/2026-10-27-hush-tv-design.md ## Global Constraints -- Spotify TV 1.134.2; Android 8+; same signing key for companion and TV app. -- Pin upstream 4e9ded397338de5c69b1784c636feb3d34a8de01; retain GPL notices. -- No global-volume mute, arbitrary external commands, private keys or original APKs in git. +- One installed Spotify app, versionName 1.3.0.1, versionCode 2340200. +- Retain player-local mute, existing settings, lyrics and Spotify-only effects. +- Pinned upstream 4e9ded397338de5c69b1784c636feb3d34a8de01; GPL notices accompany helper code. +- No private key, account data or original client inputs in git. ## Review Focus -- Duplicate native callbacks must not trigger restart loops. -- Late/stale tokens must not replace an active new session. -- Missing companion or helper leaves player-local muting usable. -- Sleep deadline expiry must suppress restart and survive Spotify process death. -- Signature checks must guard both incoming commands and outgoing session tokens. - -### Task 1: Companion preparation and skip policy -Files: `hush/prepare.py`, `hush/overlay/`, `hush/tests/`, upstream gitlink. -Interfaces: `prepare(destination)` creates an adapted Android project; `TvSkipPolicy.shouldSkip(...)` latches attempts until real music resumes. -- [ ] Add and run failing preparation and policy tests. -- [ ] Implement reproducible pinned preparation, native-signal receiver, remote setup and session adapter around Hush's skipper. -- [ ] Run preparation/policy tests and Android Gradle tests/build. - -### Task 2: TV integration and timer continuity -Files: `HushClient.java`, `Hooks.java`, `SleepDeadline.java`, manifest patch, `tests/SleepDeadlineTest.java`. -Interfaces: `HushClient.signal(context, token, ad, sleepAt)` sends trusted state; `HushClient.open(activity)` opens companion; `SleepDeadline` validates persisted deadlines. -- [ ] Test deadline expiry and restart restoration before implementation. -- [ ] Add companion launch, session/ad forwarding and persisted timer. -- [ ] Compile extension and run original deterministic/presentation tests. - -### Task 3: Build, installation, documentation and CI -Files: `build.ps1`, `install.ps1`, Hush build script, `.github/workflows/test.yml`, `HUSH.md`, notices/handoff. -- [ ] Build/sign companion with same retained key; install before Spotify splits, with no uninstall/data reset. -- [ ] CI prepares pinned upstream, runs all companion unit tests and builds an APK artifact. -- [ ] Record measured checks separately from pending device tests; review diff and publish a reviewable PR. +- Repeated ad signals and failure must not cause restart loops. +- The restart command must outlive the calling app process. +- A timer expiring during restart must prevent subsequent play commands. +- Settings rows must appear only in the real native settings host; native rows stay usable. +- Missing helper, dead media session and missing signing key must be reported accurately. + +### Task 1: Embedded helper/recovery +Files: `hush/prepare.py`, `HushIntegration.java`, `HushPolicy.java`, `start-hush.ps1`, helper tests. +- [x] Pin/extract the eight helper classes and restrict command target/action. +- [x] Implement persisted recovery, timeout/cooldown and pending sleep deadline. +- [x] Compile helper/runtime and test source preparation/policy boundaries. + +### Task 2: Graphic EQ +Files: `GraphicEq*.java`, `AudioEffectPlan.java`, `AudioDsp.java`, `Hooks.java`, EQ tests. +- [x] Write failing interpolation/migration/cache tests, then implement the curve. +- [x] Add the dark native chart, blue controls and remote/touch/accessibility interaction. +- [x] Preserve limits, hardware clamping, effect caches and existing settings. + +### Task 3: Native settings +Files: `spotifyplus-settings.js`, `NativeSettings.java`, `Hooks.java`, native settings browser test. +- [x] Inspect the delivered TV settings DOM and keep original rows. +- [x] Add scoped rows, fixed-action bridge, state synchronization and D-pad entry/return. +- [ ] Run browser regressions in CI and review the settings layout. + +### Task 4: Rebuild and delivery +Files: `rebuild_release.py`, build/install/sign scripts, manifest patch, CI, notices/docs. +- [x] Add pinned-source upgrade and single APK merge with explicit unsigned output. +- [ ] Complete local rebuild, inspect final version/provider/classes/resources and run CI. +- [ ] Publish final source/verification and deliver the unsigned build with signing limitation. diff --git a/docs/superpowers/specs/2026-10-27-hush-tv-design.md b/docs/superpowers/specs/2026-10-27-hush-tv-design.md index da17c10..4b450a7 100644 --- a/docs/superpowers/specs/2026-10-27-hush-tv-design.md +++ b/docs/superpowers/specs/2026-10-27-hush-tv-design.md @@ -1,9 +1,11 @@ -# Hush support for Spotify+ TV +# Spotify+ TV 1.3.0.1 design -The user approved adding Hush as a TV app feature, using a companion to survive Spotify restarts. Add a remote-friendly Hush menu entry and an independently installed companion derived from coldMEW/Hush 2.0.2 at `4e9ded397338de5c69b1784c636feb3d34a8de01`. Preserve themes, lyrics, EQ and player-local muting. Persist the TV sleep deadline across process restarts. +The user requests one installed Spotify app with Hush functionality embedded, a graphic EQ matching the supplied dark/blue reference, custom controls inside Spotify’s existing settings panel, and versionName 1.3.0.1. -The companion uses Hush's existing helper/Shizuku restart engine. TV native ad flags and own-session tokens cross an explicit, signature-protected receiver; both APKs must be signed with the user's existing key. No arbitrary shell commands or account changes are added. Native session forwarding avoids depending on TV notification access. Restart skipping is opt-in, deduplicated, and falls back to existing local muting when unavailable. Never use Hush's phone-wide volume mute on TV. +Embed only eight GPL helper classes from coldMEW/Hush 2.0.2 at 4e9ded397338de5c69b1784c636feb3d34a8de01. Start the shell-owned helper through authorized ADB, so it survives Spotify force-stop. Restrict its adapted command builder to the fixed Spotify TV restart. Persist recovery state before stopping; the new app process recovers its own media session with time bounds, cooldown and sleep protection. Keep local muting as fallback. No companion application, VPN, phone UI or account/entitlement changes. -Approaches considered: embedding everything loses the helper on each Spotify restart; a separately signed companion survives and keeps GPL code separate from the MIT extension. The user chose the companion approach. Keep upstream as a pinned submodule and apply explicit reproducible TV changes in a build preparation script, with attribution and GPL source available. Do not copy GPL implementation into the MIT extension. +Place all entry controls in the observed native profile settings menu, preserving Spotify rows and its focus styling. Restrict the WebView bridge to fixed settings actions on allowed Spotify main pages. The shortcut opens native Settings. EQ/lyrics/timer are native subpanels reached from these rows. -The first version exposes the existing Hush wireless-debugging setup and Shizuku authorization from a D-pad screen; device-specific pairing and TV restart behavior require real-device checks. DNS remains off by default and is available only in advanced upstream settings. CI builds the companion; rebuilding the proprietary Spotify splits still requires the user's original four APKs and private key, neither available here. +The EQ has ten visual curve points (31 Hz–16 kHz), log-frequency interpolation onto real output bands, ±6 dB range and 0–6 dB post-gain. Preserve five-band settings via migration. Provide remote, touch and accessibility adjustment. + +Rebuild the exact prior personal release, replace only extension classes/assets, add the embedded provider and merge the inspected splits into one unsigned APK. Retain versionCode 2340200 for the base client. The retained private signing key is unavailable; do not claim an installable same-key update or device verification without it. diff --git a/hush/build.ps1 b/hush/build.ps1 deleted file mode 100644 index 495a301..0000000 --- a/hush/build.ps1 +++ /dev/null @@ -1,49 +0,0 @@ -param( - [Parameter(Mandatory)][string]$AndroidSdk, - [Parameter(Mandatory)][string]$JavaHome, - [Parameter(Mandatory)][string]$KeyStore, - [Parameter(Mandatory)][string]$OutputApk, - [string]$KeyAlias = 'androiddebugkey' -) -$ErrorActionPreference = 'Stop' -if (-not $env:SPTV_STORE_PASSWORD) { throw 'Set SPTV_STORE_PASSWORD for the same private key used by Spotify+ TV.' } -if (Test-Path -LiteralPath $OutputApk) { throw 'OutputApk must be new.' } -$sdk = (Resolve-Path -LiteralPath $AndroidSdk).Path -$jdk = (Resolve-Path -LiteralPath $JavaHome).Path -$key = (Resolve-Path -LiteralPath $KeyStore).Path -$tools = Join-Path $sdk 'build-tools/35.0.0' -$project = Join-Path $PSScriptRoot 'build/android' -function Check-Exit([string]$Stage) { if ($LASTEXITCODE -ne 0) { throw "$Stage failed ($LASTEXITCODE)" } } -$oldJava = $env:JAVA_HOME -$oldSdk = $env:ANDROID_HOME -$oldSigning = $env:HUSH_SIGNING -try { - $env:JAVA_HOME = $jdk - $env:ANDROID_HOME = $sdk - # Keep upstream signing config out of this build; sign explicitly using the TV key below. - $env:HUSH_SIGNING = Join-Path $PSScriptRoot 'build/no-upstream-signing.properties' - if (Test-Path -LiteralPath $env:HUSH_SIGNING) { throw 'Unexpected upstream signing properties file; remove it first.' } - git -C $PSScriptRoot submodule update --init --recursive -- upstream - Check-Exit 'Pinned Hush checkout' - # This is a generated build directory only, never the pinned source or signing material. - if (Test-Path -LiteralPath $project) { Remove-Item -LiteralPath $project -Recurse -Force } - python (Join-Path $PSScriptRoot 'prepare.py') --output $project - Check-Exit 'TV adaptation' - & (Join-Path $project 'gradlew.bat') -p $project testDebugUnitTest assembleRelease - Check-Exit 'Hush tests and Android build' - $unsigned = Join-Path $project 'app/build/outputs/apk/release/app-release-unsigned.apk' - $aligned = Join-Path $PSScriptRoot 'build/Hush-TV-aligned.apk' - & (Join-Path $tools 'zipalign.exe') -P 16 -f 4 $unsigned $aligned - Check-Exit 'Hush alignment' - $signArgs = @('sign','--ks',$key,'--ks-key-alias',$KeyAlias,'--ks-pass','env:SPTV_STORE_PASSWORD','--out',$OutputApk) - if ($env:SPTV_KEY_PASSWORD) { $signArgs += @('--key-pass','env:SPTV_KEY_PASSWORD') } - $signArgs += $aligned - & (Join-Path $tools 'apksigner.bat') @signArgs - Check-Exit 'Hush signing' - & (Join-Path $tools 'apksigner.bat') verify --min-sdk-version 26 $OutputApk - Check-Exit 'Hush signature verification' -} finally { - $env:JAVA_HOME = $oldJava - $env:ANDROID_HOME = $oldSdk - $env:HUSH_SIGNING = $oldSigning -} diff --git a/hush/overlay/java/io/coldmew/hush/TvActivity.java b/hush/overlay/java/io/coldmew/hush/TvActivity.java deleted file mode 100644 index 0c2fa08..0000000 --- a/hush/overlay/java/io/coldmew/hush/TvActivity.java +++ /dev/null @@ -1,94 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-only -package io.coldmew.hush; - -import android.Manifest; -import android.app.Activity; -import android.app.AlertDialog; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.os.Looper; -import android.widget.Button; -import android.widget.LinearLayout; -import android.widget.ScrollView; -import android.widget.TextView; -import android.widget.Toast; - -/** A D-pad-first entry point. The upstream setup screens remain available for pairing. */ -public class TvActivity extends Activity { - private final Handler ui = new Handler(Looper.getMainLooper()); - private TextView status; - private Button power; - private final Runnable refresh = new Runnable() { - @Override public void run() { - Prefs p = new Prefs(TvActivity.this); - power.setText(p.enabled() ? "Hush skipping: on · select to turn off" : "Hush skipping: off · select to turn on"); - boolean signed = getPackageManager().checkSignatures(getPackageName(), Hush.SPOTIFY) == PackageManager.SIGNATURE_MATCH; - status.setText(!signed ? "Install Spotify+ TV and this companion signed with the same key." - : !Shell.ready() ? "Helper is not ready. Ads can still be muted by Spotify+ TV. Set up the helper below." - : !TvBridge.hasSession() ? "Helper ready. Open Spotify+ TV and start playback to connect its session." - : p.enabled() ? "Hush is enabled. TV restart skipping needs device verification." - : "Connected. Turn on Hush to attempt restart skipping during ads."); - ui.postDelayed(this, 1000); - } - }; - - @Override protected void onCreate(Bundle state) { - super.onCreate(state); - ScrollView scroll = new ScrollView(this); - LinearLayout body = new LinearLayout(this); - body.setOrientation(LinearLayout.VERTICAL); - body.setPadding(64, 32, 64, 32); - scroll.setBackgroundColor(0xff10191f); - scroll.addView(body); - TextView title = new TextView(this); - title.setText("Hush · Spotify+ TV"); title.setTextColor(0xff91e7cf); title.setTextSize(28); - body.addView(title); - status = new TextView(this); status.setTextColor(0xffeeeeee); status.setTextSize(18); - status.setPadding(0, 20, 0, 20); body.addView(status); - power = add(body, "Hush skipping", () -> { - Prefs p = new Prefs(this); p.mode(Prefs.MODE_RESTART); - Hush.setEnabled(this, !p.enabled()); TvBridge.recheck(); - if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) - requestPermissions(new String[]{Manifest.permission.POST_NOTIFICATIONS}, 1); - }); - add(body, "Set up Hush helper · Android 11+", () -> open(new Intent(this, HelperSetupActivity.class))); - add(body, "Authorize running Shizuku · Android 8+", () -> { - if (Shell.running()) Shell.requestPermission(); - else open(new Intent(this, ShizukuSetupActivity.class)); - }); - add(body, "Test Spotify restart", () -> { - if (!new Prefs(this).enabled() || !Shell.ready() || !TvBridge.hasSession() || !TvBridge.mayResume(this)) { - Toast.makeText(this, "Enable Hush, start its helper and play Spotify first. Check the sleep timer too.", Toast.LENGTH_LONG).show(); - return; - } - new AlertDialog.Builder(this).setTitle("Restart Spotify now?") - .setMessage("This interrupts current playback to test recovery. Queue behavior must be checked on your TV.") - .setPositiveButton("Test restart", (d, w) -> Skipper.start(this, true)) - .setNegativeButton("Cancel", null).show(); - }); - add(body, "Return to Spotify+ TV", () -> { - Intent launch = getPackageManager().getLeanbackLaunchIntentForPackage(Hush.SPOTIFY); - if (launch == null) launch = getPackageManager().getLaunchIntentForPackage(Hush.SPOTIFY); - if (launch != null) open(launch); else Toast.makeText(this, "Spotify TV is not installed", Toast.LENGTH_LONG).show(); - }); - TextView notes = new TextView(this); - notes.setText("Keep ‘Mute detected ads’ on in Spotify+ TV for the fallback. Hush needs Wireless debugging or Shizuku after a reboot. DNS filtering is off by default.\n\nAdapted from coldMEW/Hush 2.0.2 · GPL-3.0. Source and changes: github.com/AlphadogRSA/spotifyplus-tv-patch/tree/feat/hush-tv/hush"); - notes.setTextColor(0xffb9c7d0); notes.setTextSize(15); notes.setPadding(0, 24, 0, 12); body.addView(notes); - setContentView(scroll); power.requestFocus(); - } - - private Button add(LinearLayout parent, String label, Runnable action) { - Button button = new Button(this); button.setText(label); button.setAllCaps(false); - button.setOnClickListener(v -> action.run()); parent.addView(button); - return button; - } - private void open(Intent intent) { - try { startActivity(intent); } - catch (RuntimeException e) { Toast.makeText(this, "This setup screen is unavailable on your TV", Toast.LENGTH_LONG).show(); } - } - @Override protected void onResume() { super.onResume(); ui.post(refresh); } - @Override protected void onPause() { ui.removeCallbacks(refresh); super.onPause(); } -} diff --git a/hush/overlay/java/io/coldmew/hush/TvBridge.java b/hush/overlay/java/io/coldmew/hush/TvBridge.java deleted file mode 100644 index ced3287..0000000 --- a/hush/overlay/java/io/coldmew/hush/TvBridge.java +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-only -package io.coldmew.hush; - -import android.content.Context; -import android.media.MediaMetadata; -import android.media.session.MediaController; -import android.media.session.MediaSession; -import android.media.session.PlaybackState; -import android.os.Handler; -import android.os.Looper; -import android.os.SystemClock; -import java.util.Collections; -import java.util.List; - -/** Native TV tokens are capabilities for one Spotify session; no notification access is needed. */ -final class TvBridge { - private static final Handler UI = new Handler(Looper.getMainLooper()); - private static final TvSkipPolicy POLICY = new TvSkipPolicy(); - private static volatile MediaController current; - private static MediaController.Callback callback; - private static volatile boolean nativeAd; - private static long stamp; - private static Context app; - - private TvBridge() {} - - static void accept(Context c, MediaSession.Token token, boolean ad, long sentAt, long sleepAt) { - if (sentAt <= 0 || sentAt < stamp || sentAt > SystemClock.elapsedRealtime() - || SystemClock.elapsedRealtime() - sentAt > 15000) return; - MediaController candidate = new MediaController(c, token); - if (!Hush.SPOTIFY.equals(candidate.getPackageName())) return; - stamp = sentAt; - app = c.getApplicationContext(); - app.getSharedPreferences("tv_bridge", 0).edit().putLong("sleep_at", sleepAt).apply(); - nativeAd = ad; - if (current == null || !current.getSessionToken().equals(token)) { - if (current != null && callback != null) current.unregisterCallback(callback); - current = candidate; - callback = new MediaController.Callback() { - @Override public void onPlaybackStateChanged(PlaybackState s) { recheck(); } - @Override public void onMetadataChanged(MediaMetadata m) { recheck(); } - @Override public void onSessionDestroyed() { - if (current != candidate) return; - candidate.unregisterCallback(this); - current = null; - nativeAd = false; - } - }; - candidate.registerCallback(callback, UI); - } - recheck(); - } - - static void acceptController(Context c, MediaController controller) { - // The native bridge is authoritative for TV. An optional notification listener may - // refresh metadata, but must never replace a newer native session or mute the device. - if (current != null && current.getSessionToken().equals(controller.getSessionToken())) recheck(); - } - - static boolean isNativeAd(MediaController mc) { - MediaController active = current; - return nativeAd && active != null && active.getSessionToken().equals(mc.getSessionToken()); - } - - static List sessions(Context c) { - MediaController active = current; - return active == null ? Collections.emptyList() : Collections.singletonList(active); - } - - static boolean mayResume(Context c) { - long end = c.getSharedPreferences("tv_bridge", 0).getLong("sleep_at", 0); - return new Prefs(c).enabled() && (end <= 0 || System.currentTimeMillis() < end); - } - - static boolean hasSession() { return current != null; } - - static void recheck() { - if (Looper.myLooper() != Looper.getMainLooper()) { UI.post(TvBridge::recheck); return; } - Context c = app; - MediaController mc = current; - if (c == null || mc == null) return; - Prefs p = new Prefs(c); - if (!p.enabled() || !Prefs.MODE_RESTART.equals(p.mode())) return; - PlaybackState ps = mc.getPlaybackState(); - boolean active = ps != null && (ps.getState() == PlaybackState.STATE_PLAYING - || ps.getState() == PlaybackState.STATE_BUFFERING || ps.getState() == PlaybackState.STATE_CONNECTING); - MediaMetadata m = mc.getMetadata(); - boolean ad = AdWatcher.isAd(mc); - if (!ad && m != null && !Skipper.busy()) { - AdWatcher.lastTrack = m.getString(MediaMetadata.METADATA_KEY_MEDIA_ID); - AdWatcher.lastContext = m.getString(AdWatcher.KEY_CONTEXT); - } - long now = System.currentTimeMillis(); - long end = c.getSharedPreferences("tv_bridge", 0).getLong("sleep_at", 0); - boolean ready = Shell.ready() && (Skipper.lastFailAt <= 0 || now - Skipper.lastFailAt >= 120000); - if (POLICY.shouldSkip(ad, active, ready, Skipper.busy(), now, end)) Skipper.start(c, false); - } -} diff --git a/hush/overlay/java/io/coldmew/hush/TvReceiver.java b/hush/overlay/java/io/coldmew/hush/TvReceiver.java deleted file mode 100644 index 5a8dcb4..0000000 --- a/hush/overlay/java/io/coldmew/hush/TvReceiver.java +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-only -package io.coldmew.hush; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.media.session.MediaSession; - -/** Manifest signature permission protects this endpoint; the peer must also share our signer. */ -public class TvReceiver extends BroadcastReceiver { - public static final String ACTION = "dev.aurora.hushtv.TV_STATE"; - @Override public void onReceive(Context c, Intent i) { - if (!ACTION.equals(i.getAction())) return; - if (c.getPackageManager().checkSignatures(c.getPackageName(), Hush.SPOTIFY) - != PackageManager.SIGNATURE_MATCH) return; - try { - MediaSession.Token token = i.getParcelableExtra("session"); - if (token != null) TvBridge.accept(c, token, i.getBooleanExtra("ad", false), - i.getLongExtra("stamp", 0), i.getLongExtra("sleep_at", 0)); - } catch (RuntimeException ignored) { /* Invalid parcel or dead session: keep local muting. */ } - } -} diff --git a/hush/overlay/java/io/coldmew/hush/TvService.java b/hush/overlay/java/io/coldmew/hush/TvService.java deleted file mode 100644 index 41c96b2..0000000 --- a/hush/overlay/java/io/coldmew/hush/TvService.java +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-only -package io.coldmew.hush; - -import android.app.Service; -import android.content.Context; -import android.content.Intent; -import android.os.Handler; -import android.os.IBinder; -import android.os.Looper; - -/** Keeps restart/recovery alive after the broadcast returns and Spotify has been stopped. */ -public class TvService extends Service { - private final Handler ui = new Handler(Looper.getMainLooper()); - private final Runnable tick = new Runnable() { - @Override public void run() { - if (!new Prefs(TvService.this).enabled()) { stopSelf(); return; } - TvBridge.recheck(); - ui.postDelayed(this, 2000); - } - }; - static void enabled(Context c, boolean on) { - Intent intent = new Intent(c, TvService.class); - if (on) c.startForegroundService(intent); else c.stopService(intent); - } - @Override public int onStartCommand(Intent intent, int flags, int startId) { - if (!new Prefs(this).enabled()) { stopSelf(); return START_NOT_STICKY; } - startForeground(Hush.NOTIF_STATUS, Hush.statusNotification(this)); - ui.removeCallbacks(tick); ui.post(tick); - return START_STICKY; - } - @Override public IBinder onBind(Intent intent) { return null; } - @Override public void onDestroy() { ui.removeCallbacks(tick); super.onDestroy(); } -} diff --git a/hush/overlay/java/io/coldmew/hush/TvSkipPolicy.java b/hush/overlay/java/io/coldmew/hush/TvSkipPolicy.java deleted file mode 100644 index 0fdd363..0000000 --- a/hush/overlay/java/io/coldmew/hush/TvSkipPolicy.java +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-only -package io.coldmew.hush; - -/** One restart attempt per ad break. A running restart cannot clear the latch. */ -public final class TvSkipPolicy { - private boolean attempted; - - public synchronized boolean shouldSkip(boolean ad, boolean active, boolean ready, - boolean busy, long now, long sleepAt) { - if (busy) return false; - if (!ad && active) attempted = false; - if (!ad || !active || !ready || attempted || (sleepAt > 0 && now >= sleepAt)) return false; - attempted = true; - return true; - } -} diff --git a/hush/prepare.py b/hush/prepare.py index 8e0429e..d570624 100644 --- a/hush/prepare.py +++ b/hush/prepare.py @@ -1,147 +1,34 @@ #!/usr/bin/env python3 -"""Prepare an auditable TV adaptation from the exact upstream gitlink; never edit the submodule.""" +"""Extract the pinned Hush helper sources for embedding in Spotify's single APK.""" from pathlib import Path import argparse import shutil import subprocess -import xml.etree.ElementTree as ET - -ROOT = Path(__file__).resolve().parent -PIN = '4e9ded397338de5c69b1784c636feb3d34a8de01' -ANDROID = 'http://schemas.android.com/apk/res/android' -ET.register_namespace('android', ANDROID) -ET.register_namespace('tools', 'http://schemas.android.com/tools') - -def replace(path, old, new): - text = path.read_text(encoding='utf-8') - if text.count(old) != 1: - raise ValueError(f'Upstream changed: expected one replacement in {path.name}: {old[:60]}') - path.write_text(text.replace(old, new), encoding='utf-8') - +ROOT=Path(__file__).resolve().parent +PIN='4e9ded397338de5c69b1784c636feb3d34a8de01' +FILES=('Actions','Commands','Exec','Helper','HelperProtocol','HelperProvider','HushHelper','Providers') def prepare(destination): - upstream = ROOT / 'upstream' - actual = subprocess.check_output(['git', '-C', str(upstream), 'rev-parse', 'HEAD'], text=True).strip() - if actual != PIN: - raise ValueError(f'Expected Hush {PIN}, got {actual}') - subprocess.run(['git', '-C', str(upstream), 'diff', '--exit-code', 'HEAD', '--'], check=True, stdout=subprocess.DEVNULL) - # Untracked files are excluded too: copy only paths recorded in the pinned source tree. - if destination.exists(): - raise ValueError('Destination must be new; refusing to overwrite an existing project') - paths = subprocess.check_output(['git', '-C', str(upstream), 'ls-files', '-z', 'android'], text=True).split('\0') - for name in filter(None, paths): - relative = Path(name).relative_to('android') - target = destination / relative - target.parent.mkdir(parents=True, exist_ok=True) - shutil.copyfile(upstream / name, target) - - source = destination / 'app/src/main/java/io/coldmew/hush' - for path in (destination / 'app/src').rglob('*'): - if path.suffix not in ('.java', '.xml'): - continue - text = path.read_text(encoding='utf-8') - text = text.replace('com.spotify.music', 'com.spotify.tv.android') - # This metadata key belongs to Spotify's protocol, not its install package. - text = text.replace('com.spotify.tv.android.extra.CONTEXT_URI', 'com.spotify.music.extra.CONTEXT_URI') - text = text.replace('com.spotify.tv.android/.MainActivity', 'com.spotify.tv.android/.SpotifyTVActivity') - path.write_text(text, encoding='utf-8') - - gradle = destination / 'app/build.gradle.kts' - replace(gradle, 'applicationId = "io.coldmew.hush"', 'applicationId = "dev.aurora.hushtv"') - replace(gradle, 'versionName = "2.0.2"', 'versionName = "2.0.2-tv.1"') - # Keep one stable package for the signature-protected Spotify protocol in every variant. - replace(gradle, 'applicationIdSuffix = ".debug"', '// Stable companion package for debug builds.') - - watcher = source / 'AdWatcher.java' - replace(watcher, 'static boolean isAd(MediaController c) { return isAd(c.getMetadata()); }', - 'static boolean isAd(MediaController c) { return TvBridge.isNativeAd(c) || isAd(c.getMetadata()); }') - replace(watcher, 'AdWatcher w = instance;\n if (w != null && w.spotify != null) w.check(w.spotify);', - 'TvBridge.recheck();') - text = watcher.read_text(encoding='utf-8') - start = text.index(' private void checkLocked(MediaController c) {') - watcher.write_text(text[:start] + ' private void checkLocked(MediaController c) {\n' - ' TvBridge.acceptController(this, c);\n }\n}\n', encoding='utf-8') - - skipper = source / 'Skipper.java' - replace(skipper, 'return c.getSystemService(MediaSessionManager.class).getActiveSessions(new ComponentName(c, AdWatcher.class));', - 'return TvBridge.sessions(c);') - replace(skipper, 'Hush.SPOTIFY + "/.MainActivity"', 'Hush.SPOTIFY + "/.SpotifyTVActivity"') - replace(skipper, 'Intent i = c.getPackageManager().getLaunchIntentForPackage(Hush.SPOTIFY);', - 'Intent i = c.getPackageManager().getLeanbackLaunchIntentForPackage(Hush.SPOTIFY);\n' - ' if (i == null) i = c.getPackageManager().getLaunchIntentForPackage(Hush.SPOTIFY);') - replace(skipper, ''' switch (n % 3) { - case 0: Shell.run(Commands.MEDIA_PLAY); break; - case 1: mc.getTransportControls().play(); break; - default: Shell.run(Commands.KEY_PLAY); break; - }''', ' mc.getTransportControls().play(); // Only the forwarded Spotify TV session.') - replace(skipper, 'MediaController mc = latest(c, old);\n PlaybackState ps = mc == null ? null : mc.getPlaybackState();', - 'MediaController mc = latest(c, old);\n' - ' if (!TvBridge.mayResume(c)) {\n' - ' if (mc != null) mc.getTransportControls().pause();\n' - ' return Result.NOT_PLAYING;\n' - ' }\n' - ' PlaybackState ps = mc == null ? null : mc.getPlaybackState();') - # Repair must not send global media keys that could control another TV app. - replace(skipper, 'Shell.run(Commands.REPAIR_MUTE);', - 'Shell.run(Commands.ALLOW_AUDIO);\n' - ' if (mc != null) mc.getTransportControls().play();') - - # Hush's optional advanced timer can also use the native session without notification access. - timer = source / 'SleepTimer.java' - text = timer.read_text(encoding='utf-8') - text = text.replace('c.getSystemService(MediaSessionManager.class)\n .getActiveSessions(new ComponentName(c, AdWatcher.class))', 'TvBridge.sessions(c)') - text = text.replace(''' AudioManager am = c.getSystemService(AudioManager.class); - am.dispatchMediaKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PAUSE)); - am.dispatchMediaKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PAUSE));''', - ' // No global media keys: another TV app may now be playing.') - timer.write_text(text, encoding='utf-8') - - hush = source / 'Hush.java' - replace(hush, 'p.enabled(on);', 'p.enabled(on);\n TvService.enabled(c, on);') - replace(hush, 'if (p.enabled()) { applyDns(c); refreshNotification(c); }', - 'if (p.enabled()) { applyDns(c); refreshNotification(c); TvService.enabled(c, true); }') - - for path in (ROOT / 'overlay/java').rglob('*.java'): - target = destination / 'app/src/main/java' / path.relative_to(ROOT / 'overlay/java') - target.parent.mkdir(parents=True, exist_ok=True) - shutil.copyfile(path, target) - - manifest_path = destination / 'app/src/main/AndroidManifest.xml' - tree = ET.parse(manifest_path) - manifest = tree.getroot() - key = lambda name: '{' + ANDROID + '}' + name - permission = 'dev.aurora.hushtv.permission.TV_BRIDGE' - manifest.insert(0, ET.Element('permission', {key('name'): permission, key('protectionLevel'): 'signature'})) - manifest.insert(1, ET.Element('uses-permission', {key('name'): permission})) - manifest.insert(2, ET.Element('uses-feature', {key('name'): 'android.hardware.touchscreen', key('required'): 'false'})) - manifest.insert(3, ET.Element('uses-feature', {key('name'): 'android.software.leanback', key('required'): 'false'})) - app = manifest.find('application') - app.set(key('label'), 'Hush · Spotify+ TV') - app.set(key('banner'), '@drawable/tv_banner') - activity = ET.SubElement(app, 'activity', {key('name'): '.TvActivity', key('exported'): 'true'}) - intent = ET.SubElement(activity, 'intent-filter') - ET.SubElement(intent, 'action', {key('name'): 'android.intent.action.MAIN'}) - ET.SubElement(intent, 'category', {key('name'): 'android.intent.category.LEANBACK_LAUNCHER'}) - ET.SubElement(app, 'receiver', {key('name'): '.TvReceiver', key('exported'): 'true', key('permission'): permission}) - service = ET.SubElement(app, 'service', {key('name'): '.TvService', key('exported'): 'false', key('foregroundServiceType'): 'specialUse'}) - ET.SubElement(service, 'property', {key('name'): 'android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE', - key('value'): 'User-enabled Spotify TV ad detection and restart recovery'}) - tree.write(manifest_path, encoding='utf-8', xml_declaration=True) - assets = destination / 'app/src/main/assets' - assets.mkdir(parents=True, exist_ok=True) - shutil.copyfile(upstream / 'LICENSE', assets / 'HUSH-COPYING.txt') - (assets / 'HUSH-SOURCE.txt').write_text('Hush 2.0.2 by coldMEW, GPL-3.0\n' - f'Upstream https://github.com/coldMEW/Hush commit {PIN}\n' - 'TV changes and reproducible source: https://github.com/AlphadogRSA/spotifyplus-tv-patch\n', encoding='utf-8') - drawable = destination / 'app/src/main/res/drawable' - drawable.mkdir(exist_ok=True) - (drawable / 'tv_banner.xml').write_text(''' - - - ''', encoding='utf-8') - return destination - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--output', type=Path, default=ROOT / 'build/android') - print(prepare(parser.parse_args().output)) + upstream=ROOT/'upstream' + if subprocess.check_output(['git','-C',str(upstream),'rev-parse','HEAD'],text=True).strip()!=PIN: + raise ValueError('Hush gitlink differs from the pinned source') + subprocess.run(['git','-C',str(upstream),'diff','--exit-code','HEAD','--'],check=True,stdout=subprocess.DEVNULL) + if destination.exists():raise ValueError('Destination must be new') + target=destination/'dev/aurora/tvpatch/hush';target.mkdir(parents=True) + for name in FILES: + text=(upstream/f'android/app/src/main/java/io/coldmew/hush/helper/{name}.java').read_text() + text=text.replace('io.coldmew.hush.helper','dev.aurora.tvpatch.hush') + text=text.replace('com.spotify.music','com.spotify.tv.android') + if name=='HelperProtocol': + text=text.replace('VERSION = 3','VERSION = 4').replace('".helper"','".sptv_hush_helper"') + if name=='Commands': + start=text.index(' switch (action) {');end=text.index('\n private static String open(',start) + text=text[:start]+''' if (action != RESTART || !"com.spotify.tv.android/.SpotifyTVActivity".equals(a)) + throw new IllegalArgumentException("Only the fixed Spotify TV restart action is supported"); + return STOP + "; " + ALLOWLIST + "; " + open(a) + "; " + ALLOW; + } +''' +text[end:] + (target/f'{name}.java').write_text('// Adapted from coldMEW/Hush 2.0.2. SPDX-License-Identifier: GPL-3.0-only\n'+text) + return destination +if __name__=='__main__': + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--output',type=Path,default=ROOT/'build/generated') + print(prepare(parser.parse_args().output)) diff --git a/hush/tests/TvSkipPolicyTest.java b/hush/tests/TvSkipPolicyTest.java deleted file mode 100644 index 3dfcde3..0000000 --- a/hush/tests/TvSkipPolicyTest.java +++ /dev/null @@ -1,18 +0,0 @@ -import io.coldmew.hush.TvSkipPolicy; - -public class TvSkipPolicyTest { - static void check(boolean value) { if (!value) throw new AssertionError(); } - public static void main(String[] args) { - TvSkipPolicy p = new TvSkipPolicy(); - check(!p.shouldSkip(true, false, true, false, 1000, 0)); // paused ad - check(!p.shouldSkip(true, true, false, false, 1000, 0)); // helper missing - check(p.shouldSkip(true, true, true, false, 1000, 0)); - check(!p.shouldSkip(true, true, true, false, 1001, 0)); // repeated flag - check(!p.shouldSkip(false, true, true, true, 1002, 0)); // transient music while restarting - check(!p.shouldSkip(true, true, true, false, 1003, 0)); - check(!p.shouldSkip(false, true, true, false, 2000, 0)); // actual music resets latch - check(!p.shouldSkip(true, true, true, false, 2001, 2000)); // timer expired - check(p.shouldSkip(true, true, true, false, 2002, 10000)); - System.out.println("TvSkipPolicyTest passed"); - } -} diff --git a/hush/tests/test_prepare.py b/hush/tests/test_prepare.py index 608df52..1411710 100644 --- a/hush/tests/test_prepare.py +++ b/hush/tests/test_prepare.py @@ -1,35 +1,16 @@ import importlib.util +from pathlib import Path import tempfile import unittest -from pathlib import Path -import xml.etree.ElementTree as ET - -ROOT = Path(__file__).resolve().parents[1] - -class PreparationTest(unittest.TestCase): - def test_tv_project_is_separate_and_bridge_is_signature_protected(self): - self.assertTrue((ROOT / 'prepare.py').exists(), 'TV preparation feature is missing') - spec = importlib.util.spec_from_file_location('prepare', ROOT / 'prepare.py') - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - with tempfile.TemporaryDirectory() as directory: - out = Path(directory) / 'android' - module.prepare(out) - manifest = ET.parse(out / 'app/src/main/AndroidManifest.xml').getroot() - android = '{http://schemas.android.com/apk/res/android}' - self.assertEqual(manifest.find('permission').get(android + 'protectionLevel'), 'signature') - receiver = next(x for x in manifest.findall('application/receiver') if x.get(android + 'name') == '.TvReceiver') - self.assertEqual(receiver.get(android + 'permission'), 'dev.aurora.hushtv.permission.TV_BRIDGE') - self.assertTrue(any(x.get(android+'name') == 'android.intent.category.LEANBACK_LAUNCHER' for x in manifest.findall('.//category'))) - self.assertIn('applicationId = "dev.aurora.hushtv"', (out / 'app/build.gradle.kts').read_text()) - source = out / 'app/src/main/java/io/coldmew/hush' - self.assertIn('com.spotify.tv.android', (source / 'Hush.java').read_text()) - self.assertIn('TvBridge.sessions(c)', (source / 'Skipper.java').read_text()) - self.assertNotIn('am.adjustStreamVolume', (source / 'AdWatcher.java').read_text()) - self.assertTrue((out / 'app/src/main/assets/HUSH-COPYING.txt').exists()) - service = next(x for x in manifest.findall('application/service') if x.get(android+'name') == '.TvService') - self.assertEqual(service.get(android+'exported'), 'false') - self.assertEqual(service.get(android+'foregroundServiceType'), 'specialUse') - -if __name__ == '__main__': - unittest.main() +ROOT=Path(__file__).resolve().parents[1] +class HelperTest(unittest.TestCase): + def test_single_apk_helper_sources(self): + spec=importlib.util.spec_from_file_location('prepare',ROOT/'prepare.py'); m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) + with tempfile.TemporaryDirectory() as d: + m.prepare(Path(d)/'generated') + helper=Path(d)/'generated/dev/aurora/tvpatch/hush' + self.assertTrue((helper/'Helper.java').exists()) + commands=(helper/'Commands.java').read_text() + self.assertIn('Only the fixed Spotify TV restart action is supported',commands) + self.assertIn('com.spotify.tv.android',commands) + self.assertFalse(list((Path(d)/'generated').rglob('AndroidManifest.xml'))) diff --git a/install.ps1 b/install.ps1 index ce2a423..648f798 100644 --- a/install.ps1 +++ b/install.ps1 @@ -1,19 +1,12 @@ param( [Parameter(Mandatory)][string]$ApkDirectory, [Parameter(Mandatory)][string]$Serial, - [string]$Adb = 'adb', - [switch]$WithoutHush + [string]$Adb = 'adb' ) $ErrorActionPreference = 'Stop' $apks = @('base.apk','split_config.armeabi_v7a.apk','split_config.en.apk','split_config.tvdpi.apk') | ForEach-Object { (Resolve-Path -LiteralPath (Join-Path $ApkDirectory $_)).Path } -# Install the permission-defining companion first. An existing matching signing key is required. -if (-not $WithoutHush) { - $hush = (Resolve-Path -LiteralPath (Join-Path $ApkDirectory 'Hush-TV.apk')).Path - & $Adb -s $Serial install -r $hush - if ($LASTEXITCODE -ne 0) { throw 'Hush installation failed; no uninstall or app data reset was attempted.' } -} & $Adb -s $Serial install-multiple -r @apks if ($LASTEXITCODE -ne 0) { throw 'Installation failed; no uninstall or app data reset was attempted.' } # Development diagnostic permission: identifies only this process’s positive audio session IDs. @@ -23,3 +16,6 @@ if ($LASTEXITCODE -ne 0) { throw 'Installed, but audio-session discovery setup f & $Adb -s $Serial shell am force-stop com.spotify.tv.android & $Adb -s $Serial shell am start -W -n com.spotify.tv.android/.SpotifyTVActivity if ($LASTEXITCODE -ne 0) { throw 'Installed, but launch failed.' } + +# The helper is embedded in Spotify's APK and runs as the authorized ADB shell user. +& (Join-Path $PSScriptRoot 'start-hush.ps1') -Serial $Serial -Adb $Adb diff --git a/rebuild_release.py b/rebuild_release.py new file mode 100644 index 0000000..7ab0da3 --- /dev/null +++ b/rebuild_release.py @@ -0,0 +1,80 @@ +"""Rebuild the exact previous personal TV release as one unsigned 1.3.0.1 APK. + +Requires compiled extension DEX and the checksum-pinned APK tooling. No signing keys are read. +""" +import argparse +import hashlib +from pathlib import Path +import re +import shutil +import subprocess +import xml.etree.ElementTree as ET +import zipfile + +ROOT=Path(__file__).resolve().parent +INPUT_SHA='fd14f65b1a282621c2f4873d3323370046527dbf2c22384ba14514203ea7d17d' +TOOL_SHA={ + 'apktool':'dbf930b076c6b9be08d57c449cacefc3bdd6b71ebd59b3066fc0e1f5b14f9423', + 'apkeditor':'a9cd40df818845456be6d696de6110c89edf4b0a0580cb83438ed6b25a366e67', +} +VERSION='1.3.0.1' +def verified(path,sha): + if hashlib.sha256(path.read_bytes()).hexdigest()!=sha:raise ValueError(f'Checksum mismatch: {path.name}') +def run(*args):subprocess.run(list(map(str,args)),check=True) +def rebuild(source,dex,apktool,apkeditor,output): + verified(source,INPUT_SHA);verified(apktool,TOOL_SHA['apktool']);verified(apkeditor,TOOL_SHA['apkeditor']) + if output.exists():raise ValueError('Output directory must be new') + if not dex.is_file():raise ValueError('Compiled extension DEX is required') + output.mkdir(parents=True);parts=output/'splits';parts.mkdir() + names=['base.apk','split_config.armeabi_v7a.apk','split_config.en.apk','split_config.tvdpi.apk'] + with zipfile.ZipFile(source) as archive: + for name in names:(parts/name).write_bytes(archive.read(name)) + decoded=output/'decoded' + run('java','-jar',apktool,'d',parts/'base.apk','-o',decoded) + removed=0 + for smali in decoded.glob('smali*'): + old=smali/'dev/aurora/tvpatch' + if old.exists():shutil.rmtree(old);removed+=1 + if not removed:raise ValueError('Expected the previous TV extension; refusing to patch an unknown client') + manifest=decoded/'AndroidManifest.xml';tree=ET.parse(manifest);root=tree.getroot() + ns='http://schemas.android.com/apk/res/android';ET.register_namespace('android',ns) + attr=lambda k:'{'+ns+'}'+k + app=root.find('application') + if root.get('package')!='com.spotify.tv.android':raise ValueError('Unexpected Android package') + if any('sptv_hush_helper' in x.get(attr('authorities'),'') for x in app.findall('provider')): + raise ValueError('This input already includes the integrated helper') + ET.SubElement(app,'provider',{attr('name'):'dev.aurora.tvpatch.hush.HelperProvider', + attr('authorities'):'com.spotify.tv.android.sptv_hush_helper',attr('exported'):'true', + attr('permission'):'android.permission.INTERACT_ACROSS_USERS_FULL'}) + tree.write(manifest,encoding='utf-8',xml_declaration=True) + metadata=decoded/'apktool.yml';text=metadata.read_text() + text,count=re.subn(r'(?m)^ versionName: 1\.134\.2$',f' versionName: {VERSION}',text) + if count!=1:raise ValueError('Unexpected source version') + metadata.write_text(text) + for path in (ROOT/'assets').iterdir(): + if path.is_file():shutil.copyfile(path,decoded/'assets'/path.name) + unsigned_base=output/'rebuilt-base.apk' + run('java','-jar',apktool,'b',decoded,'-o',unsigned_base) + # Hook calls in the original app remain; the previous runtime definitions were removed above. + # Append exactly one new DEX without copying any stale compiled extension classes. + with zipfile.ZipFile(unsigned_base) as archive: + files=[(info,archive.read(info.filename)) for info in archive.infolist()] + used=set(archive.namelist()) + number=2 + while f'classes{number}.dex' in used:number+=1 + with zipfile.ZipFile(parts/'base.apk','w') as archive: + for info,data in files: + if not info.filename.upper().startswith('META-INF/'): + archive.writestr(info,data) + archive.writestr(f'classes{number}.dex',dex.read_bytes(),compress_type=zipfile.ZIP_DEFLATED) + final=output/f'SpotifyPlus-TV-{VERSION}-unsigned.apk' + run('java','-jar',apkeditor,'m','-i',parts,'-o',final,'-validate-modules') + (output/'SHA256.txt').write_text(hashlib.sha256(final.read_bytes()).hexdigest()+' '+final.name+'\n') + print(f'Unsigned single-app APK: {final}') + return final +if __name__=='__main__': + p=argparse.ArgumentParser(description=__doc__) + p.add_argument('--input',type=Path,required=True);p.add_argument('--dex',type=Path,required=True) + p.add_argument('--apktool',type=Path,required=True);p.add_argument('--apkeditor',type=Path,required=True) + p.add_argument('--output',type=Path,required=True) + a=p.parse_args();rebuild(a.input,a.dex,a.apktool,a.apkeditor,a.output) diff --git a/revanced/build.gradle.kts b/revanced/build.gradle.kts index 55465d5..df3e345 100644 --- a/revanced/build.gradle.kts +++ b/revanced/build.gradle.kts @@ -1,7 +1,7 @@ plugins { kotlin("jvm") version "2.3.10" } group = "dev.aurora.tvpatch" -version = "0.6.0" +version = "1.3.0.1" kotlin { jvmToolchain(17) // The pinned official Patcher is built with experimental context/backing-field metadata. @@ -28,7 +28,7 @@ tasks.processResources { } val bundle by tasks.registering(Jar::class) { dependsOn(tasks.classes) - archiveFileName.set("spotifyplus-tv-0.6.rvp") + archiveFileName.set("spotifyplus-tv-1.3.0.1.rvp") from(sourceSets.main.get().output) doFirst { require(extensionDex.isPresent && file(extensionDex.get()).isFile) { "Pass -PextensionDex=/absolute/path/to/classes.dex from the compiled MIT runtime extension" } } manifest { attributes("Main-Class" to "dev.aurora.patches.RunnerKt") } diff --git a/revanced/src/main/kotlin/dev/aurora/patches/TvPatches.kt b/revanced/src/main/kotlin/dev/aurora/patches/TvPatches.kt index 85276ae..5c93a23 100644 --- a/revanced/src/main/kotlin/dev/aurora/patches/TvPatches.kt +++ b/revanced/src/main/kotlin/dev/aurora/patches/TvPatches.kt @@ -22,6 +22,13 @@ val tvManifestPatch = resourcePatch(name = "TV app label and local lyric import" val app = doc.getElementsByTagName("application").item(0) as Element val android = "http://schemas.android.com/apk/res/android" app.setAttributeNS(android, "android:label", "Spotify+ TV") + doc.documentElement.setAttributeNS(android, "android:versionName", "1.3.0.1") + val provider = doc.createElement("provider") + provider.setAttributeNS(android, "android:name", "dev.aurora.tvpatch.hush.HelperProvider") + provider.setAttributeNS(android, "android:authorities", "com.spotify.tv.android.sptv_hush_helper") + provider.setAttributeNS(android, "android:exported", "true") + provider.setAttributeNS(android, "android:permission", "android.permission.INTERACT_ACROSS_USERS_FULL") + app.appendChild(provider) app.setAttributeNS(android, "android:debuggable", "true") val activities = doc.getElementsByTagName("activity") for (i in 0 until activities.length) { @@ -29,7 +36,7 @@ val tvManifestPatch = resourcePatch(name = "TV app label and local lyric import" if (node.getAttributeNS(android, "name") == "com.spotify.tv.android.SpotifyTVActivity") node.setAttributeNS(android, "android:label", "Spotify+ TV") } - for (permission in listOf("android.permission.MODIFY_AUDIO_SETTINGS", "android.permission.DUMP", "dev.aurora.hushtv.permission.TV_BRIDGE")) { + for (permission in listOf("android.permission.MODIFY_AUDIO_SETTINGS", "android.permission.DUMP")) { if ((0 until doc.getElementsByTagName("uses-permission").length).none { (doc.getElementsByTagName("uses-permission").item(it) as Element).getAttributeNS(android, "name") == permission }) { @@ -38,15 +45,6 @@ val tvManifestPatch = resourcePatch(name = "TV app label and local lyric import" doc.documentElement.insertBefore(element, app) } } - val queries = (doc.getElementsByTagName("queries").item(0) as? Element) - ?: doc.createElement("queries").also { doc.documentElement.insertBefore(it, app) } - if ((0 until queries.getElementsByTagName("package").length).none { - (queries.getElementsByTagName("package").item(it) as Element).getAttributeNS(android, "name") == "dev.aurora.hushtv" - }) { - queries.appendChild(doc.createElement("package").also { - it.setAttributeNS(android, "android:name", "dev.aurora.hushtv") - }) - } } } } @@ -54,7 +52,7 @@ val tvManifestPatch = resourcePatch(name = "TV app label and local lyric import" val tvAssetsPatch = rawResourcePatch(name = "TV theme assets and notices", use = false) { compatibleWith(PACKAGE(VERSION)) apply { - for (name in listOf("spotifyplus-tv.js", "TV-PATCH-LICENSE.txt", "SPOTIFYPLUS-LICENSE.txt", "INSPIRATION.md", "HUSH-NOTICE.txt")) { + for (name in listOf("spotifyplus-tv.js", "TV-PATCH-LICENSE.txt", "SPOTIFYPLUS-LICENSE.txt", "INSPIRATION.md", "spotifyplus-settings.js", "HUSH-NOTICE.txt", "HUSH-COPYING.txt")) { val target = get("assets/$name", false) target.parentFile.mkdirs() requireNotNull(object {}.javaClass.classLoader.getResourceAsStream(name)) { "Missing bundled asset $name" }.use { input -> diff --git a/sign-apk.ps1 b/sign-apk.ps1 new file mode 100644 index 0000000..15187fa --- /dev/null +++ b/sign-apk.ps1 @@ -0,0 +1,25 @@ +param( + [Parameter(Mandatory)][string]$UnsignedApk, + [Parameter(Mandatory)][string]$AndroidSdk, + [Parameter(Mandatory)][string]$KeyStore, + [Parameter(Mandatory)][string]$OutputApk, + [string]$KeyAlias = 'androiddebugkey' +) +$ErrorActionPreference = 'Stop' +if (-not $env:SPTV_STORE_PASSWORD) { throw 'Set SPTV_STORE_PASSWORD for your retained TV signing key.' } +if (Test-Path -LiteralPath $OutputApk) { throw 'OutputApk must be new.' } +$inputApk = (Resolve-Path -LiteralPath $UnsignedApk).Path +$key = (Resolve-Path -LiteralPath $KeyStore).Path +$tools = Join-Path (Resolve-Path -LiteralPath $AndroidSdk).Path 'build-tools/35.0.0' +$aligned = [IO.Path]::Combine([IO.Path]::GetTempPath(), [IO.Path]::GetRandomFileName() + '.apk') +try { + & (Join-Path $tools 'zipalign.exe') -P 16 -f 4 $inputApk $aligned + if ($LASTEXITCODE -ne 0) { throw 'APK alignment failed.' } + $signArgs = @('sign','--ks',$key,'--ks-key-alias',$KeyAlias,'--ks-pass','env:SPTV_STORE_PASSWORD','--out',$OutputApk) + if ($env:SPTV_KEY_PASSWORD) { $signArgs += @('--key-pass','env:SPTV_KEY_PASSWORD') } + $signArgs += $aligned + & (Join-Path $tools 'apksigner.bat') @args + if ($LASTEXITCODE -ne 0) { throw 'APK signing failed.' } + & (Join-Path $tools 'apksigner.bat') verify --min-sdk-version 26 $OutputApk + if ($LASTEXITCODE -ne 0) { throw 'APK signature verification failed.' } +} finally { Remove-Item -LiteralPath $aligned -ErrorAction SilentlyContinue } diff --git a/src/dev/aurora/tvpatch/AudioDsp.java b/src/dev/aurora/tvpatch/AudioDsp.java index 3295214..8a77014 100644 --- a/src/dev/aurora/tvpatch/AudioDsp.java +++ b/src/dev/aurora/tvpatch/AudioDsp.java @@ -103,11 +103,11 @@ private static Set ownSessions() throws Exception { private static final class Settings { final boolean enabled; final int boost; - final int[] gains = new int[5]; + final int[] gains; Settings(SharedPreferences prefs) { enabled = prefs.getBoolean("dspEnabled", false); boost = Math.max(0, Math.min(600, prefs.getInt("boostMb", 0))); - for (int i = 0; i < gains.length; i++) gains[i] = Math.max(-6, Math.min(6, prefs.getInt("eq" + i, 0))); + gains = GraphicEqSettings.read(prefs); } } private static final class Effects implements AudioEffectPlan.Target { @@ -129,7 +129,7 @@ private static final class Effects implements AudioEffectPlan.Target { } void apply(int[] gains, int boost) { if (controlChanged.getAndSet(false)) plan.invalidate(); - plan.apply(gains, boost, this); + plan.applyGraphic(gains, boost, this); } public void band(short band, short level) { eq.setBandLevel(band, level); } public void equalizerEnabled(boolean enabled) { eq.setEnabled(enabled); } diff --git a/src/dev/aurora/tvpatch/AudioEffectPlan.java b/src/dev/aurora/tvpatch/AudioEffectPlan.java index 9a92fec..0eb9316 100644 --- a/src/dev/aurora/tvpatch/AudioEffectPlan.java +++ b/src/dev/aurora/tvpatch/AudioEffectPlan.java @@ -13,12 +13,14 @@ public interface Target { private static final int[] FREQUENCIES = {60, 230, 910, 3600, 14000}; private final short min, max; private final int[] targets; + private final int[] centers; private short[] appliedLevels; private int[] appliedGains; private int appliedBoost; public AudioEffectPlan(short min, short max, int[] centerMilliHz) { if (min > max || centerMilliHz.length == 0) throw new IllegalArgumentException("Invalid EQ layout"); this.min = min; this.max = max; targets = new int[centerMilliHz.length]; + centers = centerMilliHz.clone(); for (int band = 0; band < centerMilliHz.length; band++) { double hz = Math.max(1, centerMilliHz[band] / 1000.0), best = Double.MAX_VALUE; for (int i = 0; i < FREQUENCIES.length; i++) { @@ -29,10 +31,20 @@ public AudioEffectPlan(short min, short max, int[] centerMilliHz) { } public void apply(int[] gainsDb, int boostMb, Target target) { if (gainsDb.length != FREQUENCIES.length) throw new IllegalArgumentException("Five controls required"); + applySettings(gainsDb, boostMb, target, false); + } + public void applyGraphic(int[] gainsMb, int boostMb, Target target) { + if (gainsMb.length != GraphicEq.BANDS) throw new IllegalArgumentException("Ten EQ curve points required"); + applySettings(gainsMb, boostMb, target, true); + } + private void applySettings(int[] gains, int boostMb, Target target, boolean graphic) { boostMb = Math.max(0, Math.min(600, boostMb)); - if (appliedLevels != null && Arrays.equals(gainsDb, appliedGains) && boostMb == appliedBoost) return; + if (appliedLevels != null && Arrays.equals(gains, appliedGains) && boostMb == appliedBoost) return; short[] levels = new short[targets.length]; - for (int band = 0; band < targets.length; band++) levels[band] = (short)Math.max(min, Math.min(max, gainsDb[targets[band]] * 100)); + for (int band = 0; band < targets.length; band++) { + int value = graphic ? GraphicEq.levelAt(gains, Math.max(1, centers[band] / 1000.0)) : gains[targets[band]] * 100; + levels[band] = (short)Math.max(min, Math.min(max, value)); + } boolean initial = appliedLevels == null; try { for (short band = 0; band < targets.length; band++) if (initial || levels[band] != appliedLevels[band]) target.band(band, levels[band]); @@ -40,7 +52,7 @@ public void apply(int[] gainsDb, int boostMb, Target target) { if (initial || boostMb != appliedBoost) target.boost(boostMb); if (initial || (boostMb > 0) != (appliedBoost > 0)) target.boostEnabled(boostMb > 0); } catch (RuntimeException failure) { invalidate(); throw failure; } - appliedLevels = levels; appliedGains = gainsDb.clone(); appliedBoost = boostMb; + appliedLevels = levels; appliedGains = gains.clone(); appliedBoost = boostMb; } public void invalidate() { appliedLevels = null; appliedGains = null; } } diff --git a/src/dev/aurora/tvpatch/GraphicEq.java b/src/dev/aurora/tvpatch/GraphicEq.java new file mode 100644 index 0000000..9ed9541 --- /dev/null +++ b/src/dev/aurora/tvpatch/GraphicEq.java @@ -0,0 +1,31 @@ +package dev.aurora.tvpatch; + +/** A ten-point target curve in millibels; sampled logarithmically at real hardware bands. */ +public final class GraphicEq { + public static final int BANDS = 10, LIMIT = 600, STEP = 50; + private static final int[] HZ = {31, 62, 125, 250, 500, 1000, 2000, 4000, 8000, 16000}; + private static final int[] LEGACY_HZ = {60, 230, 910, 3600, 14000}; + private GraphicEq() {} + public static int frequency(int index) { return HZ[index]; } + public static int adjust(int value, int direction) { return clamp(value + direction * STEP); } + public static int clamp(int value) { return Math.max(-LIMIT, Math.min(LIMIT, value)); } + public static int levelAt(int[] gains, double hz) { + if (gains.length != BANDS) throw new IllegalArgumentException("Ten EQ curve points required"); + return interpolate(HZ, gains, hz); + } + public static int[] fromLegacy(int[] gainsDb) { + if (gainsDb.length != LEGACY_HZ.length) throw new IllegalArgumentException("Five legacy controls required"); + int[] mb = new int[gainsDb.length], result = new int[BANDS]; + for (int i = 0; i < mb.length; i++) mb[i] = clamp(gainsDb[i] * 100); + for (int i = 0; i < result.length; i++) result[i] = interpolate(LEGACY_HZ, mb, HZ[i]); + return result; + } + private static int interpolate(int[] hz, int[] gains, double value) { + if (value <= hz[0]) return clamp(gains[0]); + for (int i = 1; i < hz.length; i++) if (value < hz[i]) { + double t = Math.log(value / hz[i-1]) / Math.log((double)hz[i] / hz[i-1]); + return clamp((int)Math.round(gains[i-1] * (1-t) + gains[i] * t)); + } + return clamp(gains[gains.length-1]); + } +} diff --git a/src/dev/aurora/tvpatch/GraphicEqSettings.java b/src/dev/aurora/tvpatch/GraphicEqSettings.java new file mode 100644 index 0000000..97f4ffa --- /dev/null +++ b/src/dev/aurora/tvpatch/GraphicEqSettings.java @@ -0,0 +1,20 @@ +package dev.aurora.tvpatch; + +import android.content.SharedPreferences; + +/** Persist the new curve once, leaving previous five-band values available for older builds. */ +public final class GraphicEqSettings { + private GraphicEqSettings() {} + public static int[] read(SharedPreferences prefs) { + int[] values = new int[GraphicEq.BANDS]; + if (!prefs.getBoolean("graphicEqMigrated", false)) { + int[] old = new int[5]; + for (int i = 0; i < old.length; i++) old[i] = prefs.getInt("eq" + i, 0); + values = GraphicEq.fromLegacy(old); + SharedPreferences.Editor edit = prefs.edit().putBoolean("graphicEqMigrated", true); + for (int i = 0; i < values.length; i++) edit.putInt("graphicEq" + i, values[i]); + edit.apply(); + } else for (int i = 0; i < values.length; i++) values[i] = GraphicEq.clamp(prefs.getInt("graphicEq" + i, 0)); + return values; + } +} diff --git a/src/dev/aurora/tvpatch/GraphicEqView.java b/src/dev/aurora/tvpatch/GraphicEqView.java new file mode 100644 index 0000000..60a5aa9 --- /dev/null +++ b/src/dev/aurora/tvpatch/GraphicEqView.java @@ -0,0 +1,165 @@ +package dev.aurora.tvpatch; + +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.DashPathEffect; +import android.graphics.LinearGradient; +import android.graphics.Paint; +import android.graphics.Path; +import android.graphics.RectF; +import android.graphics.Shader; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.View; +import android.view.accessibility.AccessibilityNodeInfo; +import java.util.Locale; + +/** Native graphic control: TV remote, touch, and accessibility all change the same stored curve. */ +public final class GraphicEqView extends View { + private static final int BLUE = 0xff659efa, MUTED = 0xffaebac4; + private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final SharedPreferences prefs; + private final float density; + private int[] gains; + private int selected; + private boolean enabled; + private float left, right, top, bottom, gainY; + + public GraphicEqView(Context c, SharedPreferences prefs) { + super(c); this.prefs = prefs; density = getResources().getDisplayMetrics().density; + gains = GraphicEqSettings.read(prefs); enabled = prefs.getBoolean("dspEnabled", false); + setFocusable(true); setFocusableInTouchMode(true); setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); + describe(); + } + private float dp(float value) { return value * density; } + public void enabled(boolean value) { enabled = value; invalidate(); describe(); } + public void reset() { + gains = new int[GraphicEq.BANDS]; + SharedPreferences.Editor edit = prefs.edit().putInt("boostMb", 0).putBoolean("graphicEqMigrated", true); + for (int i = 0; i < gains.length; i++) edit.putInt("graphicEq" + i, 0); + for (int i = 0; i < 5; i++) edit.putInt("eq" + i, 0); + edit.apply(); AudioDsp.refresh(); invalidate(); describe(); + } + private float x(int band) { return left + (right-left) * band / (GraphicEq.BANDS-1); } + private float y(int gain) { return top + (bottom-top) * (GraphicEq.LIMIT-gain) / (GraphicEq.LIMIT*2f); } + private void color(int color, float stroke) { + paint.setShader(null); paint.setPathEffect(null); paint.setStyle(Paint.Style.FILL); + paint.setColor(color); paint.setStrokeWidth(dp(stroke)); + } + private void label(Canvas c, String text, float x, float y, int color, float size, Paint.Align align) { + color(color, 1); paint.setTextSize(dp(size)); paint.setTextAlign(align); c.drawText(text, x, y, paint); + } + @Override protected void onDraw(Canvas c) { + super.onDraw(c); + float w = getWidth(), h = getHeight(); + left = dp(54); right = w-dp(32); top = dp(42); bottom = Math.max(top+dp(70), h-dp(115)); gainY = h-dp(29); + color(0xff252f36, 1); c.drawRoundRect(new RectF(0,0,w,h), dp(24), dp(24), paint); + for (int value = -600; value <= 600; value += 300) { + color(0xff3a4650, 1); paint.setPathEffect(new DashPathEffect(new float[]{dp(4),dp(5)},0)); + c.drawLine(left, y(value), right, y(value), paint); + label(c, Integer.toString(value/100), left-dp(15), y(value)+dp(4), MUTED, 12, Paint.Align.RIGHT); + } + for (int i = 0; i < gains.length; i++) { + color(0xff4b5660, 4); paint.setStrokeCap(Paint.Cap.ROUND); c.drawLine(x(i), top, x(i), bottom, paint); + } + Path curve = new Path(); curve.moveTo(left, y(gains[0])); + for (int i=1;i=1000?(hz/1000)+"K":Integer.toString(hz),x(i),bottom+dp(25),MUTED,13,Paint.Align.CENTER); + } + label(c,"Post-gain",left,bottom+dp(65),Color.WHITE,16,Paint.Align.LEFT); + int boost=Math.max(0,Math.min(600,prefs.getInt("boostMb",0))); + label(c,String.format(Locale.ROOT,"+%.1f dB",boost/100f),right,bottom+dp(65),MUTED,14,Paint.Align.RIGHT); + color(0xff4b5660,4); c.drawLine(left,gainY,right,gainY,paint); + float thumb=left+(right-left)*boost/600f; + color(enabled?BLUE:0xff778591,4); c.drawLine(left,gainY,thumb,gainY,paint); c.drawCircle(thumb,gainY,dp(9),paint); + if (hasFocus() && selected==GraphicEq.BANDS) { + color(Color.WHITE,2); paint.setStyle(Paint.Style.STROKE); c.drawCircle(thumb,gainY,dp(14),paint); + } + } + private void adjust(int direction) { + if (selected==GraphicEq.BANDS) { + int value=Math.max(0,Math.min(600,prefs.getInt("boostMb",0)+direction*50)); + prefs.edit().putInt("boostMb",value).apply(); + } else { + gains[selected]=GraphicEq.adjust(gains[selected],direction); + prefs.edit().putInt("graphicEq"+selected,gains[selected]).apply(); + } + AudioDsp.refresh(); invalidate(); describe(); + } + @Override public boolean onKeyDown(int key, KeyEvent event) { + if (key==KeyEvent.KEYCODE_DPAD_LEFT || key==KeyEvent.KEYCODE_DPAD_RIGHT) { + selected=Math.max(0,Math.min(GraphicEq.BANDS,selected+(key==KeyEvent.KEYCODE_DPAD_RIGHT?1:-1))); + invalidate(); describe(); return true; + } + if (key==KeyEvent.KEYCODE_DPAD_UP || key==KeyEvent.KEYCODE_DPAD_DOWN) { + adjust(key==KeyEvent.KEYCODE_DPAD_UP?1:-1); return true; + } + if (key==KeyEvent.KEYCODE_DPAD_CENTER || key==KeyEvent.KEYCODE_ENTER) { + if (selected==GraphicEq.BANDS) { + View toolbar=focusSearch(View.FOCUS_UP); + if (toolbar!=null && toolbar!=this) toolbar.requestFocus(); + } else selected=GraphicEq.BANDS; + invalidate(); describe(); return true; + } + return super.onKeyDown(key,event); + } + @Override public boolean onKeyUp(int key, KeyEvent event) { + if (key==KeyEvent.KEYCODE_DPAD_LEFT || key==KeyEvent.KEYCODE_DPAD_RIGHT || key==KeyEvent.KEYCODE_DPAD_UP + || key==KeyEvent.KEYCODE_DPAD_DOWN || key==KeyEvent.KEYCODE_DPAD_CENTER || key==KeyEvent.KEYCODE_ENTER) return true; + return super.onKeyUp(key,event); + } + @Override public boolean onTouchEvent(MotionEvent event) { + if (right<=left) return true; + int action=event.getActionMasked(); + if (action==MotionEvent.ACTION_DOWN || action==MotionEvent.ACTION_MOVE) { + requestFocus(); + if (event.getY()>bottom+dp(35)) { + selected=GraphicEq.BANDS; + int value=Math.round((event.getX()-left)/(right-left)*12)*50; + prefs.edit().putInt("boostMb",Math.max(0,Math.min(600,value))).apply(); + } else { + selected=Math.max(0,Math.min(GraphicEq.BANDS-1,Math.round((event.getX()-left)/(right-left)*(GraphicEq.BANDS-1)))); + gains[selected]=GraphicEq.clamp(Math.round((1-(event.getY()-top)/(bottom-top))*24-12)*50); + prefs.edit().putInt("graphicEq"+selected,gains[selected]).apply(); + } + AudioDsp.refresh(); invalidate(); describe(); return true; + } + if(action==MotionEvent.ACTION_UP) { performClick(); return true; } + return action==MotionEvent.ACTION_CANCEL || super.onTouchEvent(event); + } + @Override public boolean performClick() { super.performClick(); return true; } + private void describe() { + String selectedText=selected==GraphicEq.BANDS?"Post-gain "+prefs.getInt("boostMb",0)/100f+" dB" + :GraphicEq.frequency(selected)+" hertz "+gains[selected]/100f+" dB"; + setContentDescription(selectedText+". Left and right select. Up and down adjust. OK switches to post-gain, then toolbar. EQ "+(enabled?"on":"off")); + } + @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { + super.onInitializeAccessibilityNodeInfo(info); info.setClassName("android.widget.SeekBar"); + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD); + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD); + } + @Override public boolean performAccessibilityAction(int action, android.os.Bundle args) { + if(action==AccessibilityNodeInfo.ACTION_SCROLL_FORWARD || action==AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD) { + adjust(action==AccessibilityNodeInfo.ACTION_SCROLL_FORWARD?1:-1); return true; + } + return super.performAccessibilityAction(action,args); + } +} diff --git a/src/dev/aurora/tvpatch/Hooks.java b/src/dev/aurora/tvpatch/Hooks.java index e78e0b8..a3e4ea1 100644 --- a/src/dev/aurora/tvpatch/Hooks.java +++ b/src/dev/aurora/tvpatch/Hooks.java @@ -85,7 +85,7 @@ public final class Hooks { Activity owner = activity.get(); if (owner != null) { prefs(owner).edit().remove("sleepAt").apply(); - HushClient.signal(owner, token, detectedAd, sleepAt, true); + } toast("Sleep timer finished"); } @@ -93,7 +93,8 @@ public final class Hooks { applyAdVolume(); Activity current = activity.get(); if (current != null) { - HushClient.signal(current, token, detectedAd, sleepAt, false); + HushIntegration.tick(current, controller, detectedAd, sleepAt); + WebView page = web.get(); if (page != null) NativeSettings.refresh(page, false); PlaybackState playback = cachedPlayback; AudioDsp.tick(current, playback != null && playback.getState() == PlaybackState.STATE_PLAYING); } @@ -132,10 +133,11 @@ public static void attach(Activity a) { web = new WeakReference<>(view); if (token != null) connectController(a.getApplicationContext()); if (!started) { started = true; UI.post(ticker); } + HushIntegration.prepare(a); if (view != null) apply(view); Log.i("SPTV", "Activity extension attached"); if (!prefs(a).getBoolean("welcomed", false)) { - toast("Spotify+ TV: press Menu or hold OK for settings"); + toast("Spotify+ TV controls are in Spotify Settings"); prefs(a).edit().putBoolean("welcomed", true).apply(); } } catch (Exception ignored) { } @@ -177,7 +179,7 @@ private static void connectController(Context context) { }; next.registerCallback(controllerCallback, UI); cachedPlayback = next.getPlaybackState(); cachedMetadata = next.getMetadata(); - HushClient.signal(context, token, detectedAd, sleepAt, true); + HushIntegration.recover(context, next); } private static void clearLyricViews() { lyricTitle = null; lyricStatus = null; fetchButton = null; plainButton = null; @@ -208,7 +210,7 @@ public static void adState(boolean playing) { detectedAd = playing; AD_MUTE.ad(playing, SystemClock.elapsedRealtime()); applyAdVolume(); Activity a = activity.get(); - if (a != null) HushClient.signal(a, token, detectedAd, sleepAt, true); + if (a != null) HushIntegration.tick(a, controller, detectedAd, sleepAt); }); } /** Intercept TVBridge's native player volume; never Android's device volume. */ @@ -311,6 +313,8 @@ private static void apply(WebView view) { } if (script == null) script = read(view.getContext().getAssets().open("spotifyplus-tv.js")); SharedPreferences p = prefs(view.getContext()); + Activity owner = activity.get(); + if (owner != null) NativeSettings.attach(view, owner); JSONObject config = new JSONObject(); config.put("theme", p.getInt("theme", 1)); config.put("motion", p.getBoolean("motion", true)); @@ -320,7 +324,8 @@ private static void apply(WebView view) { view.evaluateJavascript("(" + script + ")(" + config.toString() + ")", result -> Log.i("SPTV", "Theme result: " + result)); } catch (Exception failure) { Log.w("SPTV", "Theme failed: " + failure.getClass().getSimpleName()); } } - private static void reapply() { WebView view = web.get(); if (view != null) apply(view); } + private static void reapply() { WebView view = web.get(); + if (view != null) apply(view); } private static TextView text(Activity a, String content, int size, int color) { TextView view = new TextView(a); @@ -361,111 +366,93 @@ private static AlertDialog show(Activity a, View content) { return dialog; } public static void showMenu(Activity a) { - if (a.isFinishing() || (menu != null && menu.isShowing())) return; - LinearLayout body = panel(a); - TextView heading = text(a, "Spotify+ TV", 24, accent(a)); add(body, heading); + WebView view = web.get(); + if (view != null) NativeSettings.open(view); + else toast("Open Spotify Settings to find your custom controls."); + } + public static JSONObject settingsSnapshot(Context context) throws Exception { + SharedPreferences p = prefs(context); + JSONObject values = new JSONObject(); + values.put("theme", p.getInt("theme", 1)); + values.put("blurArtwork", p.getBoolean("blurArtwork", true)); + values.put("motion", p.getBoolean("motion", true)); + values.put("hideUpgrade", p.getBoolean("hideUpgrade", true)); + values.put("muteAds", p.getBoolean("muteAds", true)); + values.put("hushEnabled", p.getBoolean("hushEnabled", false)); + values.put("hushStatus", HushIntegration.status()); + values.put("audioStatus", AudioDsp.status()); + values.put("sleep", sleepAt > 0 ? "Active · survives Spotify restarts" : "Off"); + values.put("version", "1.3.0.1"); + return values; + } + public static void settingsAction(Activity a, String action) { SharedPreferences p = prefs(a); - String[] names = {"Spotify original", "Aurora accent", "Midnight accent", "Ember accent"}; - Button theme = button(a, "Theme: " + names[p.getInt("theme", 1) % 4], () -> { }); - theme.setOnClickListener(v -> { - int value = (p.getInt("theme", 1) + 1) % 4; p.edit().putInt("theme", value).apply(); - theme.setText("Theme: " + names[value]); heading.setTextColor(accent(a)); - if (theme.hasFocus() && theme.getBackground() instanceof GradientDrawable) ((GradientDrawable)theme.getBackground()).setColor(accent(a)); - reapply(); - }); add(body, theme); - Button motion = button(a, "Animated background: " + (p.getBoolean("motion", true) ? "on" : "off"), () -> { }); - motion.setOnClickListener(v -> { - boolean value = !p.getBoolean("motion", true); p.edit().putBoolean("motion", value).apply(); - motion.setText("Animated background: " + (value ? "on" : "off")); reapply(); - }); add(body, motion); - Button blur = button(a, "Background artwork blur: " + (p.getBoolean("blurArtwork", true) ? "on" : "off"), () -> { }); - blur.setOnClickListener(v -> { - boolean value = !p.getBoolean("blurArtwork", true); p.edit().putBoolean("blurArtwork", value).apply(); - blur.setText("Background artwork blur: " + (value ? "on" : "off")); reapply(); - }); add(body, blur); - Button upgrade = button(a, "Hide promotions: " + (p.getBoolean("hideUpgrade", true) ? "on" : "off"), () -> { }); - upgrade.setOnClickListener(v -> { - boolean value = !p.getBoolean("hideUpgrade", true); p.edit().putBoolean("hideUpgrade", value).apply(); - upgrade.setText("Hide promotions: " + (value ? "on" : "off")); reapply(); - }); add(body, upgrade); - Button mute = button(a, "Mute detected ads: " + (p.getBoolean("muteAds", true) ? "on" : "off"), () -> { }); - mute.setOnClickListener(v -> { - boolean value = !p.getBoolean("muteAds", true); p.edit().putBoolean("muteAds", value).apply(); - AD_MUTE.enabled(value); applyAdVolume(); - mute.setText("Mute detected ads: " + (value ? "on" : "off")); - }); add(body, mute); - add(body, button(a, "Hush · ad-break skipping", () -> { - HushClient.signal(a, token, detectedAd, sleepAt, true); - HushClient.open(a); - })); - add(body, button(a, "Audio · Equalizer & Boost", () -> { menu.dismiss(); showAudio(a); })); - add(body, button(a, "Lyrics · local / LRCLIB", () -> { menu.dismiss(); showLyrics(a); })); - add(body, button(a, "Sleep timer" + (sleepAt > 0 ? " · active" : ""), () -> { - menu.dismiss(); trackDialog(new AlertDialog.Builder(a).setTitle("Pause this Spotify session after…") - .setItems(new String[]{"15 minutes", "30 minutes", "60 minutes", "Cancel timer"}, (dialog, which) -> { - sleepAt = which == 3 ? 0 : System.currentTimeMillis() + new long[]{900000,1800000,3600000}[which]; - int boot = android.provider.Settings.Global.getInt(a.getContentResolver(), android.provider.Settings.Global.BOOT_COUNT, -1); - p.edit().putLong("sleepAt", sleepAt).putInt("sleepBoot", boot).apply(); - HushClient.signal(a, token, detectedAd, sleepAt, true); - toast(which == 3 ? "Sleep timer cancelled" : "Sleep timer set. It survives Spotify restarts."); - }).create()).show(); - })); - add(body, button(a, "About", () -> trackDialog(new AlertDialog.Builder(a) - .setTitle("Spotify+ TV · 0.6") - .setMessage("Made for your TV remote.\n\nArtwork blur, accent colors, lyrics, sleep timer, ad muting, optional Hush companion support and audio controls.\n\nInspired by SpotifyPlus (MIT, © 2025 Devon Shoutz), Eevee's lyrics features and Spicetify's UI customization. Original Android TV implementation.\n\nOptional lyrics lookup sends track title, artist, album and duration to LRCLIB. Full source and license notices are included in the project and APK assets.") - .setPositiveButton("Close", null).create()).show())); - add(body, button(a, "Return to Spotify", () -> menu.dismiss())); - ScrollView scroll = new ScrollView(a); scroll.setBackgroundColor(Color.TRANSPARENT); scroll.addView(body); - menu = show(a, scroll); theme.requestFocus(); + if (action.equals("theme")) p.edit().putInt("theme", (p.getInt("theme", 1) + 1) % 4).apply(); + else if (action.equals("blur")) p.edit().putBoolean("blurArtwork", !p.getBoolean("blurArtwork", true)).apply(); + else if (action.equals("motion")) p.edit().putBoolean("motion", !p.getBoolean("motion", true)).apply(); + else if (action.equals("promotions")) p.edit().putBoolean("hideUpgrade", !p.getBoolean("hideUpgrade", true)).apply(); + else if (action.equals("mute")) { + boolean value = !p.getBoolean("muteAds", true); + p.edit().putBoolean("muteAds", value).apply(); AD_MUTE.enabled(value); applyAdVolume(); + } else if (action.equals("hush")) p.edit().putBoolean("hushEnabled", !p.getBoolean("hushEnabled", false)).apply(); + else if (action.equals("hushSetup")) HushIntegration.showSetup(a); + else if (action.equals("audio")) showAudio(a); + else if (action.equals("lyrics")) showLyrics(a); + else if (action.equals("sleep")) showSleep(a); + else if (action.equals("about")) trackDialog(new AlertDialog.Builder(a).setTitle("Spotify+ TV · 1.3.0.1") + .setMessage("Graphic EQ, lyrics, artwork themes and integrated Hush helper.\n\nHush helper adapted from coldMEW/Hush 2.0.2 (GPL-3.0). Spotify's account and streaming behavior remain its own. Full source and notices are included in the project.") + .setPositiveButton("Close", null).create()).show(); + else return; + reapply(); + } + private static void showSleep(Activity a) { + trackDialog(new AlertDialog.Builder(a).setTitle("Sleep timer") + .setItems(new String[]{"15 minutes", "30 minutes", "60 minutes", "Cancel timer"}, (dialog, which) -> { + sleepAt = which == 3 ? 0 : System.currentTimeMillis() + new long[]{900000,1800000,3600000}[which]; + int boot = android.provider.Settings.Global.getInt(a.getContentResolver(), android.provider.Settings.Global.BOOT_COUNT, -1); + prefs(a).edit().putLong("sleepAt", sleepAt).putInt("sleepBoot", boot).apply(); + WebView view = web.get(); if (view != null) NativeSettings.refresh(view, true); + toast(which == 3 ? "Sleep timer cancelled" : "Sleep timer set. It survives Spotify restarts."); + }).create()).show(); } private static void showAudio(Activity a) { SharedPreferences p = prefs(a); - LinearLayout body = panel(a); - add(body, text(a, "Audio", 26, accent(a))); - TextView status = text(a, AudioDsp.status(), 14, 0xffb3b3b3); add(body, status); - Button enabled = button(a, "EQ & Boost: " + (p.getBoolean("dspEnabled", false) ? "on" : "off"), () -> { }); + LinearLayout body = new LinearLayout(a); + body.setOrientation(LinearLayout.VERTICAL); + body.setPadding(24, 16, 24, 16); + body.setBackgroundColor(0xff0c1117); + LinearLayout toolbar = new LinearLayout(a); + toolbar.setGravity(android.view.Gravity.CENTER_VERTICAL); + TextView heading = text(a, "Equalizer · Graphic EQ", 23, Color.WHITE); + toolbar.addView(heading, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1)); + GraphicEqView chart = new GraphicEqView(a, p); + Button enabled = button(a, "", () -> { }); + Runnable label = () -> enabled.setText(p.getBoolean("dspEnabled", false) ? "EQ ● ON" : "EQ ○ OFF"); + label.run(); enabled.setOnClickListener(v -> { - boolean value = !p.getBoolean("dspEnabled", false); p.edit().putBoolean("dspEnabled", value).apply(); - enabled.setText("EQ & Boost: " + (value ? "on" : "off")); AudioDsp.refresh(); - }); add(body, enabled); - add(body, text(a, "Left / Right adjusts · OK increases", 13, 0xffb3b3b3)); - add(body, gainButton(a, p, "boostMb", "Volume boost", 0, 600, 100)); - String[] labels = {"60 Hz · Bass", "230 Hz · Low mids", "910 Hz · Mids", "3.6 kHz · Presence", "14 kHz · Treble"}; - for (int i = 0; i < 5; i++) add(body, gainButton(a, p, "eq" + i, labels[i], -6, 6, 1)); - add(body, button(a, "Flat / reset", () -> { - SharedPreferences.Editor edit = p.edit().putInt("boostMb", 0); - for (int i = 0; i < 5; i++) edit.putInt("eq" + i, 0); - edit.apply(); AudioDsp.refresh(); - for (int i = 0; i < body.getChildCount(); i++) { - View child = body.getChildAt(i); if (child.getTag() instanceof Runnable) ((Runnable)child.getTag()).run(); - } - })); - ScrollView scroll = new ScrollView(a); scroll.addView(body); - AlertDialog dialog = show(a, scroll); enabled.requestFocus(); + boolean value = !p.getBoolean("dspEnabled", false); + p.edit().putBoolean("dspEnabled", value).apply(); + label.run(); chart.enabled(value); AudioDsp.refresh(); + }); + toolbar.addView(enabled); + toolbar.addView(button(a, "Reset", chart::reset)); + final AlertDialog[] owner = new AlertDialog[1]; + toolbar.addView(button(a, "Close", () -> { if (owner[0] != null) owner[0].dismiss(); })); + add(body, toolbar); + TextView status = text(a, AudioDsp.status(), 13, 0xffaebac4); add(body, status); + body.addView(chart, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1)); + add(body, text(a, "← → Select band · ↑ ↓ Adjust · OK Post-gain / toolbar · Back Close", 12, 0xffaebac4)); + add(body, text(a, "10-point curve mapped to available output bands · ±6 dB EQ · 0–6 dB post-gain", 11, 0xff81919d)); + AlertDialog dialog = show(a, body); owner[0] = dialog; + dialog.getWindow().setLayout((int)(a.getResources().getDisplayMetrics().widthPixels * .92), + (int)(a.getResources().getDisplayMetrics().heightPixels * .90)); + chart.requestFocus(); Runnable updater = new Runnable() { public void run() { if (dialog.isShowing()) { setTextChanged(status, AudioDsp.status()); UI.postDelayed(this, 1000); } }}; dialogUpdates.put(dialog, updater); UI.post(updater); } - private static Button gainButton(Activity a, SharedPreferences p, String key, String label, int min, int max, int step) { - Button control = button(a, "", () -> { }); - Runnable update = () -> { - float db = p.getInt(key, 0) / (key.equals("boostMb") ? 100f : 1f); - control.setText(label + ": " + (db > 0 ? "+" : "") + String.format(java.util.Locale.ROOT, "%.0f dB", db)); - }; - java.util.function.IntConsumer adjust = direction -> { - int value = Math.max(min, Math.min(max, p.getInt(key, 0) + direction * step)); - p.edit().putInt(key, value).apply(); AudioDsp.refresh(); update.run(); - }; - control.setOnClickListener(v -> adjust.accept(1)); - control.setOnKeyListener((v, code, event) -> { - if (code != KeyEvent.KEYCODE_DPAD_LEFT && code != KeyEvent.KEYCODE_DPAD_RIGHT) return false; - if (event.getAction() == KeyEvent.ACTION_DOWN) adjust.accept(code == KeyEvent.KEYCODE_DPAD_LEFT ? -1 : 1); - return true; - }); - control.setTag(update); update.run(); return control; - } private static String lyricName(MediaMetadata metadata) { String id = metadata == null ? "" : metadata.getString(MediaMetadata.METADATA_KEY_MEDIA_ID); Matcher match = TRACK_ID.matcher(id == null ? "" : id); diff --git a/src/dev/aurora/tvpatch/HushClient.java b/src/dev/aurora/tvpatch/HushClient.java deleted file mode 100644 index 3778769..0000000 --- a/src/dev/aurora/tvpatch/HushClient.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.aurora.tvpatch; - -import android.app.Activity; -import android.app.AlertDialog; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.media.session.MediaSession; -import android.os.SystemClock; - -/** Independent protocol adapter; the GPL Hush implementation lives in a separate APK. */ -public final class HushClient { - private static final String PACKAGE = "dev.aurora.hushtv"; - private static final String PERMISSION = PACKAGE + ".permission.TV_BRIDGE"; - private static long lastSent; - private HushClient() {} - - private static boolean trusted(Context c) { - return c.getPackageManager().checkSignatures(c.getPackageName(), PACKAGE) == PackageManager.SIGNATURE_MATCH; - } - - public static void signal(Context c, MediaSession.Token token, boolean ad, long sleepAt, boolean force) { - if (token == null) return; - long now = SystemClock.elapsedRealtime(); - if (!force && now - lastSent < 10000) return; - lastSent = now; - if (!trusted(c)) return; - try { - c.sendBroadcast(new Intent(PACKAGE + ".TV_STATE") - .setComponent(new ComponentName(PACKAGE, "io.coldmew.hush.TvReceiver")) - .addFlags(Intent.FLAG_RECEIVER_FOREGROUND) - .putExtra("session", token).putExtra("ad", ad) - .putExtra("stamp", now).putExtra("sleep_at", sleepAt), PERMISSION); - } catch (RuntimeException ignored) { /* Existing per-player muting continues. */ } - } - - public static void open(Activity a) { - if (!trusted(a)) { - new AlertDialog.Builder(a).setTitle("Hush companion setup") - .setMessage("Install the Hush-TV.apk built with this Spotify+ TV release and the same signing key. Then set up Hush’s helper or authorize Shizuku.\n\nMute detected ads remains available while Hush is not ready.") - .setPositiveButton("OK", null).show(); - return; - } - try { a.startActivity(new Intent().setComponent(new ComponentName(PACKAGE, "io.coldmew.hush.TvActivity"))); } - catch (RuntimeException ignored) { - new AlertDialog.Builder(a).setMessage("Hush could not open. Reinstall the matching companion APK.").setPositiveButton("OK", null).show(); - } - } -} diff --git a/src/dev/aurora/tvpatch/HushIntegration.java b/src/dev/aurora/tvpatch/HushIntegration.java new file mode 100644 index 0000000..625f56a --- /dev/null +++ b/src/dev/aurora/tvpatch/HushIntegration.java @@ -0,0 +1,107 @@ +// Uses the separately attributed GPL Hush helper API embedded by hush/prepare.py. +package dev.aurora.tvpatch; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.SharedPreferences; +import android.media.session.MediaController; +import android.media.session.PlaybackState; +import android.os.Handler; +import android.os.Looper; +import dev.aurora.tvpatch.hush.Commands; +import dev.aurora.tvpatch.hush.HushHelper; +import java.io.File; +import java.io.FileOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.Executors; +import java.util.concurrent.ExecutorService; + +/** The shell-owned helper survives force-stop; the resumed Spotify process finishes recovery. */ +public final class HushIntegration { + private static final Handler UI = new Handler(Looper.getMainLooper()); + private static final ExecutorService WORK = Executors.newSingleThreadExecutor(); + private static SharedPreferences prefs(Context c) { return c.getSharedPreferences("spotifyplus_tv",0); } + private static volatile String message = "Helper setup required"; + private static boolean restarting; + private static int recovery; + private HushIntegration() {} + + public static String status() { return HushHelper.ready() ? "Helper ready · " + message : "Helper setup required · ad muting available"; } + public static void prepare(Context c) { + Context app=c.getApplicationContext(); + WORK.execute(() -> { + try { + File script=new File(app.getFilesDir(),"sptv-hush-start.sh"); + String apk=app.getApplicationInfo().sourceDir; + if (!script.exists() || !apk.equals(prefs(app).getString("hushApk", ""))) { + String command=HushHelper.startCommand(app); + try(FileOutputStream out=new FileOutputStream(script)) { out.write((command+"\n").getBytes(StandardCharsets.UTF_8)); } + prefs(app).edit().putString("hushApk",apk).commit(); + } + message="Waiting for an ad"; + } catch(Exception e) { message="Helper setup file unavailable"; } + }); + } + + public static void showSetup(Activity a) { + prepare(a); + new AlertDialog.Builder(a).setTitle("Hush · integrated in Spotify") + .setMessage(status()+"\n\nNo second app is installed. Enable Hush in Spotify Settings, then run the provided start-hush.ps1 over your authorized ADB connection. Run it again after a TV reboot or APK update.\n\nKeep Mute detected ads enabled as the fallback. TV restart skipping still needs device verification.") + .setPositiveButton("OK",null).show(); + } + + public static void tick(Context c, MediaController controller, boolean ad, long sleepAt) { + if(controller==null)return; + SharedPreferences p=prefs(c); + long now=System.currentTimeMillis(), pending=p.getLong("hushPending",0); + PlaybackState state=controller.getPlaybackState(); + boolean playing=state!=null && state.getState()==PlaybackState.STATE_PLAYING; + boolean active=playing || state!=null && (state.getState()==PlaybackState.STATE_BUFFERING || state.getState()==PlaybackState.STATE_CONNECTING); + if(pending>0) { + if(SleepDeadline.expired(p.getLong("hushPendingSleepAt",0),now)) { + controller.getTransportControls().pause();p.edit().remove("hushPending").apply();message="Sleep timer finished";return; + } + if(now-pending>2000 && playing && !ad) { + p.edit().remove("hushPending").apply(); message="Playback resumed"; + } else if(now-pending>20000) fail(p,now,"Recovery timed out · muting fallback"); + return; + } + if(restarting || !HushPolicy.attempt(p.getBoolean("hushEnabled",false),HushHelper.ready(),ad,active, + now,p.getLong("hushLastAttempt",0),p.getLong("hushLastFailure",0),pending,sleepAt))return; + restarting=true; + // Commit before asking the external helper to kill this process. + if(!p.edit().putLong("hushPending",now).putLong("hushLastAttempt",now).putLong("hushPendingSleepAt",sleepAt).commit()) { + restarting=false;message="Could not save recovery state";return; + } + message="Restarting Spotify"; + WORK.execute(() -> { + String result=HushHelper.run(Commands.RESTART,"com.spotify.tv.android/.SpotifyTVActivity"); + // Normally this caller has died. If it survives, do not leave a latched request forever. + if(result==null)UI.post(() -> { restarting=false;fail(p,System.currentTimeMillis(),"Helper unavailable · muting fallback"); }); + }); + } + private static void fail(SharedPreferences p,long now,String reason) { + p.edit().remove("hushPending").putLong("hushLastFailure",now).apply(); message=reason;restarting=false; + } + public static void recover(Context c,MediaController controller) { + SharedPreferences p=prefs(c); + long pending=p.getLong("hushPending",0); + if(pending<=0)return; + if(System.currentTimeMillis()-pending>20000) { fail(p,System.currentTimeMillis(),"Recovery expired · muting fallback");return; } + final int generation=++recovery; + UI.post(new Runnable() { public void run() { + if(generation!=recovery || p.getLong("hushPending",0)==0)return; + long now=System.currentTimeMillis(); + if(!p.getBoolean("hushEnabled",false) || SleepDeadline.expired(p.getLong("hushPendingSleepAt",0),now)) { + controller.getTransportControls().pause();p.edit().remove("hushPending").apply();message="Recovery stopped";return; + } + if(now-pending>20000) { fail(p,now,"Recovery timed out · muting fallback");return; } + try { + PlaybackState state=controller.getPlaybackState(); + if(state==null || state.getState()!=PlaybackState.STATE_PLAYING)controller.getTransportControls().play(); + UI.postDelayed(this,1000); + } catch (RuntimeException gone) { fail(p,now,"Spotify session ended · muting fallback"); } + }}); + } +} diff --git a/src/dev/aurora/tvpatch/HushPolicy.java b/src/dev/aurora/tvpatch/HushPolicy.java new file mode 100644 index 0000000..6c949b0 --- /dev/null +++ b/src/dev/aurora/tvpatch/HushPolicy.java @@ -0,0 +1,13 @@ +package dev.aurora.tvpatch; + +/** Persisted restart gate: no loops if a TV simply resumes the same ad after a cold start. */ +public final class HushPolicy { + private HushPolicy() {} + public static boolean attempt(boolean enabled, boolean ready, boolean ad, boolean active, + long now, long lastAttempt, long lastFailure, long pending, long sleepAt) { + return enabled && ready && ad && active && pending == 0 + && (lastAttempt <= 0 || now-lastAttempt >= 30000) + && (lastFailure <= 0 || now-lastFailure >= 120000) + && !SleepDeadline.expired(sleepAt, now); + } +} diff --git a/src/dev/aurora/tvpatch/NativeSettings.java b/src/dev/aurora/tvpatch/NativeSettings.java new file mode 100644 index 0000000..dcb2d86 --- /dev/null +++ b/src/dev/aurora/tvpatch/NativeSettings.java @@ -0,0 +1,57 @@ +package dev.aurora.tvpatch; + +import android.app.Activity; +import android.webkit.JavascriptInterface; +import android.webkit.WebView; +import org.json.JSONObject; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.lang.ref.WeakReference; + +/** Fixed settings actions only; the bridge never accepts code, shell commands or URLs. */ +public final class NativeSettings { + private static String script; + private static WeakReference attached=new WeakReference<>(null); + private static String signature=""; + private NativeSettings() {} + static boolean trusted(WebView view) { + String url=view.getUrl(); + if(url==null)return false; + if(url.startsWith("file:///android_asset/"))return true; + if(!url.startsWith("https://"))return false; + String host=android.net.Uri.parse(url).getHost(); + return host!=null && (host.equals("spotify.com")||host.endsWith(".spotify.com")||host.equals("tv.scdn.co")); + } + public static void attach(WebView view,Activity activity) { + if(!trusted(view))return; + if(attached.get()!=view) { + attached=new WeakReference<>(view);signature=""; + WeakReference owner=new WeakReference<>(activity); + view.addJavascriptInterface(new Object() { + @JavascriptInterface public void action(String action) { + if(action==null || action.length()>24)return; + Activity a=owner.get();if(a==null)return; + a.runOnUiThread(() -> { if(!a.isFinishing() && trusted(view))Hooks.settingsAction(a,action); }); + } + },"SpotifyPlusSettings"); + } + // addJavascriptInterface becomes visible on the next page load. page() also calls attach; + // attachment at Activity creation registers the bridge before the signed-in page loads. + refresh(view,true); + } + public static void refresh(WebView view,boolean force) { + if(!trusted(view))return; + try { + JSONObject values=Hooks.settingsSnapshot(view.getContext());String json=values.toString(); + if(!force && json.equals(signature))return;signature=json; + if(script==null)try(InputStream input=view.getContext().getAssets().open("spotifyplus-settings.js");ByteArrayOutputStream output=new ByteArrayOutputStream()) { + byte[] bytes=new byte[4096];int read;while((read=input.read(bytes))!=-1)output.write(bytes,0,read); + script=output.toString("UTF-8"); + } + view.evaluateJavascript("("+script+")("+json+")",null); + }catch(Exception ignored){} + } + public static void open(WebView view) { + if(trusted(view))view.evaluateJavascript("window.__sptvSettings ? window.__sptvSettings.open() : false",null); + } +} diff --git a/start-hush.ps1 b/start-hush.ps1 new file mode 100644 index 0000000..d0f9c0d --- /dev/null +++ b/start-hush.ps1 @@ -0,0 +1,21 @@ +param( + [Parameter(Mandatory)][string]$Serial, + [string]$Adb = 'adb' +) +$ErrorActionPreference = 'Stop' +# Spotify must have launched once to create its app-private, token-bound startup command. +$startup = $null +for ($attempt = 0; $attempt -lt 20; $attempt++) { + $content = & $Adb -s $Serial shell run-as com.spotify.tv.android cat files/sptv-hush-start.sh 2>$null + if ($LASTEXITCODE -eq 0 -and $content) { $startup = ($content -join "`n").Trim(); break } + Start-Sleep -Milliseconds 250 +} +if (-not $startup) { throw 'Hush startup file is not ready. Open Spotify once, then run start-hush.ps1 again.' } +# Never echo the private helper token. Only accept the generated, fixed app_process entrypoint. +if ($startup -notmatch '^CLASSPATH=/data/app/[^\s;]+ setsid /system/bin/app_process /system/bin --nice-name=hush_helper dev\.aurora\.tvpatch\.hush\.Helper --token=[a-f0-9]{32} --uid=\d+ --apk=/data/app/[^\s;]+ --authority=com\.spotify\.tv\.android\.sptv_hush_helper /dev/null 2>&1 & sleep 1$') { + throw 'Unexpected helper startup command; refusing to execute it.' +} +& $Adb -s $Serial shell $startup +if ($LASTEXITCODE -ne 0) { throw 'Hush helper startup failed. Local ad muting remains available.' } +$startup = $null +Write-Output 'Hush helper startup requested. Verify Helper ready in Spotify Settings before enabling restart skipping.' diff --git a/tests/GraphicEqTest.java b/tests/GraphicEqTest.java new file mode 100644 index 0000000..1aa9923 --- /dev/null +++ b/tests/GraphicEqTest.java @@ -0,0 +1,38 @@ +import dev.aurora.tvpatch.GraphicEq; +import dev.aurora.tvpatch.AudioEffectPlan; +import java.util.Arrays; + +public class GraphicEqTest { + private static class Hardware implements AudioEffectPlan.Target { + short[] levels = new short[3]; int writes; + public void band(short band, short gain) { levels[band] = gain; writes++; } + public void equalizerEnabled(boolean value) {} + public void boost(int gain) {} + public void boostEnabled(boolean value) {} + } + public static void main(String[] args) { + int[] gains = {0, 100, 200, 300, 400, 500, 600, 500, 400, 300}; + assert GraphicEq.levelAt(gains, 31) == 0; + assert GraphicEq.levelAt(gains, 62) == 100; + assert GraphicEq.levelAt(gains, Math.sqrt(62 * 125)) == 150; + assert GraphicEq.levelAt(gains, 1) == 0; + assert GraphicEq.levelAt(gains, 30000) == 300; + assert GraphicEq.adjust(590, 1) == 600; + assert GraphicEq.adjust(-590, -1) == -600; + assert GraphicEq.adjust(0, -1) == -50; + int[] flat = GraphicEq.fromLegacy(new int[]{3, 3, 3, 3, 3}); + for (int value : flat) assert value == 300; + int[] slope = GraphicEq.fromLegacy(new int[]{6, 3, 0, -3, -6}); + assert slope[0] == 600 && slope[9] == -600; + for (int i=1; i{ + const browser=await chromium.launch(process.env.SPTV_BROWSER ? {executablePath:process.env.SPTV_BROWSER} : {headless:true});const page=await browser.newPage({viewport:{width:1920,height:1080}}); + const source=fs.readFileSync('assets/spotifyplus-settings.js','utf8'); + const config={theme:1,blurArtwork:true,motion:true,hideUpgrade:true,muteAds:true,hushEnabled:false,hushStatus:'Helper ready',audioStatus:'Off',sleep:'Off',version:'1.3.0.1'}; + await page.setContent('
Home
'); + await page.evaluate(([source,config])=>{window.calls=[];window.SpotifyPlusSettings={action:a=>window.calls.push(a)};(new Function('return ('+source+')'))()(config)},[source,config]); + assert.equal(await page.locator('#sptv-native-settings').count(),0,'No custom settings panel on Home'); + await page.evaluate(()=>{document.querySelector('main').innerHTML='
'}); + await page.waitForSelector('#sptv-native-settings'); + assert.equal(await page.locator('#native').textContent(),'About Spotify','Existing native row retained'); + assert.equal(await page.locator('#sptv-native-settings button').count(),11); + await page.locator('#native').focus();await page.keyboard.press('ArrowDown'); + assert.equal(await page.evaluate(()=>document.activeElement.dataset.sptvAction),'theme'); + await page.keyboard.press('Enter');assert.deepEqual(await page.evaluate(()=>window.calls),['theme']); + await page.keyboard.press('ArrowUp');assert.equal(await page.evaluate(()=>document.activeElement.id),'native'); + await page.evaluate(c=>window.__sptvSettings.configure(c),config); + assert.equal(await page.locator('#sptv-native-settings').count(),1,'Repeated settings updates are idempotent'); + await page.locator('[data-sptv-action="hush"]').click();assert.equal((await page.evaluate(()=>window.calls)).at(-1),'hush'); + await page.evaluate(c=>window.__sptvSettings.configure({...c,hushEnabled:true}),config); + assert.equal(await page.locator('[data-sptv-action="hush"] p').textContent(),'On'); + await page.evaluate(()=>document.querySelector('main').replaceChildren()); + await page.waitForFunction(()=>!document.querySelector('#sptv-native-settings')); + assert.equal(await page.locator('#sptv-native-settings').count(),0,'Settings removed when native route is left'); + await browser.close();console.log('Native settings: route scoping, native rows, D-pad, actions, state and cleanup passed'); +})().catch(e=>{console.error(e);process.exit(1)}); From c09378bfbf1bd12a3ff8d51453b4e489d256999e Mon Sep 17 00:00:00 2001 From: Tumelo Rathebe <96668318+AlphadogRSA@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:26:35 +0200 Subject: [PATCH 3/7] Register native settings bridge before navigation and prevent Hush recovery latch --- .github/workflows/test.yml | 2 + rebuild_release.py | 12 ++++++ .../kotlin/dev/aurora/patches/TvPatches.kt | 31 +++++++++++++- src/dev/aurora/tvpatch/Hooks.java | 3 ++ src/dev/aurora/tvpatch/HushIntegration.java | 10 ++--- src/dev/aurora/tvpatch/NativeSettings.java | 32 ++++++++------- tests/HushPolicyTest.java | 4 ++ tests/test_settings_bridge.py | 40 +++++++++++++++++++ 8 files changed, 113 insertions(+), 21 deletions(-) create mode 100644 tests/test_settings_bridge.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0d72020..7ee7ee5 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -37,6 +37,8 @@ jobs: java -ea -cp test-classes HushPolicyTest - name: Test modular fingerprints run: bash revanced/gradlew -p revanced testFingerprints + - name: Verify WebView bridge lifecycle + run: python3 -m unittest discover -s tests -p test_settings_bridge.py -v - name: Check source tools run: | python3 -m py_compile patch.py import_lyrics.py diff --git a/rebuild_release.py b/rebuild_release.py index 7ab0da3..4ce9cae 100644 --- a/rebuild_release.py +++ b/rebuild_release.py @@ -36,6 +36,18 @@ def rebuild(source,dex,apktool,apkeditor,output): old=smali/'dev/aurora/tvpatch' if old.exists():shutil.rmtree(old);removed+=1 if not removed:raise ValueError('Expected the previous TV extension; refusing to patch an unknown client') + # Register the bridge before Spotify's first loadUrl, not at page completion. + hooks=0 + for smali in decoded.glob('smali*/com/spotify/tv/**/*.smali'): + text=smali.read_text() + pattern=r'(?m)^( invoke-virtual(?:/range)? \{([^}]+)\}, Landroid/webkit/WebView;->loadUrl\([^\n]+)$' + def inject(match): + receiver=match.group(2).split(',')[0].split(' .. ')[0].strip() + return f' invoke-static/range {{{receiver} .. {receiver}}}, Ldev/aurora/tvpatch/Hooks;->beforeLoad(Landroid/webkit/WebView;)V\n\n'+match.group(1) + text,count=re.subn(pattern,inject,text);hooks+=count + if count:smali.write_text(text) + if hooks!=2:raise ValueError(f'Expected two verified TV WebView loads, got {hooks}') + print(f'Pre-navigation bridge hooks: {hooks}') manifest=decoded/'AndroidManifest.xml';tree=ET.parse(manifest);root=tree.getroot() ns='http://schemas.android.com/apk/res/android';ET.register_namespace('android',ns) attr=lambda k:'{'+ns+'}'+k diff --git a/revanced/src/main/kotlin/dev/aurora/patches/TvPatches.kt b/revanced/src/main/kotlin/dev/aurora/patches/TvPatches.kt index 5c93a23..0dbb03d 100644 --- a/revanced/src/main/kotlin/dev/aurora/patches/TvPatches.kt +++ b/revanced/src/main/kotlin/dev/aurora/patches/TvPatches.kt @@ -6,6 +6,8 @@ import app.revanced.patcher.extensions.* import app.revanced.patcher.patch.* import com.android.tools.smali.dexlib2.Opcode import com.android.tools.smali.dexlib2.iface.instruction.TwoRegisterInstruction +import com.android.tools.smali.dexlib2.iface.instruction.FiveRegisterInstruction +import com.android.tools.smali.dexlib2.iface.instruction.RegisterRangeInstruction import com.android.tools.smali.dexlib2.iface.instruction.OneRegisterInstruction import com.android.tools.smali.dexlib2.iface.instruction.ReferenceInstruction import com.android.tools.smali.dexlib2.iface.reference.StringReference @@ -116,7 +118,34 @@ val tvRemotePatch = bytecodePatch(name = "TV remote settings menu", use = false) val tvWebViewPatch = bytecodePatch(name = "TV WebView theme hook", use = false) { compatibleWith(PACKAGE(VERSION)) dependsOn(tvLifecyclePatch, tvAssetsPatch) - apply { resolve(Fingerprints.page).addInstruction(0, "invoke-static/range {p1 .. p1}, $HOOK->page(Landroid/webkit/WebView;)V") } + apply { + resolve(Fingerprints.page).addInstruction(0, "invoke-static/range {p1 .. p1}, $HOOK->page(Landroid/webkit/WebView;)V") + var count = 0 + for (definition in classDefs.filter { it.type.startsWith("Lcom/spotify/tv/") }) { + val candidates = definition.methods.filter { method -> + method.implementation?.instructions?.any { + val ref = (it as? ReferenceInstruction)?.reference as? MethodReference + ref?.definingClass == "Landroid/webkit/WebView;" && ref.name == "loadUrl" + } == true + } + if (candidates.isEmpty()) continue + val mutable = classDefs.getOrReplaceMutable(definition) + for (original in candidates) { + val method = mutable.methods.single { it.name == original.name && it.parameterTypes == original.parameterTypes && it.returnType == original.returnType } + val calls = method.implementation!!.instructions.withIndex().filter { + val ref = (it.value as? ReferenceInstruction)?.reference as? MethodReference + ref?.definingClass == "Landroid/webkit/WebView;" && ref.name == "loadUrl" + } + for (call in calls.asReversed()) { + val register = (call.value as? FiveRegisterInstruction)?.registerC + ?: (call.value as RegisterRangeInstruction).startRegister + method.addInstruction(call.index, "invoke-static/range {v$register .. v$register}, $HOOK->beforeLoad(Landroid/webkit/WebView;)V") + count++ + } + } + } + require(count == 2) { "Expected two verified pre-navigation WebView loads, found $count" } + } } val tvSessionPatch = bytecodePatch(name = "TV own-session lyrics and timer", use = false) { diff --git a/src/dev/aurora/tvpatch/Hooks.java b/src/dev/aurora/tvpatch/Hooks.java index a3e4ea1..97a0db7 100644 --- a/src/dev/aurora/tvpatch/Hooks.java +++ b/src/dev/aurora/tvpatch/Hooks.java @@ -122,6 +122,8 @@ private static WebView find(View root) { } return null; } + static Activity activeActivity() { return activity.get(); } + public static void beforeLoad(WebView view) { NativeSettings.register(view); } public static void attach(Activity a) { try { activity = new WeakReference<>(a); @@ -133,6 +135,7 @@ public static void attach(Activity a) { web = new WeakReference<>(view); if (token != null) connectController(a.getApplicationContext()); if (!started) { started = true; UI.post(ticker); } + if (view != null) NativeSettings.register(view); HushIntegration.prepare(a); if (view != null) apply(view); Log.i("SPTV", "Activity extension attached"); diff --git a/src/dev/aurora/tvpatch/HushIntegration.java b/src/dev/aurora/tvpatch/HushIntegration.java index 625f56a..4a91427 100644 --- a/src/dev/aurora/tvpatch/HushIntegration.java +++ b/src/dev/aurora/tvpatch/HushIntegration.java @@ -23,7 +23,6 @@ public final class HushIntegration { private static final ExecutorService WORK = Executors.newSingleThreadExecutor(); private static SharedPreferences prefs(Context c) { return c.getSharedPreferences("spotifyplus_tv",0); } private static volatile String message = "Helper setup required"; - private static boolean restarting; private static int recovery; private HushIntegration() {} @@ -67,22 +66,21 @@ public static void tick(Context c, MediaController controller, boolean ad, long } else if(now-pending>20000) fail(p,now,"Recovery timed out · muting fallback"); return; } - if(restarting || !HushPolicy.attempt(p.getBoolean("hushEnabled",false),HushHelper.ready(),ad,active, + if(!HushPolicy.attempt(p.getBoolean("hushEnabled",false),HushHelper.ready(),ad,active, now,p.getLong("hushLastAttempt",0),p.getLong("hushLastFailure",0),pending,sleepAt))return; - restarting=true; // Commit before asking the external helper to kill this process. if(!p.edit().putLong("hushPending",now).putLong("hushLastAttempt",now).putLong("hushPendingSleepAt",sleepAt).commit()) { - restarting=false;message="Could not save recovery state";return; + message="Could not save recovery state";return; } message="Restarting Spotify"; WORK.execute(() -> { String result=HushHelper.run(Commands.RESTART,"com.spotify.tv.android/.SpotifyTVActivity"); // Normally this caller has died. If it survives, do not leave a latched request forever. - if(result==null)UI.post(() -> { restarting=false;fail(p,System.currentTimeMillis(),"Helper unavailable · muting fallback"); }); + if(result==null)UI.post(() -> { fail(p,System.currentTimeMillis(),"Helper unavailable · muting fallback"); }); }); } private static void fail(SharedPreferences p,long now,String reason) { - p.edit().remove("hushPending").putLong("hushLastFailure",now).apply(); message=reason;restarting=false; + p.edit().remove("hushPending").putLong("hushLastFailure",now).apply(); message=reason; } public static void recover(Context c,MediaController controller) { SharedPreferences p=prefs(c); diff --git a/src/dev/aurora/tvpatch/NativeSettings.java b/src/dev/aurora/tvpatch/NativeSettings.java index dcb2d86..4fa914e 100644 --- a/src/dev/aurora/tvpatch/NativeSettings.java +++ b/src/dev/aurora/tvpatch/NativeSettings.java @@ -1,6 +1,8 @@ package dev.aurora.tvpatch; import android.app.Activity; +import android.os.Handler; +import android.os.Looper; import android.webkit.JavascriptInterface; import android.webkit.WebView; import org.json.JSONObject; @@ -10,6 +12,7 @@ /** Fixed settings actions only; the bridge never accepts code, shell commands or URLs. */ public final class NativeSettings { + private static final Handler UI=new Handler(Looper.getMainLooper()); private static String script; private static WeakReference attached=new WeakReference<>(null); private static String signature=""; @@ -22,21 +25,22 @@ static boolean trusted(WebView view) { String host=android.net.Uri.parse(url).getHost(); return host!=null && (host.equals("spotify.com")||host.endsWith(".spotify.com")||host.equals("tv.scdn.co")); } + public static void register(WebView view) { + // Register before loadUrl. A new WebView legitimately has no trusted URL yet. + if(attached.get()==view)return; + attached=new WeakReference<>(view);signature=""; + view.addJavascriptInterface(new Object() { + @JavascriptInterface public void action(String action) { + if(action==null || action.length()>24)return; + UI.post(() -> { + Activity a=Hooks.activeActivity(); + if(a!=null && !a.isFinishing() && attached.get()==view && trusted(view))Hooks.settingsAction(a,action); + }); + } + },"SpotifyPlusSettings"); + } public static void attach(WebView view,Activity activity) { - if(!trusted(view))return; - if(attached.get()!=view) { - attached=new WeakReference<>(view);signature=""; - WeakReference owner=new WeakReference<>(activity); - view.addJavascriptInterface(new Object() { - @JavascriptInterface public void action(String action) { - if(action==null || action.length()>24)return; - Activity a=owner.get();if(a==null)return; - a.runOnUiThread(() -> { if(!a.isFinishing() && trusted(view))Hooks.settingsAction(a,action); }); - } - },"SpotifyPlusSettings"); - } - // addJavascriptInterface becomes visible on the next page load. page() also calls attach; - // attachment at Activity creation registers the bridge before the signed-in page loads. + register(view); refresh(view,true); } public static void refresh(WebView view,boolean force) { diff --git a/tests/HushPolicyTest.java b/tests/HushPolicyTest.java index 1b4ca2c..c04cb39 100644 --- a/tests/HushPolicyTest.java +++ b/tests/HushPolicyTest.java @@ -11,6 +11,10 @@ public static void main(String[] args) { assert !HushPolicy.attempt(true,true,true,true,1000000,0,0,999000,0); assert !HushPolicy.attempt(true,true,true,true,1000000,0,0,0,1000000); assert HushPolicy.attempt(true,true,true,true,1000000,900000,800000,0,1000001); + // If the original app survives the helper call, clearing persisted pending is sufficient: + // no process-local latch may permanently prevent a later attempt. + assert !HushPolicy.attempt(true,true,true,true,1000000,990000,0,990000,0); + assert HushPolicy.attempt(true,true,true,true,1030000,990000,0,0,0); System.out.println("HushPolicyTest: opt-in, helper loss, pause, cooldown, pending and sleep passed"); } } diff --git a/tests/test_settings_bridge.py b/tests/test_settings_bridge.py new file mode 100644 index 0000000..e56ba24 --- /dev/null +++ b/tests/test_settings_bridge.py @@ -0,0 +1,40 @@ +"""Run the production bridge against a minimal Android lifecycle fake (no preinstalled JS bridge).""" +from pathlib import Path +import subprocess +import tempfile +import unittest + +ROOT=Path(__file__).resolve().parents[1] +STUBS={ + 'android/app/Activity.java':'package android.app; public class Activity { public boolean isFinishing(){return false;} }', + 'android/os/Looper.java':'package android.os; public class Looper { public static Looper getMainLooper(){return new Looper();} }', + 'android/os/Handler.java':'package android.os; public class Handler {public Handler(Looper l){} public void post(Runnable r){r.run();}}', + 'android/net/Uri.java':'package android.net; public class Uri {java.net.URI u; public static Uri parse(String s){Uri r=new Uri();r.u=java.net.URI.create(s);return r;} public String getHost(){return u.getHost();}}', + 'android/content/Context.java':'package android.content; public class Context {public android.content.res.AssetManager getAssets(){return new android.content.res.AssetManager();}}', + 'android/content/res/AssetManager.java':'package android.content.res; public class AssetManager { public java.io.InputStream open(String s){return new java.io.ByteArrayInputStream(new byte[0]);} }', + 'android/webkit/JavascriptInterface.java':'package android.webkit; public @interface JavascriptInterface {}', + 'android/webkit/WebView.java':'package android.webkit; public class WebView {public String url;public Object bridge; public int registrations; public String getUrl(){return url;} public void addJavascriptInterface(Object b,String name){bridge=b;registrations++;} public android.content.Context getContext(){return new android.content.Context();} public void evaluateJavascript(String code,Object callback){} }', + 'dev/aurora/tvpatch/Hooks.java':'package dev.aurora.tvpatch; public class Hooks {public static int calls;public static android.app.Activity activeActivity(){return new android.app.Activity();} public static void settingsAction(android.app.Activity a,String s){calls++;} public static org.json.JSONObject settingsSnapshot(android.content.Context c){return new org.json.JSONObject();}}', + 'BridgeLifecycle.java':'''import dev.aurora.tvpatch.NativeSettings;import dev.aurora.tvpatch.Hooks;import android.webkit.WebView; +public class BridgeLifecycle {public static void main(String[] a)throws Exception { + WebView v=new WebView(); NativeSettings.register(v); + assert v.registrations==1 : "Interface must exist before navigation when URL is null"; + java.lang.reflect.Method action=v.bridge.getClass().getDeclaredMethod("action",String.class);action.setAccessible(true); + action.invoke(v.bridge,"theme");assert Hooks.calls==0 : "Blank documents cannot invoke settings"; + v.url="https://api-partner.spotify.com/tvapp?platform=androidtv"; + action.invoke(v.bridge,"theme");assert Hooks.calls==1 : "First trusted document can invoke settings without reload"; + NativeSettings.register(v);assert v.registrations==1 : "Repeated attachment must not replace bridge"; + v.url="https://example.com/";action.invoke(v.bridge,"theme");assert Hooks.calls==1 : "Untrusted navigation is rejected"; + System.out.println("Bridge lifecycle: first-load registration and invocation-time trust passed"); +}}''', +} +class BridgeLifecycleTest(unittest.TestCase): + def test_first_document_works_and_untrusted_documents_cannot_invoke(self): + with tempfile.TemporaryDirectory() as directory: + root=Path(directory);files=[] + for name,source in STUBS.items(): + path=root/name;path.parent.mkdir(parents=True,exist_ok=True);path.write_text(source);files.append(str(path)) + files.append(str(ROOT/'src/dev/aurora/tvpatch/NativeSettings.java')) + subprocess.run(['java','-m','jdk.compiler/com.sun.tools.javac.Main','-cp',str(ROOT/'.tools/json.jar'),'-d',str(root/'classes'),*files],check=True) + subprocess.run(['java','-ea','-cp',str(root/'classes')+':'+str(ROOT/'.tools/json.jar'),'BridgeLifecycle'],check=True) +if __name__=='__main__':unittest.main() From c2257050886ae548e4390aeb5e725283a8cb5d10 Mon Sep 17 00:00:00 2001 From: Tumelo Rathebe <96668318+AlphadogRSA@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:29:22 +0200 Subject: [PATCH 4/7] Record 1.3.0.1 validation and explicit unsigned/device-test limits --- VERIFICATION.md | 12 ++++++++++++ docs/superpowers/plans/2026-10-27-hush-tv.md | 6 +++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/VERIFICATION.md b/VERIFICATION.md index 2254555..45460eb 100644 --- a/VERIFICATION.md +++ b/VERIFICATION.md @@ -1,3 +1,15 @@ +# Version 1.3.0.1 — verified source and unsigned package (2026-10-27) + +- Final functional source: `c09378bfbf1bd12a3ff8d51453b4e489d256999e`. GitHub Actions run `40503784827` passed all three jobs: deterministic/helper/bridge/fingerprint checks, browser presentation/native-settings regressions, and Android compile/DEX/single-APK rebuild. +- Local Java checks passed: lyrics 13, provider 10, ad-mute state 13, audio-session isolation 7, existing EQ/cache 10, plus graphic curve interpolation/migration/clamping/cache, sleep deadline and Hush policy cases. The first-document WebView lifecycle test passes without supplying a JavaScript bridge in advance; it checks null-URL registration, trusted first-page invocation and rejection after untrusted navigation. +- Browser checks passed: 12 presentation, 16 theme/promotion, 4 performance checks, plus native settings route scoping, original-row preservation, D-pad entry/return, actions, state refresh and cleanup. +- Review fixes: the bridge is now injected immediately before both observed native WebView `loadUrl` calls; recovery no longer has a process-local restart latch that can remain stuck if the helper fails to terminate its caller. The pending sleep deadline remains independent of visible timer cleanup. +- The local rebuilt single APK reports package `com.spotify.tv.android`, versionName `1.3.0.1`, versionCode `2340200`; ARMv7 player libraries are merged. Earlier extension definitions are removed, the new runtime classes occur once, and the guarded embedded helper provider/full GPL notices are present. There is no companion app. +- Final local APK SHA-256: `202c36000fb1579e3020ffb82ff86155bc8fe0cab508da5b07c0088fdb66c1f5`. Android apksig verification confirms **unsigned, zero signer certificates**. It must be signed using the retained TV key before same-key installation; no new signing key was substituted. +- Not verified: installation/update on the TV, live D-pad behavior in Spotify’s complete SPA, actual frequency/loudness response, real ad-break dropping, queue context, process-restart playback, background/screen behavior and helper setup after reboot. No live-TV success claim is made for this version. + +## Historical 0.5 and earlier observations + # Verification — 26 October 2026 ## Release 0.5 diff --git a/docs/superpowers/plans/2026-10-27-hush-tv.md b/docs/superpowers/plans/2026-10-27-hush-tv.md index d152c13..9a6722e 100644 --- a/docs/superpowers/plans/2026-10-27-hush-tv.md +++ b/docs/superpowers/plans/2026-10-27-hush-tv.md @@ -39,10 +39,10 @@ Files: `GraphicEq*.java`, `AudioEffectPlan.java`, `AudioDsp.java`, `Hooks.java`, Files: `spotifyplus-settings.js`, `NativeSettings.java`, `Hooks.java`, native settings browser test. - [x] Inspect the delivered TV settings DOM and keep original rows. - [x] Add scoped rows, fixed-action bridge, state synchronization and D-pad entry/return. -- [ ] Run browser regressions in CI and review the settings layout. +- [x] Run browser/native-settings regressions in CI; live TV layout remains a device check. ### Task 4: Rebuild and delivery Files: `rebuild_release.py`, build/install/sign scripts, manifest patch, CI, notices/docs. - [x] Add pinned-source upgrade and single APK merge with explicit unsigned output. -- [ ] Complete local rebuild, inspect final version/provider/classes/resources and run CI. -- [ ] Publish final source/verification and deliver the unsigned build with signing limitation. +- [x] Complete local rebuild, inspect final version/provider/classes/resources and pass all CI jobs. +- [x] Publish source and verification; save the explicitly unsigned single APK for delivery. From 4d960f00bdd3d38fd09e29fd29580f8e3736a903 Mon Sep 17 00:00:00 2001 From: Tumelo Rathebe <96668318+AlphadogRSA@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:43:41 +0200 Subject: [PATCH 5/7] Add certificate-matching Windows signing and safe TV update installer --- installer/Install-Spotify.cmd | 6 +++ installer/Install-Spotify.ps1 | 82 ++++++++++++++++++++++++++++++++++ installer/README.txt | 31 +++++++++++++ installer/SpotifyTvSigner.java | 58 ++++++++++++++++++++++++ 4 files changed, 177 insertions(+) create mode 100644 installer/Install-Spotify.cmd create mode 100644 installer/Install-Spotify.ps1 create mode 100644 installer/README.txt create mode 100644 installer/SpotifyTvSigner.java diff --git a/installer/Install-Spotify.cmd b/installer/Install-Spotify.cmd new file mode 100644 index 0000000..69144cf --- /dev/null +++ b/installer/Install-Spotify.cmd @@ -0,0 +1,6 @@ +@echo off +cd /d "%~dp0" +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Install-Spotify.ps1" +echo. +echo Keep any error above if the installation stopped. +pause diff --git a/installer/Install-Spotify.ps1 b/installer/Install-Spotify.ps1 new file mode 100644 index 0000000..a1816bd --- /dev/null +++ b/installer/Install-Spotify.ps1 @@ -0,0 +1,82 @@ +param([string]$KeyStore, [string]$Serial, [switch]$SignOnly) +$ErrorActionPreference = 'Stop' +$expectedCert = '1ff3a55d2b53b7f232d47584eed11ed4445d0eba6c735212d071e62734fc57a1' +$apk = Join-Path $PSScriptRoot 'SpotifyPlus-TV-1.3.0.1-unsigned.apk' +if ((Get-FileHash -LiteralPath $apk -Algorithm SHA256).Hash.ToLower() -ne '202c36000fb1579e3020ffb82ff86155bc8fe0cab508da5b07c0088fdb66c1f5') { throw 'APK checksum mismatch. Download and extract the package again.' } +$java = $null +if ($env:JAVA_HOME) { + $candidate = Join-Path $env:JAVA_HOME 'bin/java.exe' + if (Test-Path -LiteralPath $candidate) { $java = $candidate } +} +if (-not $java) { $command = Get-Command java -ErrorAction SilentlyContinue; if ($command) { $java = $command.Source } } +if (-not $java) { + foreach ($vendor in @('Eclipse Adoptium','Java','Microsoft')) { + $vendorPath = Join-Path $env:ProgramFiles $vendor + if (Test-Path -LiteralPath $vendorPath) { + foreach ($directory in Get-ChildItem -LiteralPath $vendorPath -Directory) { + $candidate = Join-Path $directory.FullName 'bin/java.exe' + if (Test-Path -LiteralPath $candidate) { $java = $candidate; break } + } + } + if ($java) { break } + } +} +if (-not $java) { throw 'Java 17 or newer was not found. Use the Java installation from your previous Spotify build, then run this again.' } +if (-not $KeyStore) { + $candidates = @((Join-Path $env:USERPROFILE '.android/debug.keystore')) + if ($env:ANDROID_USER_HOME) { $candidates += Join-Path $env:ANDROID_USER_HOME 'debug.keystore' } + if ($env:ANDROID_SDK_HOME) { $candidates += Join-Path $env:ANDROID_SDK_HOME '.android/debug.keystore' } + $KeyStore = $candidates | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +} +if (-not $KeyStore) { $KeyStore = Read-Host 'Path to the signing .keystore/.jks used for the previous TV build (blank to stop)' } +if (-not $KeyStore -or -not (Test-Path -LiteralPath $KeyStore)) { + throw 'The original signing key was not found. Nothing was installed or uninstalled. Keep the existing TV app; share this message so we can choose the next step.' +} +$key = (Resolve-Path -LiteralPath $KeyStore).Path +$classPath = (Join-Path $PSScriptRoot 'tools/SpotifyTvSigner.jar') + ';' + (Join-Path $PSScriptRoot 'tools/apksig.jar') +$output = Join-Path $PSScriptRoot ('SpotifyPlus-TV-1.3.0.1-signed-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '.apk') +Write-Host 'Checking the signing key against your previous TV build...' +& $java -cp $classPath SpotifyTvSigner $apk $key $output $expectedCert +if ($LASTEXITCODE -ne 0) { throw 'Signing stopped. The key may not match, its password may differ, or Java may be older than 17. Nothing was installed or uninstalled. Custom passwords can be supplied locally through SPTV_STORE_PASSWORD and SPTV_KEY_PASSWORD.' } +if ($SignOnly) { Write-Host "Installable same-key APK: $output"; exit 0 } +$adb = $null +$command = Get-Command adb -ErrorAction SilentlyContinue +if ($command) { $adb = $command.Source } +if (-not $adb -and $env:LOCALAPPDATA) { + $candidate = Join-Path $env:LOCALAPPDATA 'Android/Sdk/platform-tools/adb.exe' + if (Test-Path -LiteralPath $candidate) { $adb = $candidate } +} +if (-not $adb) { + $candidate = Join-Path $PSScriptRoot 'tools/platform-tools/adb.exe' + if (-not (Test-Path -LiteralPath $candidate)) { + Write-Host 'Downloading official Android platform-tools for the TV connection...' + $archive = Join-Path $PSScriptRoot 'tools/platform-tools.zip' + Invoke-WebRequest -UseBasicParsing -Uri 'https://dl.google.com/android/repository/platform-tools-latest-windows.zip' -OutFile $archive + Expand-Archive -LiteralPath $archive -DestinationPath (Join-Path $PSScriptRoot 'tools') -Force + } + $adb = $candidate +} +if (-not $Serial) { + $devices = @(& $adb devices | Where-Object { $_ -match '^\S+\s+device$' } | ForEach-Object { ($_ -split '\s+')[0] }) + if ($devices.Count -eq 1) { $Serial = $devices[0] } + elseif ($devices.Count -gt 1) { $Serial = Read-Host 'More than one ADB device is connected. Enter the TV serial/IP' } + else { + $Serial = Read-Host 'Enter the TV IP address (enable network/USB debugging on the TV first)' + if ($Serial -notmatch '^(\d{1,3}\.){3}\d{1,3}(:\d{1,5})?$') { throw 'Enter an IPv4 address, optionally followed by :5555.' } + if ($Serial -notmatch ':') { $Serial += ':5555' } + & $adb connect $Serial + Write-Host 'Accept the debugging authorization on the TV if prompted.' + } +} +& $adb -s $Serial get-state +if ($LASTEXITCODE -ne 0) { throw "TV connection is not authorized/ready. The signed APK is saved at $output. Nothing was uninstalled." } +Write-Host 'Updating Spotify without uninstalling or clearing data...' +& $adb -s $Serial install -r $output +if ($LASTEXITCODE -ne 0) { throw 'Update failed. The existing app was not uninstalled or cleared. Keep the error shown above.' } +& $adb -s $Serial shell pm grant com.spotify.tv.android android.permission.DUMP +if ($LASTEXITCODE -ne 0) { Write-Warning 'Spotify installed, but EQ diagnostic permission needs setup.' } +& $adb -s $Serial shell am start -W -n com.spotify.tv.android/.SpotifyTVActivity +if ($LASTEXITCODE -ne 0) { throw 'Spotify installed, but could not launch. Open it on the TV manually.' } +try { & (Join-Path $PSScriptRoot 'start-hush.ps1') -Serial $Serial -Adb $adb } +catch { Write-Warning "Spotify installed; Hush helper setup is still pending: $($_.Exception.Message)" } +Write-Host 'Spotify update installed. Open Spotify Settings to check the custom settings, EQ and Hush helper status.' diff --git a/installer/README.txt b/installer/README.txt new file mode 100644 index 0000000..275a432 --- /dev/null +++ b/installer/README.txt @@ -0,0 +1,31 @@ +SPOTIFY+ TV 1.3.0.1 - WINDOWS UPDATE INSTALLER + +1. Extract this entire ZIP on the Windows PC used for your previous Spotify TV build. +2. Double-click Install-Spotify.cmd. +3. Keep the PC and TV on the same network. Accept the TV's debugging authorization if asked. + +The installer checks the previous build's signing certificate. It looks for the standard +Android debug keystore on your PC, or asks for your original .jks/.keystore path. +It signs and verifies the APK locally before attempting an update. It does not upload, +print or include your private signing key. It never uninstalls Spotify or clears app data. + +If the key does not match or cannot be found, the installer stops. Do not uninstall the +working TV app to bypass this. Send the displayed error so the next step can be chosen. + +Java 17+ is required (the Java installation used for the previous build should work). +ADB is used if already installed; otherwise official Google platform-tools are downloaded. +For a non-default keystore password, set SPTV_STORE_PASSWORD locally before running the +PowerShell script. SPTV_KEY_PASSWORD is only needed when the key password differs. +Do not send passwords in chat or commit them to GitHub. + +Signing only, without connecting to the TV: +powershell -NoProfile -ExecutionPolicy Bypass -File .\Install-Spotify.ps1 -SignOnly + +This APK is for the inspected ARMv7 Android TV build. Automated source/build tests passed; +real TV navigation, sound, Hush ad skipping/recovery and queue behavior still require testing. +Hush uses an embedded ADB-started helper; no second app is installed. Run start-hush.ps1 +again after a TV reboot. Source and GPL/MIT notices are in the source repository: +https://github.com/AlphadogRSA/spotifyplus-tv-patch/pull/1 + +Included signing library: Android apksig 8.4.0, Apache License 2.0. +https://source.android.com/docs/setup/about/licenses diff --git a/installer/SpotifyTvSigner.java b/installer/SpotifyTvSigner.java new file mode 100644 index 0000000..7580f85 --- /dev/null +++ b/installer/SpotifyTvSigner.java @@ -0,0 +1,58 @@ +import com.android.apksig.ApkSigner; +import com.android.apksig.ApkVerifier; +import java.io.File; +import java.nio.file.Files; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HexFormat; + +/** Sign only with a key matching the existing installation's public certificate. */ +public final class SpotifyTvSigner { + static String fingerprint(X509Certificate cert) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(cert.getEncoded())); + } + public static void main(String[] args) { + try { sign(args); } + catch (Exception error) { System.err.println("STOPPED: " + error.getMessage()); System.exit(2); } + } + static void sign(String[] args) throws Exception { + if (args.length != 4) throw new IllegalArgumentException("Expected INPUT_APK KEYSTORE OUTPUT_APK EXPECTED_CERT_SHA256"); + File input=new File(args[0]), storeFile=new File(args[1]), output=new File(args[2]); + if (output.exists()) throw new IllegalArgumentException("Output already exists; move it first: " + output.getName()); + String expected=args[3].toLowerCase(); + if (!expected.matches("[a-f0-9]{64}")) throw new IllegalArgumentException("Invalid expected certificate fingerprint"); + String configured=System.getenv("SPTV_STORE_PASSWORD"); + char[] password=(configured==null ? "android" : configured).toCharArray(); + String configuredKey=System.getenv("SPTV_KEY_PASSWORD"); + char[] keyPassword=configuredKey==null ? password.clone() : configuredKey.toCharArray(); + try { + KeyStore store=KeyStore.getInstance(storeFile,password); + String selected=null; + for (String alias:Collections.list(store.aliases())) { + if (store.isKeyEntry(alias) && store.getCertificate(alias) instanceof X509Certificate cert + && fingerprint(cert).equals(expected)) { selected=alias; break; } + } + if (selected==null) throw new IllegalArgumentException("This key does not match the Spotify app on your TV. No APK was signed or installed."); + if (!(store.getKey(selected,keyPassword) instanceof PrivateKey key)) throw new IllegalArgumentException("Matching entry has no accessible private key"); + var certificates=new ArrayList(); + for(var cert:store.getCertificateChain(selected)) certificates.add((X509Certificate)cert); + var signer=new ApkSigner.SignerConfig.Builder("SpotifyPlusTV",key,certificates).build(); + new ApkSigner.Builder(Collections.singletonList(signer)).setInputApk(input).setOutputApk(output) + .setMinSdkVersion(26).setV1SigningEnabled(true).setV2SigningEnabled(true) + .setV3SigningEnabled(true).setV4SigningEnabled(false).build().sign(); + var verification=new ApkVerifier.Builder(output).setMinCheckedPlatformVersion(26).build().verify(); + if (!verification.isVerified() || verification.getSignerCertificates().size()!=1 + || !fingerprint(verification.getSignerCertificates().get(0)).equals(expected)) { + Files.deleteIfExists(output.toPath()); + throw new IllegalStateException("Signature verification failed; invalid output removed"); + } + System.out.println("SIGNED_AND_VERIFIED: " + output.getAbsolutePath()); + System.out.println("Certificate matches the previous Spotify TV installation."); + } finally { Arrays.fill(password,'\0'); Arrays.fill(keyPassword,'\0'); } + } +} From 35c64034ddc1d51fe7754dcf1b81321a9cb17aa9 Mon Sep 17 00:00:00 2001 From: Tumelo Rathebe <96668318+AlphadogRSA@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:49:25 +0200 Subject: [PATCH 6/7] Use bundled verified portable Java in the Windows installer --- installer/Install-Spotify.ps1 | 30 +++++++++++------------------- installer/README.txt | 9 +++++++-- 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/installer/Install-Spotify.ps1 b/installer/Install-Spotify.ps1 index a1816bd..c8b4ae7 100644 --- a/installer/Install-Spotify.ps1 +++ b/installer/Install-Spotify.ps1 @@ -3,25 +3,17 @@ $ErrorActionPreference = 'Stop' $expectedCert = '1ff3a55d2b53b7f232d47584eed11ed4445d0eba6c735212d071e62734fc57a1' $apk = Join-Path $PSScriptRoot 'SpotifyPlus-TV-1.3.0.1-unsigned.apk' if ((Get-FileHash -LiteralPath $apk -Algorithm SHA256).Hash.ToLower() -ne '202c36000fb1579e3020ffb82ff86155bc8fe0cab508da5b07c0088fdb66c1f5') { throw 'APK checksum mismatch. Download and extract the package again.' } -$java = $null -if ($env:JAVA_HOME) { - $candidate = Join-Path $env:JAVA_HOME 'bin/java.exe' - if (Test-Path -LiteralPath $candidate) { $java = $candidate } +# Use the bundled portable runtime. No Java installation, PATH edits or admin rights needed. +$javaArchive = Join-Path $PSScriptRoot 'tools/java17-windows-x64.zip' +if (-not (Test-Path -LiteralPath $javaArchive)) { throw 'Portable Java archive is missing. Extract the entire new installer ZIP, not just the script.' } +if ((Get-FileHash -LiteralPath $javaArchive -Algorithm SHA256).Hash.ToLower() -ne '7fe2324cc5901a89aaa0e8dc232075c59f2aca5270c533bdb1b861a5274af834') { throw 'Portable Java checksum mismatch. Download and extract the new installer again.' } +$javaDirectory = Join-Path $PSScriptRoot 'tools/java17' +$java = Join-Path $javaDirectory 'jdk-17.0.20+8-jre/bin/java.exe' +if (-not (Test-Path -LiteralPath $java)) { + Write-Host 'Preparing bundled portable Java 17 (first run only)...' + Expand-Archive -LiteralPath $javaArchive -DestinationPath $javaDirectory -Force } -if (-not $java) { $command = Get-Command java -ErrorAction SilentlyContinue; if ($command) { $java = $command.Source } } -if (-not $java) { - foreach ($vendor in @('Eclipse Adoptium','Java','Microsoft')) { - $vendorPath = Join-Path $env:ProgramFiles $vendor - if (Test-Path -LiteralPath $vendorPath) { - foreach ($directory in Get-ChildItem -LiteralPath $vendorPath -Directory) { - $candidate = Join-Path $directory.FullName 'bin/java.exe' - if (Test-Path -LiteralPath $candidate) { $java = $candidate; break } - } - } - if ($java) { break } - } -} -if (-not $java) { throw 'Java 17 or newer was not found. Use the Java installation from your previous Spotify build, then run this again.' } +if (-not (Test-Path -LiteralPath $java)) { throw 'Portable Java could not be extracted. Make sure the folder is writable, then run again.' } if (-not $KeyStore) { $candidates = @((Join-Path $env:USERPROFILE '.android/debug.keystore')) if ($env:ANDROID_USER_HOME) { $candidates += Join-Path $env:ANDROID_USER_HOME 'debug.keystore' } @@ -37,7 +29,7 @@ $classPath = (Join-Path $PSScriptRoot 'tools/SpotifyTvSigner.jar') + ';' + (Join $output = Join-Path $PSScriptRoot ('SpotifyPlus-TV-1.3.0.1-signed-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '.apk') Write-Host 'Checking the signing key against your previous TV build...' & $java -cp $classPath SpotifyTvSigner $apk $key $output $expectedCert -if ($LASTEXITCODE -ne 0) { throw 'Signing stopped. The key may not match, its password may differ, or Java may be older than 17. Nothing was installed or uninstalled. Custom passwords can be supplied locally through SPTV_STORE_PASSWORD and SPTV_KEY_PASSWORD.' } +if ($LASTEXITCODE -ne 0) { throw 'Signing stopped. The key may not match or its password may differ. Nothing was installed or uninstalled. Custom passwords can be supplied locally through SPTV_STORE_PASSWORD and SPTV_KEY_PASSWORD.' } if ($SignOnly) { Write-Host "Installable same-key APK: $output"; exit 0 } $adb = $null $command = Get-Command adb -ErrorAction SilentlyContinue diff --git a/installer/README.txt b/installer/README.txt index 275a432..54945de 100644 --- a/installer/README.txt +++ b/installer/README.txt @@ -1,4 +1,4 @@ -SPOTIFY+ TV 1.3.0.1 - WINDOWS UPDATE INSTALLER +SPOTIFY+ TV 1.3.0.1 - WINDOWS x64 UPDATE INSTALLER (PORTABLE JAVA INCLUDED) 1. Extract this entire ZIP on the Windows PC used for your previous Spotify TV build. 2. Double-click Install-Spotify.cmd. @@ -12,7 +12,8 @@ print or include your private signing key. It never uninstalls Spotify or clears If the key does not match or cannot be found, the installer stops. Do not uninstall the working TV app to bypass this. Send the displayed error so the next step can be chosen. -Java 17+ is required (the Java installation used for the previous build should work). +Portable Eclipse Temurin Java 17.0.20+8 is included and checksum-verified. +It runs from the installer folder; no system Java setup or administrator rights are needed. ADB is used if already installed; otherwise official Google platform-tools are downloaded. For a non-default keystore password, set SPTV_STORE_PASSWORD locally before running the PowerShell script. SPTV_KEY_PASSWORD is only needed when the key password differs. @@ -29,3 +30,7 @@ https://github.com/AlphadogRSA/spotifyplus-tv-patch/pull/1 Included signing library: Android apksig 8.4.0, Apache License 2.0. https://source.android.com/docs/setup/about/licenses + +Bundled runtime: Eclipse Temurin OpenJDK 17.0.20+8 for Windows x64 (JRE). +Source/release: https://github.com/adoptium/temurin17-binaries/releases/tag/jdk-17.0.20%2B8 +The runtime archive contains its original licenses and notices (GPLv2 with Classpath Exception). From 235c0c61dd24b1fcb6831172a57b57c720f772f5 Mon Sep 17 00:00:00 2001 From: AlphadogRSA <96668318+AlphadogRSA@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:59:37 +0200 Subject: [PATCH 7/7] Release 1.3.0.2 with signed APK Windows update installer --- .github/workflows/test.yml | 8 ++--- README.md | 6 ++-- installer/Install-Spotify.ps1 | 40 +++++------------------- installer/README.txt | 58 +++++++++++++---------------------- rebuild_release.py | 4 +-- sign-apk.ps1 | 2 +- 6 files changed, 41 insertions(+), 77 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7ee7ee5..96eabb5 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -93,11 +93,11 @@ jobs: curl --fail --location --output .tools/apktool.jar https://github.com/iBotPeaches/Apktool/releases/download/v3.0.3/apktool_3.0.3.jar curl --fail --location --output .tools/apkeditor.jar https://github.com/REAndroid/APKEditor/releases/download/V1.4.9/APKEditor-1.4.9.jar - name: Rebuild one unsigned APK - run: python3 rebuild_release.py --input .tools/current.apks --dex .tools/extension-dex/classes.dex --apktool .tools/apktool.jar --apkeditor .tools/apkeditor.jar --output build/release-1.3.0.1 + run: python3 rebuild_release.py --input .tools/current.apks --dex .tools/extension-dex/classes.dex --apktool .tools/apktool.jar --apkeditor .tools/apkeditor.jar --output build/release-1.3.0.2 - uses: actions/upload-artifact@v4 with: - name: SpotifyPlus-TV-1.3.0.1-unsigned + name: SpotifyPlus-TV-1.3.0.2-unsigned path: | - build/release-1.3.0.1/SpotifyPlus-TV-1.3.0.1-unsigned.apk - build/release-1.3.0.1/SHA256.txt + build/release-1.3.0.2/SpotifyPlus-TV-1.3.0.2-unsigned.apk + build/release-1.3.0.2/SHA256.txt if-no-files-found: error diff --git a/README.md b/README.md index aeb5268..7b7a20d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Spotify+ TV 1.3.0.1 +# Spotify+ TV 1.3.0.2 A personal modification of the inspected Spotify TV 1.134.2 ARMv7 client. **One installed Spotify app**, with the custom controls integrated into Spotify’s existing Settings/profile menu. @@ -9,7 +9,7 @@ A personal modification of the inspected Spotify TV 1.134.2 ARMv7 client. **One ## Build and install -The rebuilt **single APK** is labeled `1.3.0.1`. It retains Android versionCode `2340200` from the inspected client. This is a personal extension version, not an upstream Spotify release. The build merges the inspected ARMv7/English/TV-density splits into one file; it is not an all-architecture universal package. +The rebuilt **single APK** is labeled `1.3.0.2`. It retains Android versionCode `2340200` from the inspected client. This is a personal extension version, not an upstream Spotify release. The build merges the inspected ARMv7/English/TV-density splits into one file; it is not an all-architecture universal package. `rebuild_release.py` verifies the exact previous v0.5 installation archive, replaces only the extension definitions/assets, adds the guarded embedded helper provider, updates the version name and merges the split resources/libraries. It produces an **unsigned APK**, which must be signed with the existing retained key to update your installed app. The original key is not stored here. Use `sign-apk.ps1`; do not uninstall or clear data to work around a mismatched key. @@ -17,6 +17,8 @@ GitHub Actions builds the unsigned APK and runs source/helper, native-settings, The original four-APK source build is also supported by `build.ps1` with your own original inputs and key. `install.ps1` installs that set, grants the existing audio diagnostic permission, launches Spotify and starts the embedded helper. For a signed single APK use `adb install -r`, grant `android.permission.DUMP`, launch Spotify, then run `start-hush.ps1`. +The Windows release ZIP includes the signed APK and official ADB platform-tools. Extract it and run `Install-Spotify.cmd`; Java and a local signing key are not required. It verifies the APK checksum and updates without uninstalling or clearing app data. + ## Source and attribution Original UI, lyrics and audio implementation is MIT licensed. The helper sources/adaptations from [coldMEW/Hush](https://github.com/coldMEW/Hush), pinned to `4e9ded397338de5c69b1784c636feb3d34a8de01`, are GPL-3.0 and embedded with their full license/source notice. The ReVanced build host retains its GPL license. Clone with `--recurse-submodules` to obtain the pinned helper source. None of these licenses relicense Spotify’s proprietary code, assets or recordings. diff --git a/installer/Install-Spotify.ps1 b/installer/Install-Spotify.ps1 index c8b4ae7..a3dba0f 100644 --- a/installer/Install-Spotify.ps1 +++ b/installer/Install-Spotify.ps1 @@ -1,36 +1,12 @@ -param([string]$KeyStore, [string]$Serial, [switch]$SignOnly) +param([string]$Serial, [switch]$ValidateOnly) $ErrorActionPreference = 'Stop' -$expectedCert = '1ff3a55d2b53b7f232d47584eed11ed4445d0eba6c735212d071e62734fc57a1' -$apk = Join-Path $PSScriptRoot 'SpotifyPlus-TV-1.3.0.1-unsigned.apk' -if ((Get-FileHash -LiteralPath $apk -Algorithm SHA256).Hash.ToLower() -ne '202c36000fb1579e3020ffb82ff86155bc8fe0cab508da5b07c0088fdb66c1f5') { throw 'APK checksum mismatch. Download and extract the package again.' } -# Use the bundled portable runtime. No Java installation, PATH edits or admin rights needed. -$javaArchive = Join-Path $PSScriptRoot 'tools/java17-windows-x64.zip' -if (-not (Test-Path -LiteralPath $javaArchive)) { throw 'Portable Java archive is missing. Extract the entire new installer ZIP, not just the script.' } -if ((Get-FileHash -LiteralPath $javaArchive -Algorithm SHA256).Hash.ToLower() -ne '7fe2324cc5901a89aaa0e8dc232075c59f2aca5270c533bdb1b861a5274af834') { throw 'Portable Java checksum mismatch. Download and extract the new installer again.' } -$javaDirectory = Join-Path $PSScriptRoot 'tools/java17' -$java = Join-Path $javaDirectory 'jdk-17.0.20+8-jre/bin/java.exe' -if (-not (Test-Path -LiteralPath $java)) { - Write-Host 'Preparing bundled portable Java 17 (first run only)...' - Expand-Archive -LiteralPath $javaArchive -DestinationPath $javaDirectory -Force -} -if (-not (Test-Path -LiteralPath $java)) { throw 'Portable Java could not be extracted. Make sure the folder is writable, then run again.' } -if (-not $KeyStore) { - $candidates = @((Join-Path $env:USERPROFILE '.android/debug.keystore')) - if ($env:ANDROID_USER_HOME) { $candidates += Join-Path $env:ANDROID_USER_HOME 'debug.keystore' } - if ($env:ANDROID_SDK_HOME) { $candidates += Join-Path $env:ANDROID_SDK_HOME '.android/debug.keystore' } - $KeyStore = $candidates | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 -} -if (-not $KeyStore) { $KeyStore = Read-Host 'Path to the signing .keystore/.jks used for the previous TV build (blank to stop)' } -if (-not $KeyStore -or -not (Test-Path -LiteralPath $KeyStore)) { - throw 'The original signing key was not found. Nothing was installed or uninstalled. Keep the existing TV app; share this message so we can choose the next step.' -} -$key = (Resolve-Path -LiteralPath $KeyStore).Path -$classPath = (Join-Path $PSScriptRoot 'tools/SpotifyTvSigner.jar') + ';' + (Join-Path $PSScriptRoot 'tools/apksig.jar') -$output = Join-Path $PSScriptRoot ('SpotifyPlus-TV-1.3.0.1-signed-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '.apk') -Write-Host 'Checking the signing key against your previous TV build...' -& $java -cp $classPath SpotifyTvSigner $apk $key $output $expectedCert -if ($LASTEXITCODE -ne 0) { throw 'Signing stopped. The key may not match or its password may differ. Nothing was installed or uninstalled. Custom passwords can be supplied locally through SPTV_STORE_PASSWORD and SPTV_KEY_PASSWORD.' } -if ($SignOnly) { Write-Host "Installable same-key APK: $output"; exit 0 } +$apk = Join-Path $PSScriptRoot 'SpotifyPlus-TV-1.3.0.2.apk' +$expectedHash = 'f5ecdc1f466fc98be2f6853ff753bad38ee8ea9478f9127e3300b50c0ba6150b' +$hasher = [Security.Cryptography.SHA256]::Create() +try { $actualHash = [BitConverter]::ToString($hasher.ComputeHash([IO.File]::ReadAllBytes($apk))).Replace('-', '').ToLowerInvariant() } finally { $hasher.Dispose() } +if ($actualHash -ne $expectedHash) { throw 'APK checksum mismatch. Extract the installer ZIP again.' } +$output = $apk +if ($ValidateOnly) { Write-Host "Verified installer payload: $apk"; exit 0 } $adb = $null $command = Get-Command adb -ErrorAction SilentlyContinue if ($command) { $adb = $command.Source } diff --git a/installer/README.txt b/installer/README.txt index 54945de..227808d 100644 --- a/installer/README.txt +++ b/installer/README.txt @@ -1,36 +1,22 @@ -SPOTIFY+ TV 1.3.0.1 - WINDOWS x64 UPDATE INSTALLER (PORTABLE JAVA INCLUDED) - -1. Extract this entire ZIP on the Windows PC used for your previous Spotify TV build. -2. Double-click Install-Spotify.cmd. -3. Keep the PC and TV on the same network. Accept the TV's debugging authorization if asked. - -The installer checks the previous build's signing certificate. It looks for the standard -Android debug keystore on your PC, or asks for your original .jks/.keystore path. -It signs and verifies the APK locally before attempting an update. It does not upload, -print or include your private signing key. It never uninstalls Spotify or clears app data. - -If the key does not match or cannot be found, the installer stops. Do not uninstall the -working TV app to bypass this. Send the displayed error so the next step can be chosen. - -Portable Eclipse Temurin Java 17.0.20+8 is included and checksum-verified. -It runs from the installer folder; no system Java setup or administrator rights are needed. -ADB is used if already installed; otherwise official Google platform-tools are downloaded. -For a non-default keystore password, set SPTV_STORE_PASSWORD locally before running the -PowerShell script. SPTV_KEY_PASSWORD is only needed when the key password differs. -Do not send passwords in chat or commit them to GitHub. - -Signing only, without connecting to the TV: -powershell -NoProfile -ExecutionPolicy Bypass -File .\Install-Spotify.ps1 -SignOnly - -This APK is for the inspected ARMv7 Android TV build. Automated source/build tests passed; -real TV navigation, sound, Hush ad skipping/recovery and queue behavior still require testing. -Hush uses an embedded ADB-started helper; no second app is installed. Run start-hush.ps1 -again after a TV reboot. Source and GPL/MIT notices are in the source repository: -https://github.com/AlphadogRSA/spotifyplus-tv-patch/pull/1 - -Included signing library: Android apksig 8.4.0, Apache License 2.0. -https://source.android.com/docs/setup/about/licenses - -Bundled runtime: Eclipse Temurin OpenJDK 17.0.20+8 for Windows x64 (JRE). -Source/release: https://github.com/adoptium/temurin17-binaries/releases/tag/jdk-17.0.20%2B8 -The runtime archive contains its original licenses and notices (GPLv2 with Classpath Exception). +SPOTIFY+ TV 1.3.0.2 - WINDOWS UPDATE INSTALLER - 27 OCTOBER 2026 + +Extract the entire ZIP, then double-click Install-Spotify.cmd. +Keep the PC and TV on the same network and enable TV debugging. +Accept the TV authorization prompt if asked. Enter the TV IPv4 address when prompted. + +Includes the same-key signed APK and official Android platform-tools. +No Java, signing key, administrator access or system installation is required. +The installer checks the APK SHA256 before connecting. It updates using adb install -r, +grants the audio diagnostic permission, launches Spotify and starts the embedded Hush helper. +It never uninstalls Spotify or clears its data. A signature mismatch stops the update. + +Validation without connecting or installing: +powershell -NoProfile -ExecutionPolicy Bypass -File .\Install-Spotify.ps1 -ValidateOnly + +Hush is opt-in. Run start-hush.ps1 again after a TV reboot. +Target: the inspected Spotify TV 1.134.2 ARMv7 Android TV installation. +Version name: 1.3.0.2; original Android versionCode retained for same-key updates. +TV playback, D-pad, EQ sound and helper behavior require real-device testing. +Source: https://github.com/AlphadogRSA/spotifyplus-tv-patch/tree/feat/hush-tv +Original runtime: MIT; embedded Hush and patcher: GPL-3.0; Spotify remains proprietary. +Official platform-tools notices are included under tools/platform-tools/NOTICE.txt. diff --git a/rebuild_release.py b/rebuild_release.py index 4ce9cae..6702716 100644 --- a/rebuild_release.py +++ b/rebuild_release.py @@ -1,4 +1,4 @@ -"""Rebuild the exact previous personal TV release as one unsigned 1.3.0.1 APK. +"""Rebuild the exact previous personal TV release as one unsigned 1.3.0.2 APK. Requires compiled extension DEX and the checksum-pinned APK tooling. No signing keys are read. """ @@ -17,7 +17,7 @@ 'apktool':'dbf930b076c6b9be08d57c449cacefc3bdd6b71ebd59b3066fc0e1f5b14f9423', 'apkeditor':'a9cd40df818845456be6d696de6110c89edf4b0a0580cb83438ed6b25a366e67', } -VERSION='1.3.0.1' +VERSION='1.3.0.2' def verified(path,sha): if hashlib.sha256(path.read_bytes()).hexdigest()!=sha:raise ValueError(f'Checksum mismatch: {path.name}') def run(*args):subprocess.run(list(map(str,args)),check=True) diff --git a/sign-apk.ps1 b/sign-apk.ps1 index 15187fa..fc6736e 100644 --- a/sign-apk.ps1 +++ b/sign-apk.ps1 @@ -18,7 +18,7 @@ try { $signArgs = @('sign','--ks',$key,'--ks-key-alias',$KeyAlias,'--ks-pass','env:SPTV_STORE_PASSWORD','--out',$OutputApk) if ($env:SPTV_KEY_PASSWORD) { $signArgs += @('--key-pass','env:SPTV_KEY_PASSWORD') } $signArgs += $aligned - & (Join-Path $tools 'apksigner.bat') @args + & (Join-Path $tools 'apksigner.bat') @signArgs if ($LASTEXITCODE -ne 0) { throw 'APK signing failed.' } & (Join-Path $tools 'apksigner.bat') verify --min-sdk-version 26 $OutputApk if ($LASTEXITCODE -ne 0) { throw 'APK signature verification failed.' }