From ee7c6fb42a99d177a338d1adb842d2ff5dcc99d3 Mon Sep 17 00:00:00 2001 From: Parminder Klair Date: Fri, 27 Nov 2026 19:08:52 +0000 Subject: [PATCH] feat(app): Android Auto error states, Stations tab, and a build flag A failed car pick now shows the car why (the RNTP patch's MediaBrowserBridge.showError, through setCustomErrorMessage), cleared on the next pick and when audio plays; a cold start with no session fails in 8 s with an error session instead of waiting forever; the root is one browsable Stations tab (active station first, root hints honoured) with an empty state; CarCallers admits Gemini and, in debug builds, Media Controller Test. Android Auto is now off unless SUBWAVE_ANDROID_AUTO=1 at prebuild (plugins/withAndroidAuto.js): unset, the merged manifest declares no car support. eas.json gains production-auto (Play closed testing, submit track alpha) and apk (sideload); docs/RELEASE.md has the plan. --- CLAUDE.md | 2 +- app.json | 1 + docs/RELEASE.md | 66 ++++++- docs/TESTING.md | 166 +++++++++++++---- eas.json | 23 +++ .../android/src/main/AndroidManifest.xml | 20 +-- .../com/getsubwave/androidauto/CarCallers.kt | 14 ++ .../getsubwave/androidauto/CarConnectTask.kt | 24 ++- .../com/getsubwave/androidauto/CarStations.kt | 12 +- .../androidauto/SubwaveAndroidAutoModule.kt | 30 ++++ .../androidauto/SubwaveBrowseService.kt | 149 ++++++++++++++-- .../main/res/values/subwave_android_auto.xml | 9 + .../res/xml/subwave_automotive_app_desc.xml | 3 - modules/android-auto/index.ts | 32 ++++ patches/react-native-track-player+4.1.2.patch | 41 ++++- plugins/withAndroidAuto.js | 91 ++++++++++ scripts/android-auto-plugin.test.ts | 168 ++++++++++++++++++ scripts/android-auto.test.ts | 157 ++++++++++++++++ scripts/intent-tune.test.ts | 43 ++++- service.ts | 10 +- src/intents/car-errors.ts | 54 ++++++ src/intents/car-picks.ts | 54 +++++- src/intents/car.ts | 15 +- src/intents/tune-flow.ts | 31 +++- src/intents/tune.ts | 28 ++- 25 files changed, 1142 insertions(+), 101 deletions(-) create mode 100644 modules/android-auto/android/src/main/res/values/subwave_android_auto.xml delete mode 100644 modules/android-auto/android/src/main/res/xml/subwave_automotive_app_desc.xml create mode 100644 plugins/withAndroidAuto.js create mode 100644 scripts/android-auto-plugin.test.ts create mode 100644 src/intents/car-errors.ts diff --git a/CLAUDE.md b/CLAUDE.md index 10faa11..fe674d6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,7 +6,7 @@ The Expo / React Native player for iOS and Android, with its own `package.json`, - **`ios/` and `android/` are generated** (Continuous Native Generation, gitignored). Change `app.json`, `plugins/` or `assets/`, never the native folders. - **iOS uses the UIScene life cycle (`expo-build-properties` `ios.enableSceneSupport`).** Without it an iOS 27-SDK build is killed at launch on iOS 27; drop it with the SDK 58 upgrade, whose template does the same (TESTING.md). - **OTA cannot reach native code.** The Live Activity card (Lock Screen, Dynamic Island, the Apple Watch Smart Stack) is SwiftUI under `targets/live-activity/` and `modules/live-activity/ios/`, so a change there ships only in a new binary, like a dependency, `patches/`, plugin or native `app.json` change; the JS that drives it (`src/hooks/useLiveActivity.ts`) is OTA-able. The same holds for the App Intents (Siri, Shortcuts): Swift under `targets/live-activity/_shared/` and `modules/app-intents/ios/`, JS under `src/intents/`. `SubwaveLiveAttributes.swift` is compiled into both and must stay byte-identical (`npm test` checks): a mismatch stops the card rendering instead of failing the build. -- **Android Auto's browse session is RNTP's own**, reached through the patch's `MediaBrowserBridge`; `modules/android-auto` only lists stations, and a pick reaches `service.ts` as `remote-play-id`. Play enforced against a TTS-reading app once (#477); TESTING.md has the history and the device check. +- **Android Auto is off unless `SUBWAVE_ANDROID_AUTO=1` is set at prebuild** (`plugins/withAndroidAuto.js`), because Play enforced against a TTS-reading app once (#477): unset, the merged manifest declares no Android Auto support (`npm test` checks), and `docs/RELEASE.md` has the closed-testing-first plan. Its browse session is RNTP's own, reached through the patch's `MediaBrowserBridge`; `modules/android-auto` only lists stations, a pick reaches `service.ts` as `remote-play-id`, and a failed one shows the car why through the bridge's `showError` (`src/intents/car-errors.ts`), sending the driver to the phone only "when it's safe". TESTING.md has the history and the device check. - **The CarPlay app is off unless `SUBWAVE_CARPLAY=1` is set at prebuild** (`plugins/withCarPlay.js`), because a device build can't be signed with the CarPlay entitlement until Apple grants it. Unset, the Info.plist and entitlements are unchanged (`npm test` checks). Its Swift is `targets/live-activity/_shared/SubwaveCarPlay.swift` (TESTING.md). - **The station password is not the station login** (#478). Every check is the fail-closed `POST /station-auth`, and only the controller's own answers count: a 200 with its `{ ok: true }` body is a right password and a 401 with its `{ ok: false }` body a wrong one, while anything else keeps a saved password and saves no typed one (`stationAuthResult`, #2143, #2164); the password rides the stream as `?auth=` so Cast works; `createApi` reads it through a getter because the feed reset and the Live Activity lifecycle key on the `api` object's identity, so rebuilding the client on unlock would reset both. While playback is stuck, `src/lib/stuck-password-check.ts` asks again after every answer but a denial, never within 120 s of the last check or before a 429's `Retry-After` runs out, capped at the route's own window: it allows a household's address 20 attempts per 15 minutes (#2141, #2164). When the gate's stop takes a tuned-in listener off the air, the right typed password tunes them back in with no second press (`src/lib/gate-resume.ts`, the twin of the web's `lib/gateResume.ts`), through `tune`, so it is a listener's own load in `stream-recovery.ts`. `useStationGate` outlives a station switch, so the hold names the `api` it was taken on, and `tune` toggles, so it never runs for a listener already tuned in. - **Every stream reload goes through `src/lib/stream-recovery.ts` while the player is mounted** (#2114, #2139): one at a time, and never on a state event alone. A listener's own load (a tune-in, a retune, a Play from the lock screen, a headset, CarPlay or Bluetooth) always loads, queued behind one in flight. `service.ts` hands a remote Play to the mounted player (`src/lib/remote-play.ts`) and loads directly only when none is mounted, which Android's headless service allows; an App Intent's tune-in and station switch do the same (`src/intents/tune-flow.ts`), and so does an Android Auto pick. The watchdog, churn guard and error backoff each check the native media clock first, because a reload re-sends Icecast's burst and the listener hears audio twice; a regained link reads it through the pending check it brings forward, and with none pending reloads at once. Every load is checked even when it reports no state (iOS drops a repeated Loading, #2143), and an automatic reload is a failure until its item stays up, so a hung station backs off to 60 s. Playing resets that only provisionally: an item that fails after stopping within 4 s of its first Playing, judged from the moment it stopped, takes the reset back, and the reload after it waits at most 16 s, so a stream cut a moment in can't reload 35-60 times a minute. A stall never counts, however early, and stays on the 6 s watchdog: Icecast closes a stalled socket about 15 s after its source stops, so a longer wait hears that close as a failure, and a flapping source climbs to a minute of silence. A hold counts as the item's Playing, because JS can miss the real one. None of this runs during an iOS audio interruption (a call, Siri), which freezes the clock without a state event. diff --git a/app.json b/app.json index 0d898df..fe55bb3 100644 --- a/app.json +++ b/app.json @@ -104,6 +104,7 @@ } ], "./plugins/withAndroidUserCaTrust", + "./plugins/withAndroidAuto", "./plugins/withGradleMemory", [ "expo-secure-store", diff --git a/docs/RELEASE.md b/docs/RELEASE.md index 3b0e78f..9c7b077 100644 --- a/docs/RELEASE.md +++ b/docs/RELEASE.md @@ -65,7 +65,9 @@ a branch at update time. |---|---|---|---| | `development` / `development-device` | — | dev client | local Metro, no OTA | | `preview` | `preview` | internal (Android APK, iOS non-sim) | tester builds; OTA test bed | -| `production` | `production` | store builds (Android AAB, iOS) | App Store / Play | +| `production` | `production` | store builds (Android AAB, iOS) | App Store / Play, **no Android Auto** | +| `production-auto` | `production` | Android AAB with `SUBWAVE_ANDROID_AUTO=1` | Play **closed testing** with Android Auto (below) | +| `apk` | `production` | Android APK with `SUBWAVE_ANDROID_AUTO=1` | the sideloaded build with Android Auto (below) | `cli.appVersionSource = "remote"`, so build/version numbers live on EAS (`production` auto-increments). Don't hand-edit `ios.buildNumber` / @@ -135,12 +137,74 @@ eas build --profile production --platform android # AAB (EAS-managed keystore eas submit --profile production --platform android # uses secrets/play-service-account.json ``` +For the Android Auto build, see [Android Auto](#android-auto-closed-testing-first) +below: `production-auto` builds it and submits it to closed testing. + `eas submit` Android config (`eas.json` → `submit.production.android`) points at `secrets/play-service-account.json` (gitignored). Data-safety form answers: [`docs/store/PLAY-DATA-SAFETY.md`](./store/PLAY-DATA-SAFETY.md). Full flow + Play Console checklist: `subwave-app-android-release` skill and `PRODUCTION-READINESS.md` Phase D. +### Android Auto: closed testing first + +Android Auto is behind `SUBWAVE_ANDROID_AUTO=1` at prebuild +(`plugins/withAndroidAuto.js`, TESTING.md → Android Auto). Play enforced against +the app's first car listing (#477, 20 Jun 2026): *media apps that use a TTS +engine to read out content aren't permitted*. A browse tree doesn't change +that, so whether the car listing survives a second review is a **decision, not +code**. The plan: + +1. **Play Console, once:** Advanced settings → Form factors → Add form factor → + **Android Auto**, and opt in. A bundle that declares + `com.google.android.gms.car.application` goes through Google's extra manual + car review. +2. **Closed testing with Android Auto:** + + ```bash + eas build --profile production-auto --platform android + eas submit --profile production-auto --platform android # track "alpha" = closed testing, as a draft + ``` + + Why closed testing (`alpha`) and not `internal`: Google's car review is + *none* on internal testing, *non-blocking* on closed testing and + *blocking* on open testing and production + (developer.android.com/training/cars/distribute). Internal would never tell + us whether the listing passes; closed testing gets the verdict without + holding the build back. The release lands as a draft, so a person sends it + for review in Play Console. +3. **Review notes** (Play Console → the release / App access): say plainly + that the DJ voice is generated on the station's server and mixed into the + Icecast audio stream with the music, like a broadcast radio presenter; **the + app runs no TTS engine and reads no text aloud**, it plays one live audio + stream. Give the reviewer a station to play: the featured SUB/WAVE station + (`extra.featuredStation`, offered in onboarding) or a test station's address + and password, and say a station must be added on the phone once, after which + the car lists it. +4. **If the car review passes**, promote the same build towards production + (`production-auto` stays the Play profile from then on). +5. **If it is rejected**, ship Play with the flag off: + `eas build --profile production --platform android` and the usual `eas submit + --profile production`, same JS, no car listing. Don't argue the build past + the policy with a variant that hides the DJ. +6. **Separately, either way: the sideloaded APK.** `eas build --profile apk + --platform android` builds a release APK with Android Auto on. Publish it on + GitHub Releases and the website, by hand (nothing here uploads it), with + these notes for listeners: + - Android Auto lists only apps installed from Play unless developer mode + allows others: in Android Auto's settings tap *Version and permission + info* 10 times, then ⋮ → **Developer settings** → turn on **Unknown + sources**. Without that, SUB/WAVE doesn't appear in the car. + - The APK is signed with the upload key and Play's copy with Play's app + signing key, so one can't update the other: uninstall the Play version + before installing the APK, and the other way round. + +OTA updates reach all three Android builds alike: the flag changes only the +generated manifest, not the fingerprint's inputs (`npx expo-updates +fingerprint:generate --platform android` gives the same hash with and +without it), so the `production` channel serves `production`, `production-auto` +and `apk` binaries from one `eas update`. + --- ## Pre-release gate diff --git a/docs/TESTING.md b/docs/TESTING.md index 37d5795..ebbb4d5 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -60,7 +60,9 @@ and clears that token when `MusicService` is destroyed. `MusicModule.setupPlayer skips RNTP's no-activity-in-front refusal while a media browser is bound, a background-setup bypass that only the car's callers can switch on (`CarCallers`), and turns a start Android still refuses into a rejection -instead of a crash. Every Android session runs through both. +instead of a crash. Every Android session runs through both. The bridge also +puts the session in an error state for the car (`showError`, through the +connector's `setCustomErrorMessage`), cleared when audio plays. For a device smoke test, play a track with a known duration and inspect `adb shell dumpsys media_session`: its duration should be the song's duration @@ -323,23 +325,42 @@ it in `eas.json`'s `env` for the iOS profiles. ### Android Auto — the station list in the car (Android only) -SUB/WAVE lists in Android Auto as a media app: the saved stations, tap one to tune -in, then Auto's own Now Playing screen with play and pause. "Hey Google, play -Night Shift on SUB/WAVE" tunes in by name. +SUB/WAVE lists in Android Auto as a media app: a Stations tab of the saved +stations, tap one to tune in, then Auto's own Now Playing screen with play and +pause. "Hey Google, play Night Shift on SUB/WAVE" tunes in by name. > **Play history.** A manifest-only declaration (#444) was **enforced against by > Google Play** (20 Jun 2026): *media apps that use a TTS engine to read out > content aren't permitted*, which is what the AI DJ does, and #477 removed it. -> This is a second attempt, now with a real browse tree. If Play enforces again, -> remove `modules/android-auto` from the build rather than shipping around it. +> This is a second attempt, now with a real browse tree, **behind a build flag** +> so the Play build can ship without it. A browse tree doesn't answer that +> policy: the review notes do (`docs/RELEASE.md` → Android Auto has the plan). + +**Off unless `SUBWAVE_ANDROID_AUTO=1` is set at prebuild** (`plugins/withAndroidAuto.js`). +The module's own manifest declares nothing; the plugin adds `SubwaveBrowseService` +with its `android.media.browse.MediaBrowserService` intent filter, the +`com.google.android.gms.car.application` meta-data and +`res/xml/subwave_automotive_app_desc.xml`. Unset, or any other value, the merged +manifest has none of it, so Android Auto never lists the app, and +`scripts/android-auto-plugin.test.ts` checks both states. The Kotlin, the RNTP +patch and the JS ship in every Android build either way, and do nothing without +the service: nothing binds to browse, so the car-connect task never runs and +the background-setup bypass never switches on. `eas.json`'s `production-auto` +(Play closed testing) and `apk` (sideload) profiles set it; `production` doesn't. The pieces, all in a new binary (none of it reaches a phone over the air): -- **`modules/android-auto`** declares the car app (`subwave_automotive_app_desc.xml` - and the `com.google.android.gms.car.application` meta-data, merged from the - module's manifest) and `SubwaveBrowseService`, a `MediaBrowserServiceCompat`. - It lists the stations JS mirrors into SharedPreferences (`setStations`, from - StationContext beside the Siri mirror), names and bases only. +- **`modules/android-auto`** holds `SubwaveBrowseService`, a + `MediaBrowserServiceCompat`. It lists the stations JS mirrors into + SharedPreferences (`setStations`, from StationContext beside the Siri mirror), + names and bases only, the one listened to last first. +- **The browse tree is one browsable Stations tab.** Google's root hints default + to browsable-only root children, at most four, shown as tabs, and Android + Automotive must be assumed to need that. A caller whose hints allow only + playable root children gets the stations at its root instead (`rootFor`). + With no station saved, the tab holds one item that is neither browsable nor + playable: *No stations yet — When it's safe, add one in SUB/WAVE on your + phone*. The strings are in `res/values/subwave_android_auto.xml`. - **The browse session is the player's own.** The RNTP patch's `MediaBrowserBridge` hands the service KotlinAudio's session token, and gives the session a `PlaybackPreparer`: Auto's play-from-id and voice search become @@ -350,6 +371,18 @@ The pieces, all in a new binary (none of it reaches a phone over the air): it, and so to StreamRecovery, and a pick of another station switches through it; only with none mounted does it load the stream itself. Play on an idle player still takes the connector's own path (`onPrepare` just prepares). +- **A failed pick shows the car why** (`src/intents/car-errors.ts`). The bridge's + `showError` calls ExoPlayer's `MediaSessionConnector.setCustomErrorMessage`, + which puts the session in `STATE_ERROR` with the message, and Auto shows it in + place of Now Playing. `tune-flow.ts` replies carry a `reason` (the Swift bridge + reads only `ok` and `message`): *not-saved* and *no-station* send the driver to + the phone "when it's safe" (Google's guideline VI-1); a stream that never + started is *locked* when the station needs a password none is saved for (one + `/state` read through `readJson`, never a stream probe, `activeStationLocked`), + else *unreachable*. The kinds map to `PlaybackStateCompat` error codes in + `SubwaveAndroidAutoModule.kt` (`npm test` checks the two lists match). The next + pick clears it, and so does audio playing (the bridge listens for it); only the + latest pick's failure is ever shown. - **The car can launch the app with no screen.** The session exists only once JS has set the player up, so the first connection starts React Native and runs the `SubwaveCarConnect` headless task (`src/intents/car.ts`), which calls @@ -357,44 +390,109 @@ The pieces, all in a new binary (none of it reaches a phone over the air): `setupPlayer` with no activity in front; the patch lets it through while a media browser is bound (Android allows the foreground service then), and turns a refused start into a rejection instead of a crash. +- **A cold start that never gets a session fails in 8 s, not never.** If no + token arrives within `CONNECT_TIMEOUT_MS`, or the car-connect task reports + that `setupPlayer` rejected (`carSetupFailed`), the service hands the car a + session of its own whose only state is the error *SUB/WAVE couldn't start. + When it's safe, open SUB/WAVE on your phone.*, and `CarConnectTask.reset()` + drops the pending React Native start so the next connection starts over. That + instance can't take the player's session afterwards; if the player comes up + late it releases the error session so the car reconnects to a fresh one. - **System UI's resumption query is refused** (`EXTRA_RECENT` → no root): it would otherwise start the app in the background on every boot. - **Only the car, the Assistant and the system get a root** (`CarCallers`, after Google's media sample): this app, the system UID, a platform-signed caller or one holding `MEDIA_CONTENT_CONTROL`, or Android Auto, Automotive's - media centre or the Google app when the package owns the calling UID and is a - system app or installed by Play. Any other app gets no root, so it can't read - the saved stations or start the player in the background. + media centre, the Google app or the Gemini app when the package owns the + calling UID and is a system app or installed by Play. Gemini's package + (`com.google.android.apps.bard`) is unconfirmed as the one that binds in the + car: check logcat on the Desktop Head Unit. Google's Media Controller Test app + (`com.example.android.mediacontroller`) passes in a debuggable build only. Any + other app gets no root, so it can't read the saved stations or start the + player in the background. - **A session token is taken once.** `MediaBrowserServiceCompat` accepts one, so the bridge clears its token when `MusicService` is destroyed, and a browse service still holding the dead one answers no root until its clients unbind; the car's next bind gets a fresh service that waits for the next session. + In practice that is rare: swiping the app away runs RNTP's `onTaskRemoved`, + which ends the process (`exitProcess`), so the car rebinds to a new one; and a + JS reload keeps the same `MusicService` and session. A destroyed + `MusicService` in a live process is left as it was: the car recovers on its + next connection, since no API can hand a bound client a second token. - **A prepare doesn't play.** A pick with `playWhenReady` false (the Assistant's prepare-then-play) is held in JS (`src/intents/car-picks.ts`) and the next Play tunes in to it; pause or stop drops it. A refused or failed - pick is a line in the playback log. + pick is a line in the playback log, as is the error the car was shown. - **A spoken name that matches nothing plays the station listened to last**, as Siri does: a generic word ("play radio") names no station. -Testing needs the Android Auto app on a phone and Google's **Desktop Head Unit** -(SDK Manager → SDK Tools → Android Auto Desktop Head Unit Emulator). In Android -Auto's settings tap the version 10 times for developer mode, then ⋮ → **Start head -unit server**; `adb forward tcp:5277 tcp:5277` and run `desktop-head-unit`. Check: -the list shows each saved station with its host; a tap plays and opens Now -Playing, with the DJ's title and artwork; play and pause work; adding a station on -the phone updates the list; "play " by voice switches station. Then -cold: force-stop the app, connect, pick a station (it must play), then open the -phone app (it must show the same playback). With the phone app open, pick -another station in the car, then the playing one again: the playback log shows -`intent station switch: handed to the player` and `intent tune-in: handed to -the player`, never a direct load. Then the session restart: with the -car connected, swipe the app away (or reload JS in a dev build), reconnect, and -pick a station; it must play, not show a dead session. `adb shell dumpsys -media_session` should list one SUB/WAVE session. Finally a **release build** -(`eas build --profile preview` or `./gradlew :app:assembleRelease`): the bridge -reads KotlinAudio's fields by reflection, so only R8's output proves the keep -rules still pin them, and the car's list, a pick and play/pause must all work -there too. +#### Testing on a phone with the Desktop Head Unit + +You need the Android Auto app on a phone, signed in to Play, and Google's +**Desktop Head Unit** (DHU). Install it from Android Studio → Settings → +Languages & Frameworks → Android SDK → SDK Tools → *Android Auto Desktop Head +Unit Emulator*, or `sdkmanager "extras;google;auto"`. It lands in +`~/Library/Android/sdk/extras/google/auto/`. In Android Auto's settings tap +*Version and permission info* 10 times for developer mode, then ⋮ → **Start +head unit server** (and check *Add new cars to Android Auto* is on). Then: + +```bash +export JAVA_HOME=/opt/homebrew/opt/openjdk@17 +SUBWAVE_ANDROID_AUTO=1 npx expo prebuild -p android --clean +npx expo run:android --device +adb forward tcp:5277 tcp:5277 +~/Library/Android/sdk/extras/google/auto/desktop-head-unit # or --usb +adb logcat | grep -iE "SubwaveBrowse|MediaBrowser|gearhead|TrackPlayer|ForegroundService" +``` + +In the DHU console, `mic begin` (or M) takes a voice command, `day` / `night` +switch themes, `restrict all` turns on driving restrictions. Check: + +- The root shows one Stations tab; in it each saved station with its host, + the one listened to last first. Adding a station on the phone updates it. +- A tap plays and opens Now Playing, with the DJ's title and artwork; play and + pause work; "play " by voice switches station; "play SUB/WAVE" + with no name plays the last station. +- **Gemini:** ask Gemini to play a station and note which package binds in + logcat (`onGetRoot` / `CarCallers`); if it isn't `com.google.android.apps.bard`, + fix `CarCallers.GOOGLE_CALLERS`. +- **Errors:** pick a station on a dead stream (stop its controller) → *Couldn't + reach … Try again in a moment.*; a private station with no saved password → *… + needs its password. When it's safe, unlock it…*; ask by voice with no station + saved → *No station yet…*. Each clears on the next pick and when audio plays. + `adb shell dumpsys media_session` shows the SUB/WAVE session's state as 7 + (`STATE_ERROR`) with the message while one shows. +- **Empty state:** `adb shell pm clear com.getsubwave.app`, connect: the + Stations tab shows *No stations yet*, and a tap does nothing. +- **Cold start:** force-stop the app (`adb shell am force-stop com.getsubwave.app`), + connect, pick a station (it must play), then open the phone app (it must show + the same playback). If the car shows *SUB/WAVE couldn't start*, the log says + why (`car setup failed: …`, or nothing: the 8 s timeout): that is the + background-start refusal this design was worried about. +- **Mounted player:** with the phone app open, pick another station in the car, + then the playing one again: the playback log shows `intent station switch: + handed to the player` and `intent tune-in: handed to the player`, never a + direct load. +- **Session restart:** with the car connected, swipe the app away (the process + exits), reconnect if the car doesn't, and pick a station; it must play, not + show a dead session. Reload JS in a dev build too: the session stays and the + car keeps working. `adb shell dumpsys media_session` should list one SUB/WAVE + session. +- **Media Controller Test:** in a debug build it gets a root and can browse and + play; in a release build it gets none. +- **Flag off:** `npx expo prebuild -p android --clean` without the variable, then + install: SUB/WAVE must not appear in the car at all, and the merged manifest + (`android/app/build/intermediates/merged_manifests/debug/processDebugManifest/AndroidManifest.xml`) + has no `SubwaveBrowseService` or `gms.car.application`. +- Finally a **release build** (`eas build --profile apk` or + `SUBWAVE_ANDROID_AUTO=1 npx expo prebuild -p android --clean && (cd android && + ./gradlew :app:assembleRelease)`): the bridge reads KotlinAudio's fields by + reflection, so only R8's output proves the keep rules still pin them, and the + car's list, a pick, play/pause and an error message must all work there too. + +An Android emulator works only with a Google Play system image (Android Auto +comes from Play), e.g. `sdkmanager "system-images;android-35;google_apis_playstore;arm64-v8a"`, +then the same Android Auto steps inside it; it is less reliable than a phone. ### iPad — every orientation, Split View, Stage Manager diff --git a/eas.json b/eas.json index b229767..dc118c5 100644 --- a/eas.json +++ b/eas.json @@ -34,6 +34,22 @@ "ios": { "image": "macos-tahoe-26.6-xcode-27.1" } + }, + "production-auto": { + "extends": "production", + "env": { + "SUBWAVE_ANDROID_AUTO": "1" + } + }, + "apk": { + "extends": "production", + "distribution": "internal", + "android": { + "buildType": "apk" + }, + "env": { + "SUBWAVE_ANDROID_AUTO": "1" + } } }, "submit": { @@ -47,6 +63,13 @@ "track": "internal", "releaseStatus": "draft" } + }, + "production-auto": { + "android": { + "serviceAccountKeyPath": "./secrets/play-service-account.json", + "track": "alpha", + "releaseStatus": "draft" + } } } } diff --git a/modules/android-auto/android/src/main/AndroidManifest.xml b/modules/android-auto/android/src/main/AndroidManifest.xml index a9a92ed..b82c8bc 100644 --- a/modules/android-auto/android/src/main/AndroidManifest.xml +++ b/modules/android-auto/android/src/main/AndroidManifest.xml @@ -1,16 +1,4 @@ - - - - - - - - - - - - + + diff --git a/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarCallers.kt b/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarCallers.kt index a47e970..4d76bc5 100644 --- a/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarCallers.kt +++ b/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarCallers.kt @@ -13,6 +13,8 @@ import android.os.Process * gets no root. The service is exported, so without this any app could read * the saved stations' hosts and start the player in the background. * + * Google's Media Controller Test app passes too, in a debug build only. + * * Follows Google's media sample (UAMP's PackageValidator): this app, the * system UID, a platform-signed caller or one holding MEDIA_CONTENT_CONTROL * pass. For the Google apps, UAMP pins signing certificates; here a known @@ -26,7 +28,14 @@ internal object CarCallers { "com.google.android.carassistant", // Assistant on Android Automotive "com.android.car.media", // Android Automotive's media centre "com.google.android.googlequicksearchbox", // Google app, Assistant + // Gemini (guideline VC-1). Unconfirmed as the package that binds in the + // car: check logcat on the Desktop Head Unit (docs/TESTING.md). + "com.google.android.apps.bard", ) + + // Google's Media Controller Test app (github.com/googlesamples/android-media-controller), + // sideloaded for testing: debug builds only. + private const val MEDIA_CONTROLLER_TEST = "com.example.android.mediacontroller" private const val PLAY_STORE = "com.android.vending" fun allowed(context: Context, packageName: String, uid: Int): Boolean { @@ -38,9 +47,14 @@ internal object CarCallers { if (pm.checkPermission(Manifest.permission.MEDIA_CONTENT_CONTROL, packageName) == PackageManager.PERMISSION_GRANTED ) return true + if (packageName == MEDIA_CONTROLLER_TEST) return isDebuggable(context) return packageName in GOOGLE_CALLERS && (isSystemApp(pm, packageName) || fromPlay(pm, packageName)) } + // This app's own build, not the library's: a release build never passes. + private fun isDebuggable(context: Context): Boolean = + (context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0 + private fun isSystemApp(pm: PackageManager, packageName: String): Boolean = try { val flags = pm.getApplicationInfo(packageName, 0).flags (flags and (ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0 diff --git a/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarConnectTask.kt b/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarConnectTask.kt index 150ccf5..ef3380e 100644 --- a/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarConnectTask.kt +++ b/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarConnectTask.kt @@ -3,6 +3,7 @@ package com.getsubwave.androidauto import android.app.Application import androidx.annotation.MainThread import com.facebook.react.ReactApplication +import com.facebook.react.ReactHost import com.facebook.react.ReactInstanceEventListener import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.ReactContext @@ -20,7 +21,8 @@ internal object CarConnectTask { private const val TASK = "SubwaveCarConnect" private const val TIMEOUT_MS = 30_000L - private var starting = false + // The listener waiting on React Native, while it starts. + private var waiting: Pair? = null @MainThread fun run(app: Application) { @@ -29,20 +31,30 @@ internal object CarConnectTask { start(it) return } - if (starting) return - starting = true - host.addReactInstanceEventListener(object : ReactInstanceEventListener { + if (waiting != null) return + val listener = object : ReactInstanceEventListener { override fun onReactContextInitialized(context: ReactContext) { host.removeReactInstanceEventListener(this) UiThreadUtil.runOnUiThread { - starting = false + if (waiting?.second !== this) return@runOnUiThread + waiting = null start(context) } } - }) + } + waiting = host to listener + host.addReactInstanceEventListener(listener) host.start() } + /** The car gave up waiting (SubwaveBrowseService.connectFailed): the next + * connection starts over, rather than finding a start still pending. */ + @MainThread + fun reset() { + waiting?.let { (host, listener) -> host.removeReactInstanceEventListener(listener) } + waiting = null + } + private fun start(context: ReactContext) { HeadlessJsTaskContext.getInstance(context) .startTask(HeadlessJsTaskConfig(TASK, Arguments.createMap(), TIMEOUT_MS, true)) diff --git a/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarStations.kt b/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarStations.kt index 3ff05a0..0dff2ef 100644 --- a/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarStations.kt +++ b/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarStations.kt @@ -32,15 +32,23 @@ internal object CarStations { context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, json).apply() } + /** The saved stations, the one listened to last first. */ fun load(context: Context): List { val json = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return emptyList() return runCatching { - val stations = JSONObject(json).getJSONArray("stations") - (0 until stations.length()).map { + val root = JSONObject(json) + val active = root.optString("active").takeIf { !root.isNull("active") && it.isNotEmpty() } + val stations = root.getJSONArray("stations") + val list = (0 until stations.length()).map { val station = stations.getJSONObject(it) CarStation(station.getString("id"), station.getString("name")) } + activeFirst(list, active) }.getOrDefault(emptyList()) } + + // A stable sort: the rest keep the order JS gave them (most recent first). + fun activeFirst(stations: List, active: String?): List = + if (active == null) stations else stations.sortedBy { if (it.id == active) 0 else 1 } } diff --git a/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/SubwaveAndroidAutoModule.kt b/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/SubwaveAndroidAutoModule.kt index bead49d..8ea3183 100644 --- a/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/SubwaveAndroidAutoModule.kt +++ b/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/SubwaveAndroidAutoModule.kt @@ -1,11 +1,17 @@ package com.getsubwave.androidauto +import android.os.Handler +import android.os.Looper +import android.support.v4.media.session.PlaybackStateCompat +import com.doublesymmetry.trackplayer.service.MediaBrowserBridge import expo.modules.kotlin.modules.Module import expo.modules.kotlin.modules.ModuleDefinition // The JS half is modules/android-auto/index.ts; the car's side is // SubwaveBrowseService. class SubwaveAndroidAutoModule : Module() { + private val main = Handler(Looper.getMainLooper()) + override fun definition() = ModuleDefinition { Name("SubwaveAndroidAuto") @@ -16,5 +22,29 @@ class SubwaveAndroidAutoModule : Module() { CarStations.save(context, json) SubwaveBrowseService.stationsChanged() } + + /** Why a car pick failed, shown in place of Now Playing until the next + * pick or until audio plays. `kind` is CarErrorKind in + * src/intents/car-errors.ts (npm test checks the two match). */ + Function("showError") { kind: String, message: String -> + val code = errorCode(kind) + main.post { MediaBrowserBridge.showError(message, code) } + } + + Function("clearError") { + main.post { MediaBrowserBridge.clearError() } + } + + /** setupPlayer failed in the car-connect task (src/intents/car.ts). */ + Function("setupFailed") { + SubwaveBrowseService.setupFailed() + } + } + + private fun errorCode(kind: String): Int = when (kind) { + "locked" -> PlaybackStateCompat.ERROR_CODE_AUTHENTICATION_EXPIRED + "not-saved", "no-station" -> PlaybackStateCompat.ERROR_CODE_NOT_SUPPORTED + "unreachable" -> PlaybackStateCompat.ERROR_CODE_APP_ERROR + else -> PlaybackStateCompat.ERROR_CODE_UNKNOWN_ERROR } } diff --git a/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/SubwaveBrowseService.kt b/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/SubwaveBrowseService.kt index 69e6004..9e26a1e 100644 --- a/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/SubwaveBrowseService.kt +++ b/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/SubwaveBrowseService.kt @@ -1,36 +1,57 @@ package com.getsubwave.androidauto import android.os.Bundle +import android.os.Handler +import android.os.Looper import android.support.v4.media.MediaBrowserCompat.MediaItem +import android.support.v4.media.MediaDescriptionCompat import android.support.v4.media.session.MediaSessionCompat +import android.support.v4.media.session.PlaybackStateCompat import androidx.media.MediaBrowserServiceCompat +import androidx.media.utils.MediaConstants import com.doublesymmetry.trackplayer.service.MediaBrowserBridge /** - * Android Auto's view of SUB/WAVE: the saved stations, each one playable. + * Android Auto's view of SUB/WAVE: one Stations tab holding the saved + * stations, the one listened to last first, each one playable. * * Kotlin lists, JS plays. The browse session is the player's own * (react-native-track-player), so the car's Now Playing screen, play and pause * work as they do on the lock screen. A tap on a station reaches that session, * which the RNTP patch (MediaBrowserBridge) turns into a remote-play-id event; - * service.ts answers it with the tune-in Siri uses (src/intents/tune.ts). + * service.ts answers it with the tune-in Siri uses (src/intents/tune.ts), and + * a pick that fails shows the car why (src/intents/car-errors.ts). * * The car can bind this with the app not running, and the player's session * only exists once JS has set the player up. So the first connection starts * React Native and runs the car-connect task (CarConnectTask), and the car's - * connection completes when the session token arrives. + * connection completes when the session token arrives. If it hasn't within + * CONNECT_TIMEOUT_MS, or JS says setupPlayer failed, the car gets a session of + * this service's own that shows only an error, instead of waiting forever. * * MediaBrowserServiceCompat takes a session token once, so an instance whose * session ended (its MusicService was destroyed) can't take the next one. It * stops answering instead: once its clients unbind it is destroyed, and the - * car's next bind creates an instance that waits for the new session. + * car's next bind creates an instance that waits for the new session. The + * same goes for an instance that gave the car the error session. */ class SubwaveBrowseService : MediaBrowserServiceCompat() { private var sessionEnded = false + private var errorSession: MediaSessionCompat? = null + private val handler = Handler(Looper.getMainLooper()) + private val connectTimeout = Runnable { connectFailed() } private val session = object : MediaBrowserBridge.SessionListener { override fun ready(token: MediaSessionCompat.Token) { - if (sessionToken == null) sessionToken = token + handler.removeCallbacks(connectTimeout) + if (sessionToken == null) { + sessionToken = token + } else if (errorSession != null) { + // The player came up after the car was shown the error. Ending the + // error session tells the car this one is gone, so that it reconnects; + // a fresh instance then takes the player's session. + releaseErrorSession() + } } override fun ended() { @@ -45,7 +66,9 @@ class SubwaveBrowseService : MediaBrowserServiceCompat() { } override fun onDestroy() { + handler.removeCallbacks(connectTimeout) MediaBrowserBridge.removeListener(session) + releaseErrorSession() current = null MediaBrowserBridge.browsing = false super.onDestroy() @@ -62,30 +85,134 @@ class SubwaveBrowseService : MediaBrowserServiceCompat() { // This instance holds a released session's token and can't take another. if (sessionEnded) return null MediaBrowserBridge.browsing = true - if (sessionToken == null) CarConnectTask.run(application) - return BrowserRoot(ROOT, ROOT_EXTRAS) + if (sessionToken == null) { + CarConnectTask.run(application) + handler.removeCallbacks(connectTimeout) + handler.postDelayed(connectTimeout, CONNECT_TIMEOUT_MS) + } + return BrowserRoot(rootFor(rootHints), ROOT_EXTRAS) } override fun onLoadChildren(parentId: String, result: Result>) { - val items = if (parentId == ROOT) CarStations.load(this).map { it.toMediaItem() } else emptyList() + val items: List = when (parentId) { + ROOT_TABS -> listOf(stationsTab()) + STATIONS, ROOT_FLAT -> stationItems() + else -> emptyList() + } result.sendResult(items.toMutableList()) } + /** The player's session never came: setupPlayer was refused or React + * Native didn't start. The car shows why rather than a spinner. */ + internal fun connectFailed() { + handler.removeCallbacks(connectTimeout) + CarConnectTask.reset() + if (sessionToken != null) return + val error = MediaSessionCompat(this, "SubwaveCarError").apply { + setPlaybackState( + PlaybackStateCompat.Builder() + .setState(PlaybackStateCompat.STATE_ERROR, 0L, 0f) + .setErrorMessage( + PlaybackStateCompat.ERROR_CODE_APP_ERROR, + getString(R.string.subwave_car_start_failed), + ) + .build(), + ) + isActive = true + } + errorSession = error + sessionToken = error.sessionToken + // This instance can't take the player's session any more. + sessionEnded = true + } + + private fun releaseErrorSession() { + errorSession?.run { + isActive = false + release() + } + errorSession = null + } + + private fun stationsTab(): MediaItem { + val description = MediaDescriptionCompat.Builder() + .setMediaId(STATIONS) + .setTitle(getString(R.string.subwave_car_stations)) + .setExtras(LIST_STYLE) + .build() + return MediaItem(description, MediaItem.FLAG_BROWSABLE) + } + + private fun stationItems(): List { + val stations = CarStations.load(this) + if (stations.isNotEmpty()) return stations.map { it.toMediaItem() } + // Neither browsable nor playable: a line of text, nothing to tap into. + val description = MediaDescriptionCompat.Builder() + .setMediaId(EMPTY) + .setTitle(getString(R.string.subwave_car_empty_title)) + .setSubtitle(getString(R.string.subwave_car_empty_subtitle)) + .build() + return listOf(MediaItem(description, 0)) + } + companion object { - private const val ROOT = "subwave-root" + private const val CONNECT_TIMEOUT_MS = 8_000L + + // Tabs: the root holds only the Stations tab. Android Auto and Automotive + // show only browsable root children, as tabs, unless the car's root hints + // say playable ones are supported. + private const val ROOT_TABS = "subwave-root" + // A car whose hints allow only playable root children: the stations there. + private const val ROOT_FLAT = "subwave-stations-root" + private const val STATIONS = "subwave-stations" + private const val EMPTY = "subwave-no-stations" + + private val LIST_STYLE = Bundle().apply { + putInt( + MediaConstants.DESCRIPTION_EXTRAS_KEY_CONTENT_STYLE_PLAYABLE, + MediaConstants.DESCRIPTION_EXTRAS_VALUE_CONTENT_STYLE_LIST_ITEM, + ) + } // Stations as a list, not a grid of tiles. private val ROOT_EXTRAS = Bundle().apply { putBoolean("android.media.browse.CONTENT_STYLE_SUPPORTED", true) - putInt("android.media.browse.CONTENT_STYLE_PLAYABLE_HINT", 1) + putInt( + MediaConstants.DESCRIPTION_EXTRAS_KEY_CONTENT_STYLE_PLAYABLE, + MediaConstants.DESCRIPTION_EXTRAS_VALUE_CONTENT_STYLE_LIST_ITEM, + ) + } + + /** The Stations tab, unless the caller can show only playable items at + * its root. No hints means Google's defaults: browsable only. */ + internal fun rootFor(hints: Bundle?): String { + val flags = hints?.getInt( + MediaConstants.BROWSER_ROOT_HINTS_KEY_ROOT_CHILDREN_SUPPORTED_FLAGS, + MediaItem.FLAG_BROWSABLE, + ) ?: MediaItem.FLAG_BROWSABLE + val browsable = (flags and MediaItem.FLAG_BROWSABLE) != 0 + val playable = (flags and MediaItem.FLAG_PLAYABLE) != 0 + return if (!browsable && playable) ROOT_FLAT else ROOT_TABS } @Volatile private var current: SubwaveBrowseService? = null + private val main = Handler(Looper.getMainLooper()) + /** Redraws the car's list, when the car is connected. */ fun stationsChanged() { - current?.notifyChildrenChanged(ROOT) + main.post { + current?.run { + notifyChildrenChanged(STATIONS) + notifyChildrenChanged(ROOT_FLAT) + } + } + } + + /** JS couldn't set the player up for the car (src/intents/car.ts). */ + fun setupFailed() { + main.post { current?.connectFailed() } } } } diff --git a/modules/android-auto/android/src/main/res/values/subwave_android_auto.xml b/modules/android-auto/android/src/main/res/values/subwave_android_auto.xml new file mode 100644 index 0000000..c596cdd --- /dev/null +++ b/modules/android-auto/android/src/main/res/values/subwave_android_auto.xml @@ -0,0 +1,9 @@ + + + + Stations + No stations yet + When it\'s safe, add one in SUB/WAVE on your phone + SUB/WAVE couldn\'t start. When it\'s safe, open SUB/WAVE on your phone. + diff --git a/modules/android-auto/android/src/main/res/xml/subwave_automotive_app_desc.xml b/modules/android-auto/android/src/main/res/xml/subwave_automotive_app_desc.xml deleted file mode 100644 index b4a189f..0000000 --- a/modules/android-auto/android/src/main/res/xml/subwave_automotive_app_desc.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/modules/android-auto/index.ts b/modules/android-auto/index.ts index 0399b51..fc36ba1 100644 --- a/modules/android-auto/index.ts +++ b/modules/android-auto/index.ts @@ -7,6 +7,10 @@ import type { MirroredStation } from '@/lib/station-store'; interface NativeAndroidAuto { setStations(json: string): void; + // Absent from binaries before car error states. + showError?(kind: string, message: string): void; + clearError?(): void; + setupFailed?(): void; } // Binaries older than Android Auto support lack this module, and an OTA @@ -29,3 +33,31 @@ export function setStations(active: string | null, stations: MirroredStation[]): /* a binary older than Android Auto support */ } } + +/** Why a car pick failed, in place of Now Playing (src/intents/car-errors.ts), + * until the next pick or until audio plays. */ +export function showCarError(kind: string, message: string): void { + try { + native?.showError?.(kind, message); + } catch { + /* no session to show it on */ + } +} + +export function clearCarError(): void { + try { + native?.clearError?.(); + } catch { + /* no session */ + } +} + +/** setupPlayer failed for a car that is waiting on the player's session: the + * car shows an error instead of waiting. */ +export function carSetupFailed(): void { + try { + native?.setupFailed?.(); + } catch { + /* a binary older than car error states */ + } +} diff --git a/patches/react-native-track-player+4.1.2.patch b/patches/react-native-track-player+4.1.2.patch index b705557..f72d7e2 100644 --- a/patches/react-native-track-player+4.1.2.patch +++ b/patches/react-native-track-player+4.1.2.patch @@ -521,10 +521,10 @@ index b2409a0..38187bc 100644 } diff --git a/node_modules/react-native-track-player/android/src/main/java/com/doublesymmetry/trackplayer/service/MediaBrowserBridge.kt b/node_modules/react-native-track-player/android/src/main/java/com/doublesymmetry/trackplayer/service/MediaBrowserBridge.kt new file mode 100644 -index 0000000..e222c94 +index 0000000..d9788c4 --- /dev/null +++ b/node_modules/react-native-track-player/android/src/main/java/com/doublesymmetry/trackplayer/service/MediaBrowserBridge.kt -@@ -0,0 +1,117 @@ +@@ -0,0 +1,152 @@ +package com.doublesymmetry.trackplayer.service + +import android.net.Uri @@ -542,7 +542,8 @@ index 0000000..e222c94 + * Android Auto. The app's own MediaBrowserService lists what can be played; + * this hands it the player's session and turns the car's "play this item" and + * voice searches into the remote-play-id and remote-play-search events, which -+ * RNTP 4.1.2 declares but never fires. (patched — patch-package) ++ * RNTP 4.1.2 declares but never fires, and shows the car why a pick failed ++ * (showError). (patched — patch-package) + */ +object MediaBrowserBridge { + /** True while a media browser is bound. Lets setupPlayer run with no @@ -561,8 +562,17 @@ index 0000000..e222c94 + } + + private var token: MediaSessionCompat.Token? = null ++ private var connector: MediaSessionConnector? = null ++ private var errorShown = false + private val listeners = mutableSetOf() + ++ // Audio playing again is the answer to any error the car was shown. ++ private val clearOnPlay = object : Player.Listener { ++ override fun onIsPlayingChanged(isPlaying: Boolean) { ++ if (isPlaying) clearError() ++ } ++ } ++ + /** Calls [listener] with the player's session token now, or once setupPlayer + * has created the player, and again for each session after it. */ + @MainThread @@ -584,6 +594,8 @@ index 0000000..e222c94 + val connector = field(manager, "mediaSessionConnector") as MediaSessionConnector + val player = field(manager, "player") as Player + connector.setPlaybackPreparer(Preparer(player, emit)) ++ player.addListener(clearOnPlay) ++ this.connector = connector + val session = connector.mediaSession.sessionToken + token = session + listeners.toList().forEach { it.ready(session) } @@ -593,11 +605,34 @@ index 0000000..e222c94 + * after this waits for the next setupPlayer instead of taking a dead token. */ + @MainThread + internal fun detach() { ++ connector = null ++ errorShown = false + if (token == null) return + token = null + listeners.toList().forEach { it.ended() } + } + ++ /** Puts the session in STATE_ERROR with [message], which Android Auto ++ * shows in place of Now Playing; [code] is a PlaybackStateCompat ++ * ERROR_CODE_*. Kept until [clearError] or the next time audio plays. ++ * False when there is no session to show it on. */ ++ @MainThread ++ @JvmStatic ++ fun showError(message: CharSequence, code: Int): Boolean { ++ val connector = connector ?: return false ++ connector.setCustomErrorMessage(message, code) ++ errorShown = true ++ return true ++ } ++ ++ @MainThread ++ @JvmStatic ++ fun clearError() { ++ if (!errorShown) return ++ errorShown = false ++ connector?.setCustomErrorMessage(null) ++ } ++ + private fun field(manager: NotificationManager, name: String): Any = + NotificationManager::class.java.getDeclaredField(name).let { + it.isAccessible = true diff --git a/plugins/withAndroidAuto.js b/plugins/withAndroidAuto.js new file mode 100644 index 0000000..8a8881b --- /dev/null +++ b/plugins/withAndroidAuto.js @@ -0,0 +1,91 @@ +// Expo config plugin: Android Auto, behind SUBWAVE_ANDROID_AUTO=1. +// +// The car's side is modules/android-auto (SubwaveBrowseService and friends). +// That module's own manifest declares nothing, so its classes are compiled +// into every Android build but reachable only once this plugin declares them: +// +// 1. SubwaveBrowseService, exported, with the +// android.media.browse.MediaBrowserService intent filter Android Auto +// binds through. +// 2. The com.google.android.gms.car.application meta-data, pointing at +// res/xml/subwave_automotive_app_desc.xml (``), +// which this plugin also writes. +// +// Play enforced against the app's Android Auto listing once (#477), so the +// Play build can ship without it: unset, or any value but 1, and the merged +// manifest declares no Android Auto support at all, and a descriptor left by +// an earlier flagged prebuild is deleted. docs/RELEASE.md has the plan, +// scripts/android-auto-plugin.test.ts checks both states. +// +// Usage in app.json plugins: "./plugins/withAndroidAuto" + +const fs = require('fs'); +const path = require('path'); +const { withAndroidManifest, withDangerousMod } = require('@expo/config-plugins'); + +const SERVICE = 'com.getsubwave.androidauto.SubwaveBrowseService'; +const BROWSE_ACTION = 'android.media.browse.MediaBrowserService'; +const CAR_META = 'com.google.android.gms.car.application'; +const DESC = 'subwave_automotive_app_desc'; +const DESC_XML = ` + + + + +`; + +function androidAutoEnabled() { + return process.env.SUBWAVE_ANDROID_AUTO === '1'; +} + +/** Adds or removes the browse service and the car meta-data on a parsed + * AndroidManifest.xml (as @expo/config-plugins hands it over). */ +function applyAndroidAuto(manifest, enabled) { + const app = manifest.manifest.application?.[0]; + if (!app) throw new Error('withAndroidAuto: the manifest has no .'); + const named = (name) => (entry) => entry.$?.['android:name'] === name; + + app['meta-data'] = (app['meta-data'] ?? []).filter((m) => !named(CAR_META)(m)); + app.service = (app.service ?? []).filter((s) => !named(SERVICE)(s)); + if (enabled) { + app['meta-data'].push({ + $: { 'android:name': CAR_META, 'android:resource': `@xml/${DESC}` }, + }); + app.service.push({ + $: { 'android:name': SERVICE, 'android:exported': 'true' }, + 'intent-filter': [{ action: [{ $: { 'android:name': BROWSE_ACTION } }] }], + }); + } + if (!app['meta-data'].length) delete app['meta-data']; + if (!app.service.length) delete app.service; + return manifest; +} + +/** Writes res/xml/subwave_automotive_app_desc.xml, or deletes it. */ +function writeAutomotiveDescriptor(platformProjectRoot, enabled) { + const file = path.join(platformProjectRoot, 'app/src/main/res/xml', `${DESC}.xml`); + if (enabled) { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, DESC_XML); + } else { + fs.rmSync(file, { force: true }); + } +} + +function withAndroidAuto(config) { + config = withAndroidManifest(config, (cfg) => { + applyAndroidAuto(cfg.modResults, androidAutoEnabled()); + return cfg; + }); + return withDangerousMod(config, [ + 'android', + (cfg) => { + writeAutomotiveDescriptor(cfg.modRequest.platformProjectRoot, androidAutoEnabled()); + return cfg; + }, + ]); +} + +module.exports = withAndroidAuto; +module.exports.applyAndroidAuto = applyAndroidAuto; +module.exports.writeAutomotiveDescriptor = writeAutomotiveDescriptor; diff --git a/scripts/android-auto-plugin.test.ts b/scripts/android-auto-plugin.test.ts new file mode 100644 index 0000000..07228e1 --- /dev/null +++ b/scripts/android-auto-plugin.test.ts @@ -0,0 +1,168 @@ +// plugins/withAndroidAuto.js declares Android Auto only when +// SUBWAVE_ANDROID_AUTO=1 is set at prebuild, because Play enforced against the +// app's car listing once (#477) and the Play build must be able to ship +// without it. Unset, or any other value, the manifest must declare no Android +// Auto support at all: no browse service, no car meta-data, no descriptor. +// +// The plugin's manifest and file mods run here as prebuild calls them, on a +// minimal manifest and a scratch android/ folder. +import assert from 'node:assert/strict'; +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import test, { type TestContext } from 'node:test'; +import type { ExpoConfig } from 'expo/config'; +import withAndroidAuto from '../plugins/withAndroidAuto.js'; + +const ROOT = path.join(import.meta.dirname, '..'); +const SERVICE = 'com.getsubwave.androidauto.SubwaveBrowseService'; +const CAR_META = 'com.google.android.gms.car.application'; + +type Manifest = { manifest: { application?: Record[] } & Record }; +type Mod = (config: Record) => Promise>; + +/** Set or unset SUBWAVE_ANDROID_AUTO for one test. */ +function flag(t: TestContext, value: string | undefined) { + const before = process.env.SUBWAVE_ANDROID_AUTO; + if (value === undefined) delete process.env.SUBWAVE_ANDROID_AUTO; + else process.env.SUBWAVE_ANDROID_AUTO = value; + t.after(() => { + if (before === undefined) delete process.env.SUBWAVE_ANDROID_AUTO; + else process.env.SUBWAVE_ANDROID_AUTO = before; + }); +} + +function emptyManifest(): Manifest { + return { + manifest: { + $: { 'xmlns:android': 'http://schemas.android.com/apk/res/android' }, + application: [ + { + $: { 'android:name': '.MainApplication' }, + activity: [{ $: { 'android:name': '.MainActivity' } }], + }, + ], + }, + }; +} + +/** Runs the plugin's mods: the manifest one on `manifest`, the file one on a + * scratch android/ folder. */ +async function prebuild(t: TestContext, manifest: Manifest = emptyManifest()) { + const android = mkdtempSync(path.join(tmpdir(), 'subwave-auto-')); + t.after(() => rmSync(android, { recursive: true, force: true })); + const config = withAndroidAuto({ + name: 'SUB/WAVE', + slug: 'subwave', + _internal: { projectRoot: ROOT }, + } as ExpoConfig); + const mods = config.mods?.android as Record | undefined; + const request = (modName: string) => ({ + platform: 'android', + modName, + projectRoot: ROOT, + platformProjectRoot: android, + }); + const out = await mods?.manifest?.({ + ...config, + modResults: manifest, + modRequest: request('manifest'), + }); + await mods?.dangerous?.({ ...config, modResults: {}, modRequest: request('dangerous') }); + const desc = path.join(android, 'app/src/main/res/xml/subwave_automotive_app_desc.xml'); + return { manifest: (out?.modResults ?? manifest) as Manifest, android, desc }; +} + +function declared(manifest: Manifest) { + const app = manifest.manifest.application?.[0] ?? {}; + const names = (key: string) => + ((app[key] as { $?: Record }[] | undefined) ?? []).map( + (e) => e.$?.['android:name'], + ); + return { services: names('service'), meta: names('meta-data'), xml: JSON.stringify(manifest) }; +} + +for (const value of [undefined, '', '0', 'true', 'yes', ' 1']) { + test(`SUBWAVE_ANDROID_AUTO=${JSON.stringify(value)} declares no Android Auto support`, async (t) => { + flag(t, value); + const { manifest, desc } = await prebuild(t); + assert.deepEqual(manifest, emptyManifest(), 'the manifest is what it was without the plugin'); + const { xml } = declared(manifest); + for (const needle of [SERVICE, CAR_META, 'MediaBrowserService', 'automotive_app_desc']) { + assert.equal(xml.includes(needle), false, `${needle} in a flag-off manifest`); + } + assert.equal(existsSync(desc), false, 'no automotive descriptor is written'); + }); +} + +test('SUBWAVE_ANDROID_AUTO=1 declares the browse service, the car meta-data and its descriptor', async (t) => { + flag(t, '1'); + const { manifest, desc } = await prebuild(t); + const app = manifest.manifest.application?.[0] as Record; + assert.deepEqual(app.service, [ + { + $: { 'android:name': SERVICE, 'android:exported': 'true' }, + 'intent-filter': [ + { action: [{ $: { 'android:name': 'android.media.browse.MediaBrowserService' } }] }, + ], + }, + ]); + assert.deepEqual(app['meta-data'], [ + { $: { 'android:name': CAR_META, 'android:resource': '@xml/subwave_automotive_app_desc' } }, + ]); + assert.match( + readFileSync(desc, 'utf8'), + /\s*\s*<\/automotiveApp>/, + ); +}); + +test('a second flagged prebuild declares each once, and an unflagged one removes them', async (t) => { + flag(t, '1'); + const once = (await prebuild(t)).manifest; + const twice = (await prebuild(t, once)).manifest; + assert.deepEqual(declared(twice).services, [SERVICE]); + assert.deepEqual(declared(twice).meta, [CAR_META]); + + process.env.SUBWAVE_ANDROID_AUTO = '0'; + const off = await prebuild(t, twice); + assert.deepEqual(off.manifest, emptyManifest()); +}); + +test('a flag-off prebuild deletes the descriptor a flagged one left', async (t) => { + flag(t, '1'); + const on = await prebuild(t); + assert.ok(existsSync(on.desc)); + process.env.SUBWAVE_ANDROID_AUTO = ''; + const { writeAutomotiveDescriptor } = withAndroidAuto as unknown as { + writeAutomotiveDescriptor(root: string, enabled: boolean): void; + }; + writeAutomotiveDescriptor(on.android, false); + assert.equal(existsSync(on.desc), false); +}); + +test("the module's own manifest declares nothing for the car, and app.json runs the plugin", () => { + const module = readFileSync( + path.join(ROOT, 'modules/android-auto/android/src/main/AndroidManifest.xml'), + 'utf8', + ).replace(//g, ''); + for (const needle of ['service', 'meta-data', 'gms.car', 'MediaBrowserService']) { + assert.equal( + module.includes(needle), + false, + `the module manifest declares ${needle}: move it to the plugin`, + ); + } + assert.equal( + existsSync( + path.join( + ROOT, + 'modules/android-auto/android/src/main/res/xml/subwave_automotive_app_desc.xml', + ), + ), + false, + 'the descriptor is written by the plugin, not shipped by the module', + ); + const plugins = JSON.parse(readFileSync(path.join(ROOT, 'app.json'), 'utf8')).expo + .plugins as unknown[]; + assert.ok(plugins.includes('./plugins/withAndroidAuto')); +}); diff --git a/scripts/android-auto.test.ts b/scripts/android-auto.test.ts index ac197f1..a2ef14c 100644 --- a/scripts/android-auto.test.ts +++ b/scripts/android-auto.test.ts @@ -8,7 +8,9 @@ import { readFileSync } from 'node:fs'; import path from 'node:path'; import test from 'node:test'; import type { IntentReply } from '../modules/app-intents/index.ts'; +import { CAR_ERROR_KINDS, carErrorFor } from '../src/intents/car-errors.ts'; import { CAR_PICK_BUDGET_MS, createCarPicks } from '../src/intents/car-picks.ts'; +import type { TuneReply } from '../src/intents/tune-flow.ts'; const ROOT = path.join(import.meta.dirname, '..'); const read = (file: string) => readFileSync(path.join(ROOT, file), 'utf8'); @@ -90,10 +92,165 @@ test('a refused or failed tune-in is logged, never thrown', async () => { await car.pick(pick('search "x"', new Error('load failed')), true); assert.deepEqual(logged, [ "car pick a refused: That station isn't saved", + 'car error shown: unreachable', 'car search "x" failed: load failed', + 'car error shown: unreachable', ]); }); +// The car's error state (src/intents/car-errors.ts). +function screened(locked = false) { + const shown: string[] = []; + const lockChecks: number[] = []; + const logged: string[] = []; + const car = createCarPicks((msg) => logged.push(msg), Date.now, { + show: (e) => shown.push(`${e.kind}: ${e.message}`), + clear: () => shown.push('clear'), + locked: async () => { + lockChecks.push(1); + return locked; + }, + }); + const pick = (reply: TuneReply | Error, tune?: () => Promise) => ({ + label: 'pick', + tune: + tune ?? + (async () => { + if (reply instanceof Error) throw reply; + return reply; + }), + }); + return { car, pick, shown, lockChecks, logged }; +} + +test('each failure shows the car why, and sends it to the phone only when safe', () => { + const unreachable = carErrorFor( + { ok: false, reason: 'unreachable', station: 'Night Shift' }, + false, + ); + assert.deepEqual(unreachable, { + kind: 'unreachable', + message: "Couldn't reach Night Shift. Try again in a moment.", + }); + assert.equal( + carErrorFor({ ok: false, reason: 'unreachable' }, false).message, + "Couldn't reach the station. Try again in a moment.", + ); + assert.deepEqual( + carErrorFor({ ok: false, reason: 'unreachable', station: 'Night Shift' }, true), + { + kind: 'locked', + message: + "Night Shift needs its password. When it's safe, unlock it in SUB/WAVE on your phone.", + }, + ); + assert.equal( + carErrorFor({ ok: false, reason: 'unreachable' }, true).message.startsWith('The station needs'), + true, + ); + assert.equal( + carErrorFor({ ok: false, reason: 'not-saved' }, true).kind, + 'not-saved', + 'locked only reads a failed stream', + ); + assert.equal(carErrorFor({ ok: false, reason: 'no-station' }, false).kind, 'no-station'); + for (const kind of ['not-saved', 'no-station', 'locked'] as const) { + const reason = kind === 'locked' ? 'unreachable' : kind; + const { message } = carErrorFor({ ok: false, reason }, kind === 'locked'); + assert.match( + message, + /When it's safe, .* on your phone\./, + `${kind} sends the driver to the phone safely`, + ); + } +}); + +test('a pick clears the last error first, and a success shows none', async () => { + const { car, pick, shown } = screened(); + await car.pick(pick({ ok: false, reason: 'not-saved' }), true); + await car.pick(pick({ ok: true }), true); + assert.deepEqual(shown, [ + 'clear', + "not-saved: That station isn't saved. When it's safe, add it in SUB/WAVE on your phone.", + 'clear', + ]); +}); + +test('a prepare clears the error too, and its Play reports its own failure', async () => { + const { car, pick, shown } = screened(); + await car.pick(pick({ ok: false, reason: 'no-station' }), false); + assert.deepEqual(shown, ['clear']); + assert.equal(car.playPrepared(), true); + for (let i = 0; i < 10; i++) await Promise.resolve(); + assert.deepEqual(shown, [ + 'clear', + 'clear', + "no-station: No station yet. When it's safe, add one in SUB/WAVE on your phone.", + ]); +}); + +test('only a failed stream asks whether the station is locked', async () => { + const locked = screened(true); + await locked.car.pick( + locked.pick({ ok: false, reason: 'unreachable', station: 'Night Shift' }), + true, + ); + assert.deepEqual( + locked.shown.at(-1), + "locked: Night Shift needs its password. When it's safe, unlock it in SUB/WAVE on your phone.", + ); + assert.equal(locked.lockChecks.length, 1); + + const unsaved = screened(true); + await unsaved.car.pick(unsaved.pick({ ok: false, reason: 'not-saved' }), true); + assert.equal(unsaved.lockChecks.length, 0); +}); + +test('a lock check that fails reads as unreachable', async () => { + const shown: string[] = []; + const car = createCarPicks(() => {}, Date.now, { + show: (e) => shown.push(e.kind), + clear: () => {}, + locked: async () => { + throw new Error('offline'); + }, + }); + await car.pick({ label: 'pick', tune: async () => ({ ok: false, reason: 'unreachable' }) }, true); + assert.deepEqual(shown, ['unreachable']); +}); + +test("an older pick's failure never covers a newer pick", async () => { + const { car, pick, shown } = screened(); + let fail: (reply: TuneReply) => void = () => {}; + const slow = car.pick( + pick({ ok: true }, () => new Promise((resolve) => (fail = resolve))), + true, + ); + await car.pick(pick({ ok: true }), true); + fail({ ok: false, reason: 'unreachable' }); + await slow; + assert.deepEqual(shown, ['clear', 'clear']); +}); + +test('every car error kind has its own error code in Kotlin', () => { + const kotlin = read( + 'modules/android-auto/android/src/main/java/com/getsubwave/androidauto/SubwaveAndroidAutoModule.kt', + ); + const mapped = [ + ...(kotlin.match(/fun errorCode[\s\S]*?\n {2}}/)?.[0] ?? '').matchAll(/"([a-z-]+)"/g), + ].map((m) => m[1]); + assert.deepEqual( + [...mapped].sort(), + [...CAR_ERROR_KINDS].sort(), + 'errorCode and CAR_ERROR_KINDS differ: change both', + ); +}); + +test('the car-connect task tells the car when setupPlayer fails', () => { + const car = read('src/intents/car.ts'); + assert.match(car, /setupPlayer\(\)\.catch\([\s\S]*carSetupFailed\(\)/); +}); + test('the car-connect task has the same name in JS and Kotlin', () => { const js = read('src/intents/car.ts').match(/CAR_CONNECT_TASK = '([^']+)'/)?.[1]; const kotlin = read( diff --git a/scripts/intent-tune.test.ts b/scripts/intent-tune.test.ts index ed1d5b4..4961b62 100644 --- a/scripts/intent-tune.test.ts +++ b/scripts/intent-tune.test.ts @@ -33,8 +33,16 @@ import { tuneInOnArrival, } from '../src/lib/remote-play.ts'; -const NIGHT = { url: 'https://radio.example.com', name: 'Night Shift', lastUsed: 2 }; -const WAVE = { url: 'https://www.getsubwave.com', name: 'SUB/WAVE', lastUsed: 1 }; +const NIGHT = { + url: 'https://radio.example.com', + name: 'Night Shift', + lastUsed: 2, +}; +const WAVE = { + url: 'https://www.getsubwave.com', + name: 'SUB/WAVE', + lastUsed: 1, +}; const DEADLINE = 1_000_000; interface Opts { @@ -175,6 +183,8 @@ test('a stream that never starts is reported, and the control turns off with no const reply = await tuneIn(s.deps, undefined, DEADLINE); assert.equal(reply.ok, false); assert.match(reply.message ?? '', /Night Shift/); + assert.equal(reply.reason, 'unreachable'); + assert.equal(reply.station, 'Night Shift'); assert.deepEqual(s.onAirStates, [false]); }); @@ -183,11 +193,13 @@ test('an unsaved station or no station at all is said, and nothing loads', async assert.deepEqual(await tuneIn(unsaved.deps, 'https://elsewhere.example.com', DEADLINE), { ok: false, message: NOT_SAVED_MESSAGE, + reason: 'not-saved', }); const none = intents({ active: null }); assert.deepEqual(await tuneIn(none.deps, undefined, DEADLINE), { ok: false, message: NO_STATION_MESSAGE, + reason: 'no-station', }); assert.deepEqual([...unsaved.calls, ...none.calls], []); }); @@ -258,7 +270,9 @@ test('within gives the work’s answer, or TIMED_OUT once the wait ends first', test('a station asked for by name tunes in to it, through the mounted player', async () => { const s = intents({ mounted: true, active: WAVE.url }); - assert.deepEqual(await tuneInByName(s.deps, 'night shift', DEADLINE), { ok: true }); + assert.deepEqual(await tuneInByName(s.deps, 'night shift', DEADLINE), { + ok: true, + }); assert.deepEqual(s.calls, ['store Night Shift', `arm ${NIGHT.url}`, 'announce', 'disarm']); }); @@ -280,9 +294,15 @@ test('with no player mounted, a station asked for by name is loaded directly', a // service.ts wires them, never load past the mounted player. function carPicks(s: ReturnType, now: number) { const logged: string[] = []; + const shown: string[] = []; const car = createCarPicks( (line) => logged.push(line), () => now, + { + show: (e) => shown.push(`${e.kind}: ${e.message}`), + clear: () => shown.push('clear'), + locked: async () => false, + }, ); const byId = (id: string) => ({ label: `pick ${id}`, @@ -292,7 +312,7 @@ function carPicks(s: ReturnType, now: number) { label: `search "${query}"`, tune: (deadline: number) => tuneInByName(s.deps, query, deadline), }); - return { car, byId, byName, logged }; + return { car, byId, byName, logged, shown }; } test('car picks go through the mounted player: by id, by voice, and a prepared Play', async () => { @@ -326,5 +346,20 @@ test('a car pick its station refuses is logged with the reason', async () => { await c.car.pick(c.byId('https://unknown.example.com'), true); assert.deepEqual(c.logged, [ `car pick https://unknown.example.com refused: ${NOT_SAVED_MESSAGE}`, + 'car error shown: not-saved', + ]); + assert.deepEqual(c.shown, [ + 'clear', + "not-saved: That station isn't saved. When it's safe, add it in SUB/WAVE on your phone.", + ]); +}); + +test('a car pick whose stream never starts names the station in the car', async () => { + const s = intents({ plays: false }); + const c = carPicks(s, DEADLINE - CAR_PICK_BUDGET_MS); + await c.car.pick(c.byName(''), true); + assert.deepEqual(c.shown, [ + 'clear', + "unreachable: Couldn't reach Night Shift. Try again in a moment.", ]); }); diff --git a/service.ts b/service.ts index 2035b93..bdbbf1f 100644 --- a/service.ts +++ b/service.ts @@ -1,10 +1,11 @@ // This headless service cannot access React state. // Skip and seek are unavailable on a shared live broadcast. import TrackPlayer, { Event } from 'react-native-track-player'; +import { clearCarError, showCarError } from './modules/android-auto'; import { getLastLiveMeta, loadAndPlay } from '@/audio/player'; import { plog } from '@/hooks/usePlayer'; import { createCarPicks } from '@/intents/car-picks'; -import { tuneIn, tuneInByName } from '@/intents/tune'; +import { activeStationLocked, tuneIn, tuneInByName } from '@/intents/tune'; import { remotePlay } from '@/lib/remote-play'; // The RNTP patch adds playWhenReady to these; 4.1.2's types lack it. @@ -13,7 +14,12 @@ interface CarPickFlag { } export async function PlaybackService(): Promise { - const carPicks = createCarPicks(plog); + // A failed pick shows the car why (src/intents/car-errors.ts). + const carPicks = createCarPicks(plog, Date.now, { + show: ({ kind, message }) => showCarError(kind, message), + clear: clearCarError, + locked: activeStationLocked, + }); // RemotePlay reloads with a cache-buster to discard the paused buffer, // through the app's player and its stream recovery while that is mounted diff --git a/src/intents/car-errors.ts b/src/intents/car-errors.ts new file mode 100644 index 0000000..bac44fe --- /dev/null +++ b/src/intents/car-errors.ts @@ -0,0 +1,54 @@ +// What Android Auto shows when a pick fails: the session's error state, in +// place of Now Playing, until the next pick or until audio plays +// (modules/android-auto's showError, the RNTP patch's MediaBrowserBridge). +// +// A driver may be sent to the phone only "when it's safe to do so" (Google's +// car app quality guideline VI-1), so every fix that needs the phone says so. + +import type { TuneReply } from './tune-flow'; + +/** Matched by STRING with SubwaveAndroidAutoModule.kt's errorCode (npm test + * checks), which turns each into a PlaybackStateCompat error code. */ +export const CAR_ERROR_KINDS = ['not-saved', 'no-station', 'locked', 'unreachable'] as const; +export type CarErrorKind = (typeof CAR_ERROR_KINDS)[number]; + +export interface CarError { + kind: CarErrorKind; + message: string; +} + +const SAFE = "When it's safe,"; + +/** The car's error for a refused or failed pick. `locked` is whether the + * station needs a password the app doesn't have, asked only after a stream + * failed to start. */ +export function carErrorFor(reply: TuneReply, locked: boolean): CarError { + const station = reply.station ?? 'the station'; + switch (reply.reason) { + case 'not-saved': + return { + kind: 'not-saved', + message: `That station isn't saved. ${SAFE} add it in SUB/WAVE on your phone.`, + }; + case 'no-station': + return { + kind: 'no-station', + message: `No station yet. ${SAFE} add one in SUB/WAVE on your phone.`, + }; + default: + if (locked) { + return { + kind: 'locked', + message: `${capitalise(station)} needs its password. ${SAFE} unlock it in SUB/WAVE on your phone.`, + }; + } + return { + kind: 'unreachable', + message: `Couldn't reach ${station}. Try again in a moment.`, + }; + } +} + +function capitalise(s: string): string { + return s.charAt(0).toUpperCase() + s.slice(1); +} diff --git a/src/intents/car-picks.ts b/src/intents/car-picks.ts index 4492398..540d2f8 100644 --- a/src/intents/car-picks.ts +++ b/src/intents/car-picks.ts @@ -8,8 +8,13 @@ // // A pick tunes in through src/intents/tune-flow.ts, as Siri does: handed to // the mounted player, and so to StreamRecovery, whenever one is mounted. +// +// A pick that fails shows the car why, in place of Now Playing +// (src/intents/car-errors.ts); the next pick clears it, and so does audio +// playing (the RNTP patch's MediaBrowserBridge). -import type { IntentReply } from '../../modules/app-intents'; +import { carErrorFor, type CarError } from './car-errors'; +import type { TuneReply } from './tune-flow'; /** A car has no Siri reply window to fit: a pick may take as long as a * tune-in waits for audio. */ @@ -19,9 +24,24 @@ export interface CarPick { /** For the playback log: what was picked. */ label: string; /** Tune in, answering by `deadline` (epoch ms). */ - tune(deadline: number): Promise; + tune(deadline: number): Promise; +} + +/** The car's error state (modules/android-auto). */ +export interface CarScreen { + show(error: CarError): void; + clear(): void; + /** Whether the station a failed stream was for needs a password the app + * doesn't have (tune.ts activeStationLocked). */ + locked(): Promise; } +const NO_SCREEN: CarScreen = { + show: () => {}, + clear: () => {}, + locked: async () => false, +}; + export interface CarPicks { /** A pick from the car. Tunes in now, or holds it when only preparing. */ pick(pick: CarPick, playWhenReady: boolean): Promise; @@ -32,21 +52,46 @@ export interface CarPicks { forget(): void; } -export function createCarPicks(log: (msg: string) => void, now: () => number = Date.now): CarPicks { +export function createCarPicks( + log: (msg: string) => void, + now: () => number = Date.now, + screen: CarScreen = NO_SCREEN, +): CarPicks { let prepared: CarPick | null = null; + // Each pick's number: only the latest one's failure reaches the car. + let latest = 0; + + async function show(pick: number, reply: TuneReply): Promise { + const locked = reply.reason === 'unreachable' && (await screen.locked().catch(() => false)); + if (pick !== latest) return; + const error = carErrorFor(reply, locked); + log(`car error shown: ${error.kind}`); + screen.show(error); + } async function run(pick: CarPick): Promise { + const n = latest; try { // From when it runs: a prepared pick may wait a while for its Play. const reply = await pick.tune(now() + CAR_PICK_BUDGET_MS); - if (!reply.ok) log(`car ${pick.label} refused: ${reply.message ?? 'no reason'}`); + if (reply.ok) return; + log(`car ${pick.label} refused: ${reply.message ?? 'no reason'}`); + await show(n, reply); } catch (e) { log(`car ${pick.label} failed: ${e instanceof Error ? e.message : String(e)}`); + await show(n, { ok: false, reason: 'unreachable' }); } } + /** A new pick: the car's last error is old news. */ + function next(): void { + latest += 1; + screen.clear(); + } + return { pick(pick, playWhenReady) { + next(); if (!playWhenReady) { prepared = pick; log(`car ${pick.label} prepared`); @@ -59,6 +104,7 @@ export function createCarPicks(log: (msg: string) => void, now: () => number = D const pick = prepared; if (!pick) return false; prepared = null; + next(); void run(pick); return true; }, diff --git a/src/intents/car.ts b/src/intents/car.ts index a82e480..a039c71 100644 --- a/src/intents/car.ts +++ b/src/intents/car.ts @@ -5,7 +5,9 @@ // station or asking for one by voice then arrives in service.ts. import { AppRegistry, Platform } from 'react-native'; +import { carSetupFailed } from '../../modules/android-auto'; import { setupPlayer } from '@/audio/player'; +import { plog } from '@/hooks/usePlayer'; // Matched by STRING with modules/android-auto/…/CarConnectTask.kt (npm test checks). const CAR_CONNECT_TASK = 'SubwaveCarConnect'; @@ -14,6 +16,15 @@ const CAR_CONNECT_TASK = 'SubwaveCarConnect'; * no screen to mount. */ export function registerCarHandlers(): void { if (Platform.OS !== 'android') return; - // Sets up only. Nothing plays until the listener picks a station. - AppRegistry.registerHeadlessTask(CAR_CONNECT_TASK, () => () => setupPlayer()); + // Sets up only. Nothing plays until the listener picks a station. A refusal + // (Android can deny a background start) shows the car an error at once, + // rather than after the browse service's 8 s wait. + AppRegistry.registerHeadlessTask( + CAR_CONNECT_TASK, + () => () => + setupPlayer().catch((e: unknown) => { + plog(`car setup failed: ${e instanceof Error ? e.message : String(e)}`); + carSetupFailed(); + }), + ); } diff --git a/src/intents/tune-flow.ts b/src/intents/tune-flow.ts index b84a1f2..ab1e606 100644 --- a/src/intents/tune-flow.ts +++ b/src/intents/tune-flow.ts @@ -14,6 +14,17 @@ import { splitStationAddress, type StoredStationRef } from '../lib/station-crede import { findSavedStation, matchStations, stationsForSiri } from '../lib/station-store'; import { NO_STATION_MESSAGE } from './station-messages'; +/** Why a tune-in failed, for a caller that says more than Siri's message: + * Android Auto (src/intents/car-errors.ts). The Swift bridge reads only + * `ok` and `message`. */ +export type TuneFailure = 'not-saved' | 'no-station' | 'unreachable'; + +export interface TuneReply extends IntentReply { + reason?: TuneFailure; + /** The station a failed load was for, when its name is known. */ + station?: string; +} + export const NOT_SAVED_MESSAGE = "That station isn't saved in SUB/WAVE. Add it in the app first."; /** How long a switch waits for StationContext to hand the player the new @@ -54,11 +65,11 @@ export async function tuneIn( deps: TuneDeps, stationId: string | undefined, deadline: number, -): Promise { +): Promise { if (stationId) { const store = await deps.loadStore(); const wanted = findSavedStation(store.recents, stationId); - if (!wanted) return { ok: false, message: NOT_SAVED_MESSAGE }; + if (!wanted) return { ok: false, message: NOT_SAVED_MESSAGE, reason: 'not-saved' }; const active = store.activeStation ? splitStationAddress(store.activeStation).base : null; if (splitStationAddress(wanted.url).base !== active) return switchTo(deps, wanted, deadline); } @@ -77,7 +88,7 @@ export async function tuneIn( // when loaded here: a stored format preference is only honoured once the // station's feed confirms the mount, and usePlayer retunes onto it then. const station = await deps.activeStation(); - if (!station) return { ok: false, message: NO_STATION_MESSAGE }; + if (!station) return { ok: false, message: NO_STATION_MESSAGE, reason: 'no-station' }; return started( deps, station.name, @@ -92,7 +103,7 @@ export async function tuneInByName( deps: TuneDeps, query: string, deadline: number, -): Promise { +): Promise { const store = await deps.loadStore(); const [match] = matchStations(stationsForSiri(store.recents), query); return tuneIn(deps, match?.id, deadline); @@ -113,7 +124,7 @@ async function switchTo( deps: TuneDeps, ref: StoredStationRef, deadline: number, -): Promise { +): Promise { const base = splitStationAddress(ref.url).base; await deps.setActiveStation(ref); @@ -139,7 +150,7 @@ async function switchTo( const station = await deps.activeStation(); if (!station) { deps.announceSwitch(); - return { ok: false, message: NO_STATION_MESSAGE }; + return { ok: false, message: NO_STATION_MESSAGE, reason: 'no-station' }; } const ok = await deps.startAndWait(async () => { try { @@ -152,7 +163,7 @@ async function switchTo( return started(deps, station.name ?? ref.name, ok); } -function started(deps: TuneDeps, stationName: string | null, ok: boolean): IntentReply { +function started(deps: TuneDeps, stationName: string | null, ok: boolean): TuneReply { // With a player mounted it owns the control's state, failures included: it // stays tuned in through its own backoff. if (ok) deps.setOnAir(true); @@ -160,15 +171,17 @@ function started(deps: TuneDeps, stationName: string | null, ok: boolean): Inten return ok ? { ok: true } : failed(stationName); } -export function failed(stationName: string | null): IntentReply { +export function failed(stationName: string | null): TuneReply { const station = stationName ?? 'the station'; return { ok: false, message: `Couldn't reach ${station}. If it's private, open SUB/WAVE to unlock it.`, + reason: 'unreachable', + ...(stationName ? { station: stationName } : {}), }; } -export async function tuneOut(deps: TuneDeps): Promise { +export async function tuneOut(deps: TuneDeps): Promise { deps.log('intent tune-out'); await deps.tuneOut().catch(() => {}); deps.setOnAir(false); diff --git a/src/intents/tune.ts b/src/intents/tune.ts index d582893..169ba2d 100644 --- a/src/intents/tune.ts +++ b/src/intents/tune.ts @@ -22,7 +22,13 @@ import { playOnMountedPlayer, tuneInOnArrival, } from '@/lib/remote-play'; -import { announceStationStoreChanged, loadStations, setActiveStation } from '@/lib/station'; +import { + announceStationStoreChanged, + loadStations, + readActiveStationState, + setActiveStation, +} from '@/lib/station'; +import { stationLockRequired } from '@/lib/station-password'; import { timeLeft } from './deadline'; import { activeStation } from './station'; import * as flow from './tune-flow'; @@ -70,13 +76,13 @@ const deps: flow.TuneDeps = { log: (line) => playbackLog.add(line), }; -export function tuneIn(stationId: string | undefined, deadline: number): Promise { +export function tuneIn(stationId: string | undefined, deadline: number): Promise { return flow.tuneIn(deps, stationId, deadline); } /** A station asked for by name ("Hey Google, play Night Shift on SUB/WAVE"), * as Siri matches one (tune-flow.ts). */ -export function tuneInByName(query: string, deadline: number): Promise { +export function tuneInByName(query: string, deadline: number): Promise { return flow.tuneInByName(deps, query, deadline); } @@ -84,6 +90,22 @@ export function tuneOut(): Promise { return flow.tuneOut(deps); } +/** Whether the active station needs a password the app has none saved for: + * after a car pick's stream failed, to tell the car why + * (src/intents/car-errors.ts). One /state read, through readJson's deadline; + * the stream itself is never probed. Unknown counts as not locked. */ +export async function activeStationLocked(): Promise { + const { store, password } = await readActiveStationState(); + if (!store.activeStation || password) return false; + const station = await activeStation(); + if (!station) return false; + try { + return stationLockRequired((await station.api.state()).privacy); + } catch { + return false; + } +} + async function startAndWait(start: () => Promise, deadline: number): Promise { // The card's wait comes out of the budget first; the rest is for audio. const startWait = Math.min(START_WAIT_MS, timeLeft(deadline, Date.now()) - CARD_WAIT_MS);