diff --git a/.gitignore b/.gitignore index 3169800..5d4497f 100644 --- a/.gitignore +++ b/.gitignore @@ -43,6 +43,9 @@ secrets/ /ios /android +# Gradle output of local Expo modules +/modules/*/android/build/ + # local EAS build output (eas build --local --output) /build/ diff --git a/CLAUDE.md b/CLAUDE.md index 6d04834..a0c6e79 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,8 +6,9 @@ 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. - **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`). 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. +- **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. - **The idle skip changes only the native rate, never seeks or reloads** (#9, the port of web's `idleSkip.ts`, kept in step with it). It runs on an MP3 load in the foreground, reads `/state` only after that load's first Playing, and ends on any stall, pause, interruption or backgrounding, since JS timers can stop while the 8x would not. `loadAndPlay` resets the rate to 1x because RNTP carries it to the next item. What it shed reaches the feed as `leadTrimMs`, so the track clock and the DJ's lines move with the listener. - **Playback lines go through `plog` (`src/hooks/usePlayer.ts`), and are redacted before they are stored** (#2140). Release builds keep the last few hundred for the About sheet's Share playback log, so `src/lib/playback-log.ts` strips the station password, the Station login, URL queries and route device names first; a line that can carry a new kind of secret needs a rule and a test there. `PlaybackLog.add` never throws, because `plog` runs mid-reload and ahead of each event's dispatch: a line it can't redact is lost, never stored raw (#2160). - **Every request to a station sends the Station login as a header, from `loginHeaders` (`src/lib/api.ts`)** (#764, #1873): API calls go to the credential-free base, and images get the header too. Android's fetch and image loaders, and AVPlayer, ignore URL userinfo. diff --git a/README.md b/README.md index 08ee1dc..6c44624 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Native iOS + Android player for [SUB/WAVE](../README.md) — built with Expo + r ## Stack - **Expo SDK 57** (RN 0.86, React 19, New Architecture) · **expo-router** (file-based) -- **react-native-track-player** — background audio + lock-screen / CarPlay controls (Android Auto is intentionally not declared — Google Play rejected it under the Auto content policy, #477) +- **react-native-track-player** — background audio + lock-screen / CarPlay controls, and the session Android Auto browses (`modules/android-auto`; Play enforced against an earlier declaration, #477, so this is a second attempt) - **react-native-google-cast** — Google Cast sender (Chromecast / Nest / Android TV). The Cast device fetches the stream itself; the phone becomes a remote (`src/hooks/useCast.ts` merges cast state over the local player). Uses the Default Media Receiver, so no receiver registration. Basic-auth stations can't cast (the `Authorization` header can't ride along) — the button hides for them. - **AirPlay** (iOS) — a local Expo module (`modules/airplay-route-picker`) wraps `AVRoutePickerView`; routing itself is system-level, the button just makes it discoverable in-app. - **NativeWind 4** (Tailwind for RN) — reuses the web's class names + the 7 theme tokens diff --git a/docs/PRODUCTION-READINESS.md b/docs/PRODUCTION-READINESS.md index f7904d0..e93e6d3 100644 --- a/docs/PRODUCTION-READINESS.md +++ b/docs/PRODUCTION-READINESS.md @@ -146,7 +146,7 @@ The pipeline is already proven (ascAppId `6778786696`, submit config in `eas.jso - Lock-screen metadata + persona/cover swap on song change - Headphone unplug → pauses; resume returns to live edge (validates A3) - Phone-call interruption + resume (`autoHandleInterruptions`) - - CarPlay controls (iOS; Android Auto intentionally not declared — Play policy) + - CarPlay controls (iOS) and the Android Auto station list (Android) - Wifi→cellular switch: banner shows, reconnect within a beat (validates A1) - Airplane-mode cold start: banner shows, no stuck splash - Station off-air mid-listen diff --git a/docs/QA-CHECKLIST.md b/docs/QA-CHECKLIST.md index 5048672..88361ae 100644 --- a/docs/QA-CHECKLIST.md +++ b/docs/QA-CHECKLIST.md @@ -51,7 +51,7 @@ Mark each box per platform. Note the device + OS version you tested on. ## Platform controls - [ ] **iOS** — **CarPlay**: SUB/WAVE appears, shows now-playing, Play/Pause/Stop work. - _(Android Auto is intentionally **not** declared — rejected by Google Play under the Auto TTS-content policy; nothing to test there.)_ +- [ ] **Android** — **Android Auto** (Desktop Head Unit or a car): the saved stations are listed; a tap plays and opens Now Playing; play/pause work; "play " by voice switches station; force-stopped app → connect → pick a station still plays (TESTING.md, Android Auto). - [ ] **iOS 17+** — **Live Activity appears on tune-in**: lock the phone → the SUB/WAVE card is on the Lock Screen with station name, title, artist, cover and a running clock. Tune out → the card disappears. - [ ] **iOS 17+** — **Card tracks the broadcast while backgrounded**: leave it locked across a song change → title/artist/cover swap and the progress bar restarts. While the DJ talks, the artist line + artwork swap to the persona (same as the lock screen). - [ ] **iOS 17+** — **Cover art renders**, not the fallback disc mark. _(a disc mark on every track means the App Group entitlement is missing on one side — see TESTING.md)_ diff --git a/docs/TESTING.md b/docs/TESTING.md index 6b7f512..2188467 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -30,7 +30,7 @@ RNTP 4.1.2 is not natively New-Architecture-compatible — out of the box, Andro playback crashes with `You should not use ReactNativeHost directly in the New Architecture` from `MusicService`. **The fix is `patches/react-native-track-player+4.1.2.patch`**, whose New Architecture half is two source edits (the rest of the patch is the -progress and iOS metadata fixes described below): +progress, iOS metadata and Android Auto changes described below): - `MusicModule.kt` — routes async `@ReactMethod`s through a Unit-returning `launch` helper (TurboModule interop requires void-returning async methods). @@ -53,6 +53,15 @@ The iOS metadata patch clears omitted song-clock fields and preserves artwork on progress-only refreshes, while retaining `isLiveStream` and the LIVE controls. These changes require a new binary, not an OTA update. +The patch also carries Android Auto's half of the player (see "Android Auto" +below). `MediaBrowserBridge` reads the same two pinned KotlinAudio fields to +give the session a `PlaybackPreparer` and hand its token to the browse service, +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. + 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 in milliseconds, and position should match the app's elapsed time, including @@ -253,14 +262,80 @@ stream in the phone app first, then connect the car. RNTP feeds the iOS surface Play/Pause work; no scrubber (the `isLiveStream` track hides it). On iOS 26+ the Live Activity's `.small` card also appears on the CarPlay Dashboard. -> **Android Auto is intentionally not declared.** The earlier -> `plugins/withAndroidAuto.js` declaration (#444) was **rejected by Google Play** -> (20 Jun 2026) under the Auto App Quality Guidelines: media apps that use a TTS -> engine to read out content aren't permitted on Android Auto, which is exactly -> what SUB/WAVE's AI DJ does. The declaration was removed so the Android build -> stays Play-compliant. iOS CarPlay is unaffected (separate `MPNowPlayingInfoCenter` -> path, no manifest declaration). Revisit only if Google's policy changes **and** -> a compliant `MediaBrowserService` browse tree is added. +### 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. + +> **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. + +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. +- **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 + RNTP's `remote-play-id` and `remote-play-search` events, which 4.1.2 declares + but never fires. `service.ts` answers them with `tuneIn` / `tuneInByName` + (`src/intents/tune.ts`), the tune-in Siri uses, so a pick goes through + `tune-flow.ts` like an App Intent's: with the player mounted it is handed to + 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). +- **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 + `setupPlayer()` and nothing else: Auto forbids autoplay on launch. RNTP refuses + `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. +- **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. +- **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. +- **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. +- **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. ### iPad — every orientation, Split View, Stage Manager @@ -552,7 +627,8 @@ port types without device names, with `Other` for a word that isn't a known port ## Known issues / gotchas - **`patches/react-native-track-player+4.1.2.patch`** contains the RNTP new-arch - and media-session progress fixes (see "Architecture-critical facts"). It was previously bloated + and media-session progress fixes and Android Auto's `MediaBrowserBridge` (see + "Architecture-critical facts"). It was previously bloated to 229 files with accidental Gradle build artifacts; slimmed in 2026-06 and re-verified with a clean `BUILD SUCCESSFUL` before the progress fix was added. Keep it lean — never run `patch-package` after a Gradle build has populated diff --git a/index.ts b/index.ts index bbdf33e..1cf5151 100644 --- a/index.ts +++ b/index.ts @@ -1,14 +1,17 @@ // App entry: register the RNTP playback service so OS media controls reach our // remote handlers even when the JS UI isn't mounted, then hand off to // expo-router. The service MUST be registered before the router entry runs. -// App Intents register here for the same reason: Siri or a Control can launch -// the app into the background, where no screen may ever mount. +// App Intents and Android Auto register here for the same reason: Siri, a +// Control or the car can launch the app into the background, where no screen +// may ever mount. import TrackPlayer from 'react-native-track-player'; +import { registerCarHandlers } from '@/intents/car'; import { registerIntentHandlers } from '@/intents/handlers'; import { PlaybackService } from './service'; TrackPlayer.registerPlaybackService(() => PlaybackService); registerIntentHandlers(); +registerCarHandlers(); // Registration must run before the router starts the app. // eslint-disable-next-line import/first diff --git a/modules/android-auto/android/build.gradle b/modules/android-auto/android/build.gradle new file mode 100644 index 0000000..9ecc324 --- /dev/null +++ b/modules/android-auto/android/build.gradle @@ -0,0 +1,22 @@ +plugins { + id 'com.android.library' + id 'expo-module-gradle-plugin' +} + +group = 'com.getsubwave' +version = '1.0.0' + +android { + namespace "com.getsubwave.androidauto" + defaultConfig { + versionCode 1 + versionName "1.0.0" + } +} + +dependencies { + // The player's session and its play-from-id events: the RNTP patch's MediaBrowserBridge. + implementation project(':react-native-track-player') + implementation 'com.facebook.react:react-android' + implementation 'androidx.media:media:1.7.0' +} diff --git a/modules/android-auto/android/src/main/AndroidManifest.xml b/modules/android-auto/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..a9a92ed --- /dev/null +++ b/modules/android-auto/android/src/main/AndroidManifest.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + 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 new file mode 100644 index 0000000..a47e970 --- /dev/null +++ b/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarCallers.kt @@ -0,0 +1,62 @@ +package com.getsubwave.androidauto + +import android.Manifest +import android.content.Context +import android.content.pm.ApplicationInfo +import android.content.pm.PackageManager +import android.os.Build +import android.os.Process + +/** + * Who may browse SUB/WAVE: Android Auto, Android Automotive's media centre, + * the Google app (Assistant's voice search), and the system. Everything else + * 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. + * + * 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 + * package must instead own the calling UID and be a system app or installed + * by the Play Store, which no other developer can publish under that name. + * That needs no certificate list to keep up to date. + */ +internal object CarCallers { + private val GOOGLE_CALLERS = setOf( + "com.google.android.projection.gearhead", // Android Auto + "com.google.android.carassistant", // Assistant on Android Automotive + "com.android.car.media", // Android Automotive's media centre + "com.google.android.googlequicksearchbox", // Google app, Assistant + ) + private const val PLAY_STORE = "com.android.vending" + + fun allowed(context: Context, packageName: String, uid: Int): Boolean { + if (uid == Process.myUid() || uid == Process.SYSTEM_UID) return true + val pm = context.packageManager + // The name must be the caller's own, not one it claims. + if (pm.getPackagesForUid(uid)?.contains(packageName) != true) return false + if (pm.checkSignatures("android", packageName) == PackageManager.SIGNATURE_MATCH) return true + if (pm.checkPermission(Manifest.permission.MEDIA_CONTENT_CONTROL, packageName) == + PackageManager.PERMISSION_GRANTED + ) return true + return packageName in GOOGLE_CALLERS && (isSystemApp(pm, packageName) || fromPlay(pm, packageName)) + } + + 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 + } catch (e: PackageManager.NameNotFoundException) { + false + } + + private fun fromPlay(pm: PackageManager, packageName: String): Boolean = try { + val installer = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + pm.getInstallSourceInfo(packageName).installingPackageName + } else { + @Suppress("DEPRECATION") + pm.getInstallerPackageName(packageName) + } + installer == PLAY_STORE + } catch (e: Exception) { + false + } +} 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 new file mode 100644 index 0000000..150ccf5 --- /dev/null +++ b/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarConnectTask.kt @@ -0,0 +1,50 @@ +package com.getsubwave.androidauto + +import android.app.Application +import androidx.annotation.MainThread +import com.facebook.react.ReactApplication +import com.facebook.react.ReactInstanceEventListener +import com.facebook.react.bridge.Arguments +import com.facebook.react.bridge.ReactContext +import com.facebook.react.bridge.UiThreadUtil +import com.facebook.react.jstasks.HeadlessJsTaskConfig +import com.facebook.react.jstasks.HeadlessJsTaskContext + +/** + * Runs JS's car-connect task, which sets the player up so its session exists + * for the car (src/intents/car.ts). Starts React Native first when the car is + * what launched the app: there is no activity, so nothing else will. + */ +internal object CarConnectTask { + // Matched by STRING with src/intents/car.ts (npm test checks). + private const val TASK = "SubwaveCarConnect" + private const val TIMEOUT_MS = 30_000L + + private var starting = false + + @MainThread + fun run(app: Application) { + val host = (app as? ReactApplication)?.reactHost ?: return + host.currentReactContext?.let { + start(it) + return + } + if (starting) return + starting = true + host.addReactInstanceEventListener(object : ReactInstanceEventListener { + override fun onReactContextInitialized(context: ReactContext) { + host.removeReactInstanceEventListener(this) + UiThreadUtil.runOnUiThread { + starting = false + start(context) + } + } + }) + host.start() + } + + 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 new file mode 100644 index 0000000..3ff05a0 --- /dev/null +++ b/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarStations.kt @@ -0,0 +1,46 @@ +package com.getsubwave.androidauto + +import android.content.Context +import android.net.Uri +import android.support.v4.media.MediaBrowserCompat.MediaItem +import android.support.v4.media.MediaDescriptionCompat +import org.json.JSONObject + +/** One saved station, as JS mirrors it: the credential-free base is the id. */ +internal data class CarStation(val id: String, val name: String) { + fun toMediaItem(): MediaItem { + val description = MediaDescriptionCompat.Builder() + .setMediaId(id) + .setTitle(name) + .setSubtitle(Uri.parse(id).host ?: id) + .build() + return MediaItem(description, MediaItem.FLAG_PLAYABLE) + } +} + +/** + * The saved stations, written by JS (StationContext, through the module's + * setStations) for a car that may connect while JS is not running. The same + * `{ active, stations: [{ id, name }] }` JSON the iOS module writes for Siri. + * Names and bases only: a station's login and password stay in JS's keychain. + */ +internal object CarStations { + private const val PREFS = "subwave.android-auto" + private const val KEY = "stations" + + fun save(context: Context, json: String) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, json).apply() + } + + 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 station = stations.getJSONObject(it) + CarStation(station.getString("id"), station.getString("name")) + } + }.getOrDefault(emptyList()) + } +} 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 new file mode 100644 index 0000000..bead49d --- /dev/null +++ b/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/SubwaveAndroidAutoModule.kt @@ -0,0 +1,20 @@ +package com.getsubwave.androidauto + +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() { + override fun definition() = ModuleDefinition { + Name("SubwaveAndroidAuto") + + /** The saved stations and the active one, as JSON from JS: + * `{ active, stations: [{ id, name }] }`. Redraws the car's list. */ + Function("setStations") { json: String -> + val context = appContext.reactContext ?: return@Function + CarStations.save(context, json) + SubwaveBrowseService.stationsChanged() + } + } +} 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 new file mode 100644 index 0000000..69e6004 --- /dev/null +++ b/modules/android-auto/android/src/main/java/com/getsubwave/androidauto/SubwaveBrowseService.kt @@ -0,0 +1,91 @@ +package com.getsubwave.androidauto + +import android.os.Bundle +import android.support.v4.media.MediaBrowserCompat.MediaItem +import android.support.v4.media.session.MediaSessionCompat +import androidx.media.MediaBrowserServiceCompat +import com.doublesymmetry.trackplayer.service.MediaBrowserBridge + +/** + * Android Auto's view of SUB/WAVE: the saved stations, 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). + * + * 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. + * + * 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. + */ +class SubwaveBrowseService : MediaBrowserServiceCompat() { + private var sessionEnded = false + + private val session = object : MediaBrowserBridge.SessionListener { + override fun ready(token: MediaSessionCompat.Token) { + if (sessionToken == null) sessionToken = token + } + + override fun ended() { + if (sessionToken != null) sessionEnded = true + } + } + + override fun onCreate() { + super.onCreate() + current = this + MediaBrowserBridge.addListener(session) + } + + override fun onDestroy() { + MediaBrowserBridge.removeListener(session) + current = null + MediaBrowserBridge.browsing = false + super.onDestroy() + } + + override fun onGetRoot(clientPackageName: String, clientUid: Int, rootHints: Bundle?): BrowserRoot? { + // System UI asks every media app for something to resume after a reboot. + // A live station has nothing to resume, and answering would start the app + // in the background on every boot. + if (rootHints?.getBoolean(BrowserRoot.EXTRA_RECENT) == true) return null + // Only the car, the Assistant and the system: anything else that binds + // would read the saved stations and start the app in the background. + if (!CarCallers.allowed(this, clientPackageName, clientUid)) return null + // 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) + } + + override fun onLoadChildren(parentId: String, result: Result>) { + val items = if (parentId == ROOT) CarStations.load(this).map { it.toMediaItem() } else emptyList() + result.sendResult(items.toMutableList()) + } + + companion object { + private const val ROOT = "subwave-root" + + // 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) + } + + @Volatile + private var current: SubwaveBrowseService? = null + + /** Redraws the car's list, when the car is connected. */ + fun stationsChanged() { + current?.notifyChildrenChanged(ROOT) + } + } +} 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 new file mode 100644 index 0000000..b4a189f --- /dev/null +++ b/modules/android-auto/android/src/main/res/xml/subwave_automotive_app_desc.xml @@ -0,0 +1,3 @@ + + + diff --git a/modules/android-auto/expo-module.config.json b/modules/android-auto/expo-module.config.json new file mode 100644 index 0000000..e345711 --- /dev/null +++ b/modules/android-auto/expo-module.config.json @@ -0,0 +1,6 @@ +{ + "platforms": ["android"], + "android": { + "modules": ["com.getsubwave.androidauto.SubwaveAndroidAutoModule"] + } +} diff --git a/modules/android-auto/index.ts b/modules/android-auto/index.ts new file mode 100644 index 0000000..0399b51 --- /dev/null +++ b/modules/android-auto/index.ts @@ -0,0 +1,31 @@ +// The JS half of Android Auto: the station list the car shows. The car's side +// is android/…/SubwaveBrowseService.kt. A no-op outside Android. + +import { requireNativeModule } from 'expo-modules-core'; +import { Platform } from 'react-native'; +import type { MirroredStation } from '@/lib/station-store'; + +interface NativeAndroidAuto { + setStations(json: string): void; +} + +// Binaries older than Android Auto support lack this module, and an OTA +// update must not crash them. +const native: NativeAndroidAuto | null = (() => { + if (Platform.OS !== 'android') return null; + try { + return requireNativeModule('SubwaveAndroidAuto') as unknown as NativeAndroidAuto; + } catch { + return null; + } +})(); + +/** The saved stations and the active one, for a car that may connect while JS + * is not running. Names and credential-free bases only, as for Siri. */ +export function setStations(active: string | null, stations: MirroredStation[]): void { + try { + native?.setStations(JSON.stringify({ active, stations })); + } catch { + /* a binary older than Android Auto support */ + } +} diff --git a/patches/react-native-track-player+4.1.2.patch b/patches/react-native-track-player+4.1.2.patch index 81b6363..b705557 100644 --- a/patches/react-native-track-player+4.1.2.patch +++ b/patches/react-native-track-player+4.1.2.patch @@ -91,10 +91,17 @@ index 0000000..f3dd73c + } +} diff --git a/node_modules/react-native-track-player/android/src/main/java/com/doublesymmetry/trackplayer/module/MusicModule.kt b/node_modules/react-native-track-player/android/src/main/java/com/doublesymmetry/trackplayer/module/MusicModule.kt -index b2409a0..301f0ee 100644 +index b2409a0..38187bc 100644 --- a/node_modules/react-native-track-player/android/src/main/java/com/doublesymmetry/trackplayer/module/MusicModule.kt +++ b/node_modules/react-native-track-player/android/src/main/java/com/doublesymmetry/trackplayer/module/MusicModule.kt -@@ -18,6 +18,7 @@ import com.doublesymmetry.trackplayer.utils.RejectionException +@@ -12,12 +12,14 @@ import com.doublesymmetry.trackplayer.extensions.NumberExt.Companion.toMilliseco + import com.doublesymmetry.trackplayer.model.State + import com.doublesymmetry.trackplayer.model.Track + import com.doublesymmetry.trackplayer.module.MusicEvents.Companion.EVENT_INTENT ++import com.doublesymmetry.trackplayer.service.MediaBrowserBridge + import com.doublesymmetry.trackplayer.service.MusicService + import com.doublesymmetry.trackplayer.utils.AppForegroundTracker + import com.doublesymmetry.trackplayer.utils.RejectionException import com.facebook.react.bridge.* import com.google.android.exoplayer2.DefaultLoadControl.* import com.google.android.exoplayer2.Player @@ -102,7 +109,7 @@ index b2409a0..301f0ee 100644 import kotlinx.coroutines.MainScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch -@@ -38,6 +39,14 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -38,6 +40,14 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM private lateinit var musicService: MusicService private val context = reactContext @@ -117,7 +124,58 @@ index b2409a0..301f0ee 100644 @Nonnull override fun getName(): String { return "TrackPlayerModule" -@@ -251,7 +260,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -170,7 +180,8 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM + } + + // prevent crash Fatal Exception: android.app.RemoteServiceException$ForegroundServiceDidNotStartInTimeException +- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && AppForegroundTracker.backgrounded) { ++ // A bound media browser (Android Auto) lets the app start playback with no activity. (patched) ++ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && AppForegroundTracker.backgrounded && !MediaBrowserBridge.browsing) { + promise.reject( + "android_cannot_setup_player_in_background", + "On Android the app must be in the foreground when setting up the player." +@@ -225,21 +236,28 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM + return + } + +- playerSetUpPromise = promise +- playerOptions = bundledData ++ Intent(context, MusicService::class.java).also { intent -> ++ // Android can still refuse a background start: answer instead of ++ // crashing, before anything is registered for a retry to repeat. (patched) ++ try { ++ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { ++ context.startForegroundService(intent) ++ } else { ++ context.startService(intent) ++ } ++ } catch (e: IllegalStateException) { ++ promise.reject("android_cannot_setup_player_in_background", e.message) ++ return ++ } + ++ playerSetUpPromise = promise ++ playerOptions = bundledData + +- LocalBroadcastManager.getInstance(context).registerReceiver( +- MusicEvents(context), +- IntentFilter(EVENT_INTENT) +- ) ++ LocalBroadcastManager.getInstance(context).registerReceiver( ++ MusicEvents(context), ++ IntentFilter(EVENT_INTENT) ++ ) + +- Intent(context, MusicService::class.java).also { intent -> +- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { +- context.startForegroundService(intent) +- } else { +- context.startService(intent) +- } + context.bindService(intent, this, Context.BIND_AUTO_CREATE) + } + } +@@ -251,7 +269,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -126,7 +184,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch val options = Arguments.toBundle(data) -@@ -264,7 +273,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -264,7 +282,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -135,7 +193,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch try { -@@ -285,7 +294,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -285,7 +303,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -144,7 +202,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch if (data == null) { callback.resolve(null) -@@ -301,14 +310,14 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -301,14 +319,14 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -161,7 +219,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch val inputIndexes = Arguments.toList(data) if (inputIndexes != null) { -@@ -332,7 +341,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -332,7 +350,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM @ReactMethod fun updateMetadataForTrack(index: Int, map: ReadableMap?, callback: Promise) = @@ -170,7 +228,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch if (index < 0 || index >= musicService.tracks.size) { -@@ -348,23 +357,23 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -348,23 +366,23 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -200,7 +258,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch if (musicService.tracks.isEmpty()) -@@ -375,7 +384,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -375,7 +393,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -209,7 +267,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch musicService.removeUpcomingTracks() -@@ -383,7 +392,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -383,7 +401,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -218,7 +276,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch musicService.skip(index) -@@ -396,7 +405,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -396,7 +414,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -227,7 +285,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch musicService.skipToNext() -@@ -409,7 +418,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -409,7 +427,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -236,7 +294,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch musicService.skipToPrevious() -@@ -422,7 +431,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -422,7 +440,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -245,7 +303,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch musicService.stop() -@@ -433,7 +442,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -433,7 +451,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -254,7 +312,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch musicService.play() -@@ -441,7 +450,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -441,7 +459,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -263,7 +321,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch musicService.pause() -@@ -449,7 +458,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -449,7 +467,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -272,7 +330,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch musicService.stop() -@@ -457,7 +466,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -457,7 +475,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -281,7 +339,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch musicService.seekTo(seconds) -@@ -465,7 +474,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -465,7 +483,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -290,7 +348,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch musicService.seekBy(offset) -@@ -473,7 +482,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -473,7 +491,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -299,7 +357,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch musicService.retry() -@@ -481,7 +490,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -481,7 +499,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -308,7 +366,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch musicService.setVolume(volume) -@@ -489,14 +498,14 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -489,14 +507,14 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -325,7 +383,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch musicService.setRate(rate) -@@ -504,14 +513,14 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -504,14 +522,14 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -342,7 +400,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch musicService.setRepeatMode(RepeatMode.fromOrdinal(mode)) -@@ -519,14 +528,14 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -519,14 +537,14 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -359,7 +417,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch musicService.playWhenReady = playWhenReady -@@ -534,32 +543,32 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -534,32 +552,32 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -397,7 +455,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch try { -@@ -572,7 +581,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -572,7 +590,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -406,7 +464,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch callback.resolve( if (musicService.tracks.isEmpty()) null else musicService.getCurrentTrackIndex() -@@ -580,39 +589,39 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -580,39 +598,39 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -452,7 +510,7 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch var bundle = Bundle() bundle.putDouble("duration", musicService.getDurationInSeconds()); -@@ -622,7 +631,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM +@@ -622,7 +640,7 @@ class MusicModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaM } @ReactMethod @@ -461,8 +519,131 @@ index b2409a0..301f0ee 100644 if (verifyServiceBoundOrReject(callback)) return@launch callback.resolve(Arguments.fromBundle(musicService.getPlayerStateBundle(musicService.state))) } +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 +--- /dev/null ++++ b/node_modules/react-native-track-player/android/src/main/java/com/doublesymmetry/trackplayer/service/MediaBrowserBridge.kt +@@ -0,0 +1,117 @@ ++package com.doublesymmetry.trackplayer.service ++ ++import android.net.Uri ++import android.os.Bundle ++import android.os.ResultReceiver ++import android.support.v4.media.session.MediaSessionCompat ++import android.support.v4.media.session.PlaybackStateCompat ++import androidx.annotation.MainThread ++import com.doublesymmetry.kotlinaudio.notification.NotificationManager ++import com.doublesymmetry.trackplayer.module.MusicEvents ++import com.google.android.exoplayer2.Player ++import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector ++ ++/** ++ * 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) ++ */ ++object MediaBrowserBridge { ++ /** True while a media browser is bound. Lets setupPlayer run with no ++ * activity in front: the car launched the app. */ ++ @Volatile ++ @JvmStatic ++ var browsing = false ++ ++ /** A media browser service waiting on the player's session. */ ++ interface SessionListener { ++ /** The player's session exists: publish [token]. */ ++ fun ready(token: MediaSessionCompat.Token) ++ /** That session was released with its MusicService: a token already ++ * published is dead. */ ++ fun ended() ++ } ++ ++ private var token: MediaSessionCompat.Token? = null ++ private val listeners = mutableSetOf() ++ ++ /** Calls [listener] with the player's session token now, or once setupPlayer ++ * has created the player, and again for each session after it. */ ++ @MainThread ++ @JvmStatic ++ fun addListener(listener: SessionListener) { ++ listeners.add(listener) ++ token?.let(listener::ready) ++ } ++ ++ @MainThread ++ @JvmStatic ++ fun removeListener(listener: SessionListener) { ++ listeners.remove(listener) ++ } ++ ++ @MainThread ++ internal fun attach(manager: NotificationManager, emit: (String, Bundle) -> Unit) { ++ // The same pinned KotlinAudio fields NowPlayingProgress adapts. ++ val connector = field(manager, "mediaSessionConnector") as MediaSessionConnector ++ val player = field(manager, "player") as Player ++ connector.setPlaybackPreparer(Preparer(player, emit)) ++ val session = connector.mediaSession.sessionToken ++ token = session ++ listeners.toList().forEach { it.ready(session) } ++ } ++ ++ /** MusicService is going, and its session with it: a browser that binds ++ * after this waits for the next setupPlayer instead of taking a dead token. */ ++ @MainThread ++ internal fun detach() { ++ if (token == null) return ++ token = null ++ listeners.toList().forEach { it.ended() } ++ } ++ ++ private fun field(manager: NotificationManager, name: String): Any = ++ NotificationManager::class.java.getDeclaredField(name).let { ++ it.isAccessible = true ++ it.get(manager)!! ++ } ++ ++ private class Preparer( ++ private val player: Player, ++ private val emit: (String, Bundle) -> Unit, ++ ) : MediaSessionConnector.PlaybackPreparer { ++ // Not ACTION_PREPARE: Play on an idle player keeps the connector's own path. ++ override fun getSupportedPrepareActions(): Long = ++ PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID or ++ PlaybackStateCompat.ACTION_PREPARE_FROM_MEDIA_ID or ++ PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH or ++ PlaybackStateCompat.ACTION_PREPARE_FROM_SEARCH ++ ++ // What the connector does on Play with no preparer set. ++ override fun onPrepare(playWhenReady: Boolean) = player.prepare() ++ ++ // A prepare (playWhenReady false) must not start audio: JS holds the ++ // pick until the next Play (src/intents/car-picks.ts). ++ override fun onPrepareFromMediaId(mediaId: String, playWhenReady: Boolean, extras: Bundle?) = ++ emit(MusicEvents.BUTTON_PLAY_FROM_ID, Bundle().apply { ++ putString("id", mediaId) ++ putBoolean("playWhenReady", playWhenReady) ++ }) ++ ++ override fun onPrepareFromSearch(query: String, playWhenReady: Boolean, extras: Bundle?) = ++ emit(MusicEvents.BUTTON_PLAY_FROM_SEARCH, Bundle().apply { ++ putString("query", query) ++ putBoolean("playWhenReady", playWhenReady) ++ }) ++ ++ override fun onPrepareFromUri(uri: Uri, playWhenReady: Boolean, extras: Bundle?) = Unit ++ ++ override fun onCommand( ++ player: Player, ++ command: String, ++ extras: Bundle?, ++ cb: ResultReceiver?, ++ ): Boolean = false ++ } ++} diff --git a/node_modules/react-native-track-player/android/src/main/java/com/doublesymmetry/trackplayer/service/MusicService.kt b/node_modules/react-native-track-player/android/src/main/java/com/doublesymmetry/trackplayer/service/MusicService.kt -index afa6b0f..422e568 100644 +index afa6b0f..dd8e0a0 100644 --- a/node_modules/react-native-track-player/android/src/main/java/com/doublesymmetry/trackplayer/service/MusicService.kt +++ b/node_modules/react-native-track-player/android/src/main/java/com/doublesymmetry/trackplayer/service/MusicService.kt @@ -24,13 +24,16 @@ import com.doublesymmetry.trackplayer.extensions.find @@ -491,7 +672,15 @@ index afa6b0f..422e568 100644 /** * Use [appKilledPlaybackBehavior] instead. -@@ -302,6 +307,8 @@ class MusicService : HeadlessJsTaskService() { +@@ -160,6 +165,7 @@ class MusicService : HeadlessJsTaskService() { + player.automaticallyUpdateNotificationMetadata = automaticallyUpdateNotificationMetadata + observeEvents() + setupForegrounding() ++ MediaBrowserBridge.attach(player.notificationManager) { event, data -> emit(event, data) } + } + + @MainThread +@@ -302,6 +308,8 @@ class MusicService : HeadlessJsTaskService() { @MainThread fun load(track: Track) { @@ -500,7 +689,7 @@ index afa6b0f..422e568 100644 player.load(track.toAudioItem()) } -@@ -322,6 +329,8 @@ class MusicService : HeadlessJsTaskService() { +@@ -322,6 +330,8 @@ class MusicService : HeadlessJsTaskService() { @MainThread fun clear() { @@ -509,7 +698,7 @@ index afa6b0f..422e568 100644 player.clear() } -@@ -432,8 +441,32 @@ class MusicService : HeadlessJsTaskService() { +@@ -432,8 +442,32 @@ class MusicService : HeadlessJsTaskService() { } @MainThread @@ -544,7 +733,7 @@ index afa6b0f..422e568 100644 } @MainThread -@@ -739,9 +772,21 @@ class MusicService : HeadlessJsTaskService() { +@@ -739,9 +773,21 @@ class MusicService : HeadlessJsTaskService() { return bundle } @@ -567,7 +756,7 @@ index afa6b0f..422e568 100644 ?.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java) ?.emit(event, data?.let { Arguments.fromBundle(it) }) } -@@ -751,7 +796,7 @@ class MusicService : HeadlessJsTaskService() { +@@ -751,7 +797,7 @@ class MusicService : HeadlessJsTaskService() { val payload = Arguments.createArray() data.forEach { payload.pushMap(Arguments.fromBundle(it)) } @@ -576,6 +765,15 @@ index afa6b0f..422e568 100644 ?.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java) ?.emit(event, payload) } +@@ -799,6 +845,8 @@ class MusicService : HeadlessJsTaskService() { + @MainThread + override fun onDestroy() { + super.onDestroy() ++ // The session goes with the player: a car must not keep its token. (patched) ++ MediaBrowserBridge.detach() + if (::player.isInitialized) { + player.destroy() + } diff --git a/node_modules/react-native-track-player/ios/RNTrackPlayer/Utils/Metadata.swift b/node_modules/react-native-track-player/ios/RNTrackPlayer/Utils/Metadata.swift index 70c094d..ece903f 100644 --- a/node_modules/react-native-track-player/ios/RNTrackPlayer/Utils/Metadata.swift diff --git a/scripts/android-auto.test.ts b/scripts/android-auto.test.ts new file mode 100644 index 0000000..ac197f1 --- /dev/null +++ b/scripts/android-auto.test.ts @@ -0,0 +1,119 @@ +// Android Auto: the car's picks (src/intents/car-picks.ts), and the two +// contracts JS shares with native code by text alone, which drift with no +// build error: the car-connect task's name, and the spoken-name rule Google's +// voice search shares with Siri's. + +import assert from 'node:assert/strict'; +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_PICK_BUDGET_MS, createCarPicks } from '../src/intents/car-picks.ts'; + +const ROOT = path.join(import.meta.dirname, '..'); +const read = (file: string) => readFileSync(path.join(ROOT, file), 'utf8'); + +function picks() { + const logged: string[] = []; + const tuned: string[] = []; + const car = createCarPicks((msg) => logged.push(msg)); + const pick = (label: string, reply: IntentReply | Error = { ok: true }) => ({ + label, + tune: async () => { + tuned.push(label); + if (reply instanceof Error) throw reply; + return reply; + }, + }); + return { car, pick, logged, tuned }; +} + +test('a pick that plays tunes in at once', async () => { + const { car, pick, tuned } = picks(); + await car.pick(pick('pick a'), true); + assert.deepEqual(tuned, ['pick a']); + assert.equal(car.playPrepared(), false); +}); + +test('a prepare starts nothing, and the next Play tunes in to it once', async () => { + const { car, pick, tuned } = picks(); + await car.pick(pick('pick a'), false); + assert.deepEqual(tuned, []); + assert.equal(car.playPrepared(), true); + await Promise.resolve(); + assert.deepEqual(tuned, ['pick a']); + assert.equal(car.playPrepared(), false, 'a later Play is the usual remote Play'); +}); + +test("a prepared pick's deadline runs from its Play, not from the prepare", async () => { + let now = 1_000; + const deadlines: number[] = []; + const car = createCarPicks( + () => {}, + () => now, + ); + await car.pick( + { + label: 'pick a', + tune: async (deadline) => { + deadlines.push(deadline); + return { ok: true }; + }, + }, + false, + ); + now = 61_000; + car.playPrepared(); + await Promise.resolve(); + assert.deepEqual(deadlines, [61_000 + CAR_PICK_BUDGET_MS]); +}); + +test('a pick that plays replaces a held prepare', async () => { + const { car, pick, tuned } = picks(); + await car.pick(pick('pick a'), false); + await car.pick(pick('pick b'), true); + assert.equal(car.playPrepared(), false); + assert.deepEqual(tuned, ['pick b']); +}); + +test('pause or stop drops a held prepare', async () => { + const { car, pick, tuned } = picks(); + await car.pick(pick('pick a'), false); + car.forget(); + assert.equal(car.playPrepared(), false); + assert.deepEqual(tuned, []); +}); + +test('a refused or failed tune-in is logged, never thrown', async () => { + const { car, pick, logged } = picks(); + await car.pick(pick('pick a', { ok: false, message: "That station isn't saved" }), true); + await car.pick(pick('search "x"', new Error('load failed')), true); + assert.deepEqual(logged, [ + "car pick a refused: That station isn't saved", + 'car search "x" failed: load failed', + ]); +}); + +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( + 'modules/android-auto/android/src/main/java/com/getsubwave/androidauto/CarConnectTask.kt', + ).match(/const val TASK = "([^"]+)"/)?.[1]; + assert.ok(js, 'CAR_CONNECT_TASK not found in src/intents/car.ts'); + assert.equal(kotlin, js, 'CarConnectTask.kt starts a task JS never registered'); +}); + +test("matchStations keeps Siri's rule: the same generic words and shortest term", () => { + const ts = read('src/lib/station-store.ts'); + const swift = read('targets/live-activity/_shared/StationEntities.swift'); + const words = (block: string | undefined) => + [...(block ?? '').matchAll(/['"]([a-z]+)['"]/g)].map((m) => m[1]).sort(); + const tsWords = words(ts.match(/GENERIC_TERMS = new Set\(\[([^\]]*)\]/)?.[1]); + const swiftWords = words(swift.match(/genericTerms: Set = \[([^\]]*)\]/)?.[1]); + assert.ok(tsWords.length, 'GENERIC_TERMS not found in station-store.ts'); + assert.deepEqual(swiftWords, tsWords, 'the generic words differ: change both'); + const tsMin = ts.match(/wanted\.length < (\d+)/)?.[1]; + const swiftMin = swift.match(/wanted\.count >= (\d+)/)?.[1]; + assert.ok(tsMin, 'the shortest-term check not found in station-store.ts'); + assert.equal(swiftMin, tsMin, 'the shortest term differs: change both'); +}); diff --git a/scripts/intent-stations.test.ts b/scripts/intent-stations.test.ts index dadc36b..10d7429 100644 --- a/scripts/intent-stations.test.ts +++ b/scripts/intent-stations.test.ts @@ -4,7 +4,12 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { findSavedStation, stationsForSiri, streamBelongsTo } from '../src/lib/station-store.ts'; +import { + findSavedStation, + matchStations, + stationsForSiri, + streamBelongsTo, +} from '../src/lib/station-store.ts'; const recents = [ { url: 'https://radio.example.com', name: 'Night Shift', lastUsed: 2 }, @@ -49,3 +54,35 @@ test('a stream belongs to the station whose base it is built on', () => { // A host that merely starts the same is a different station. assert.ok(!streamBelongsTo('https://radio.example.com.evil.net/stream.mp3', base)); }); + +test('a spoken station name matches however speech spells it', () => { + const stations = [ + { id: 'https://radio.example.com', name: 'ChillWave Radio' }, + { id: 'https://night.example.com', name: 'Night Shift' }, + { id: 'https://cafe.example.com', name: 'Café Ñandú' }, + ]; + const ids = (term: string) => matchStations(stations, term).map((s) => s.id); + assert.deepEqual(ids('chill wave radio'), ['https://radio.example.com']); + assert.deepEqual(ids('chillwave'), ['https://radio.example.com']); + assert.deepEqual(ids('the night shift station'), ['https://night.example.com']); + assert.deepEqual(ids('night shift'), ['https://night.example.com']); + assert.deepEqual(ids('cafe nandu'), ['https://cafe.example.com']); +}); + +test('a generic or too-short term names no station', () => { + const stations = [{ id: 'https://radio.example.com', name: 'ChillWave Radio' }]; + for (const term of ['', 'radio', 'Radio!', 'some music', 'SUB/WAVE', 'ch']) { + assert.deepEqual(matchStations(stations, term), [], term); + } +}); + +test('an exact name wins over one that only contains the term', () => { + const stations = [ + { id: 'https://a.example.com', name: 'Night Shift Radio' }, + { id: 'https://b.example.com', name: 'Night Shift' }, + ]; + assert.deepEqual( + matchStations(stations, 'night shift').map((s) => s.id), + ['https://b.example.com'], + ); +}); diff --git a/scripts/intent-tune.test.ts b/scripts/intent-tune.test.ts index 7052322..ed1d5b4 100644 --- a/scripts/intent-tune.test.ts +++ b/scripts/intent-tune.test.ts @@ -1,5 +1,6 @@ // Tune-ins and tune-outs from Siri, Shortcuts, Spotlight and the Control -// (src/intents/tune-flow.ts): with the player mounted every load is handed to +// (src/intents/tune-flow.ts), and Android Auto's picks, which tune in the same +// way (src/intents/car-picks.ts): with the player mounted every load is handed to // it, so it goes through StreamRecovery; only with none mounted does the // intent load the stream itself. Also the mounted player's side of a station // switch (src/lib/remote-play.ts) and the bridge's deadline @@ -16,7 +17,14 @@ import { within, } from '../src/intents/deadline.ts'; import { NO_STATION_MESSAGE } from '../src/intents/station-messages.ts'; -import { NOT_SAVED_MESSAGE, tuneIn, tuneOut, type TuneDeps } from '../src/intents/tune-flow.ts'; +import { CAR_PICK_BUDGET_MS, createCarPicks } from '../src/intents/car-picks.ts'; +import { + NOT_SAVED_MESSAGE, + tuneIn, + tuneInByName, + tuneOut, + type TuneDeps, +} from '../src/intents/tune-flow.ts'; import { claimRemotePlay, playerMounted, @@ -247,3 +255,76 @@ test('within gives the work’s answer, or TIMED_OUT once the wait ends first', assert.equal(await within(Promise.resolve('done'), new Promise(() => {})), 'done'); assert.equal(await within(new Promise(() => {}), Promise.resolve()), TIMED_OUT); }); + +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(s.calls, ['store Night Shift', `arm ${NIGHT.url}`, 'announce', 'disarm']); +}); + +test('a name that matches nothing, or a generic word, tunes in to the station listened to last', async () => { + for (const query of ['jazz fm', 'radio']) { + const s = intents({ mounted: true }); + assert.deepEqual(await tuneInByName(s.deps, query, DEADLINE), { ok: true }); + assert.deepEqual(s.calls, ['player tunes in'], query); + } +}); + +test('with no player mounted, a station asked for by name is loaded directly', async () => { + const s = intents(); + await tuneInByName(s.deps, 'Night Shift', DEADLINE); + assert.deepEqual(s.calls, [`direct load ${NIGHT.url}`]); +}); + +// Android Auto: a pick, a voice search and a prepared pick's Play, wired as +// service.ts wires them, never load past the mounted player. +function carPicks(s: ReturnType, now: number) { + const logged: string[] = []; + const car = createCarPicks( + (line) => logged.push(line), + () => now, + ); + const byId = (id: string) => ({ + label: `pick ${id}`, + tune: (deadline: number) => tuneIn(s.deps, id, deadline), + }); + const byName = (query: string) => ({ + label: `search "${query}"`, + tune: (deadline: number) => tuneInByName(s.deps, query, deadline), + }); + return { car, byId, byName, logged }; +} + +test('car picks go through the mounted player: by id, by voice, and a prepared Play', async () => { + const now = DEADLINE - CAR_PICK_BUDGET_MS; + + const id = intents({ mounted: true }); + await carPicks(id, now).car.pick(carPicks(id, now).byId(WAVE.url), true); + assert.deepEqual(id.calls, ['store SUB/WAVE', `arm ${WAVE.url}`, 'announce', 'disarm']); + + const voice = intents({ mounted: true }); + const v = carPicks(voice, now); + await v.car.pick(v.byName('night shift'), true); + assert.deepEqual(voice.calls, ['player tunes in']); + + const prepared = intents({ mounted: true }); + const p = carPicks(prepared, now); + await p.car.pick(p.byId(WAVE.url), false); + assert.deepEqual(prepared.calls, [], 'a prepare loads nothing'); + assert.equal(p.car.playPrepared(), true); + for (let i = 0; i < 10; i++) await Promise.resolve(); + assert.deepEqual(prepared.calls, ['store SUB/WAVE', `arm ${WAVE.url}`, 'announce', 'disarm']); + assert.deepEqual( + [...id.calls, ...voice.calls, ...prepared.calls].filter((c) => c.startsWith('direct')), + [], + ); +}); + +test('a car pick its station refuses is logged with the reason', async () => { + const s = intents({ mounted: true }); + const c = carPicks(s, DEADLINE - CAR_PICK_BUDGET_MS); + 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}`, + ]); +}); diff --git a/service.ts b/service.ts index 735a313..2035b93 100644 --- a/service.ts +++ b/service.ts @@ -2,25 +2,67 @@ // Skip and seek are unavailable on a shared live broadcast. import TrackPlayer, { Event } from 'react-native-track-player'; import { getLastLiveMeta, loadAndPlay } from '@/audio/player'; +import { plog } from '@/hooks/usePlayer'; +import { createCarPicks } from '@/intents/car-picks'; +import { 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. +interface CarPickFlag { + playWhenReady?: boolean; +} + export async function PlaybackService(): Promise { + const carPicks = createCarPicks(plog); + // RemotePlay reloads with a cache-buster to discard the paused buffer, // through the app's player and its stream recovery while that is mounted // (src/lib/remote-play.ts), where a failed load goes to the error backoff. // If a direct load fails, fall back to play. - TrackPlayer.addEventListener(Event.RemotePlay, () => - remotePlay({ + TrackPlayer.addEventListener(Event.RemotePlay, () => { + // A station the car only prepared plays now (src/intents/car-picks.ts). + if (carPicks.playPrepared()) return; + return remotePlay({ hasStream: () => getLastLiveMeta() !== null, reloadLast: async () => { const meta = getLastLiveMeta(); if (meta) await loadAndPlay(meta); }, resume: () => TrackPlayer.play(), - }), - ); - TrackPlayer.addEventListener(Event.RemotePause, () => TrackPlayer.pause()); - TrackPlayer.addEventListener(Event.RemoteStop, () => TrackPlayer.stop()); + }); + }); + TrackPlayer.addEventListener(Event.RemotePause, () => { + carPicks.forget(); + return TrackPlayer.pause(); + }); + TrackPlayer.addEventListener(Event.RemoteStop, () => { + carPicks.forget(); + return TrackPlayer.stop(); + }); + + // Android Auto: a station picked from the car's list (its id is the + // station's base), or asked for by voice. The tune-in Siri uses, so with the + // player mounted it is handed to it (tune-flow.ts); a failure goes to the + // playback log. + TrackPlayer.addEventListener(Event.RemotePlayId, (e) => { + const { id } = e; + const { playWhenReady = true } = e as CarPickFlag; + void carPicks.pick( + { label: `pick ${id}`, tune: (deadline) => tuneIn(id, deadline) }, + playWhenReady, + ); + }); + TrackPlayer.addEventListener(Event.RemotePlaySearch, (e) => { + const { query } = e; + const { playWhenReady = true } = e as CarPickFlag; + void carPicks.pick( + { + label: `search "${query}"`, + tune: (deadline) => tuneInByName(query, deadline), + }, + playWhenReady, + ); + }); // Never settle. On Android this is a headless JS task, and RN fires JS timers // behind a paused activity only while one is running — the feed poll that diff --git a/src/config/StationContext.tsx b/src/config/StationContext.tsx index 4ccea2c..d055349 100644 --- a/src/config/StationContext.tsx +++ b/src/config/StationContext.tsx @@ -7,6 +7,7 @@ import React, { useRef, useState, } from 'react'; +import { setStations as setCarStations } from '../../modules/android-auto'; import { setStations } from '../../modules/app-intents'; import { teardown } from '@/audio/player'; import { createApi, type StationApi } from '@/lib/api'; @@ -170,10 +171,13 @@ export function StationProvider({ children }: { children: React.ReactNode }) { return store.recents.find((r) => r.url === base)?.name ?? null; }, [base, store.recents]); - // Siri, Shortcuts and Spotlight know the saved stations by name, and cannot - // read this store. + // Siri, Shortcuts, Spotlight and Android Auto know the saved stations by + // name, and cannot read this store. useEffect(() => { - if (ready) setStations(base, stationsForSiri(store.recents)); + if (!ready) return; + const stations = stationsForSiri(store.recents); + setStations(base, stations); + setCarStations(base, stations); }, [ready, base, store.recents]); const value = useMemo( diff --git a/src/hooks/usePlayer.ts b/src/hooks/usePlayer.ts index 617e9dd..3ab16ec 100644 --- a/src/hooks/usePlayer.ts +++ b/src/hooks/usePlayer.ts @@ -31,7 +31,8 @@ import { StreamRecovery } from '@/lib/stream-recovery'; import type { StreamFormat } from '@/lib/streamFormat'; import { loadVolumePref, saveVolumePref } from '@/lib/volume'; -function plog(msg: string) { +/** A playback line: redacted into the Share playback log, and printed in dev. */ +export function plog(msg: string) { playbackLog.add(msg); if (__DEV__) console.log(`[player ${new Date().toISOString().slice(11, 23)}] ${msg}`); } diff --git a/src/intents/car-picks.ts b/src/intents/car-picks.ts new file mode 100644 index 0000000..4492398 --- /dev/null +++ b/src/intents/car-picks.ts @@ -0,0 +1,69 @@ +// Android Auto's picks: a station tapped in the car's list, or asked for by +// voice, arriving in service.ts as remote-play-id / remote-play-search. +// +// A pick can be a prepare (playWhenReady false): Android expects that to get +// ready without starting audio, and a live stream has nothing worth loading +// paused, so the pick is held and the next Play tunes in to it instead of +// resuming. Failures land in the playback log, never in silence. +// +// 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. + +import type { IntentReply } from '../../modules/app-intents'; + +/** A car has no Siri reply window to fit: a pick may take as long as a + * tune-in waits for audio. */ +export const CAR_PICK_BUDGET_MS = 10_000; + +export interface CarPick { + /** For the playback log: what was picked. */ + label: string; + /** Tune in, answering by `deadline` (epoch ms). */ + tune(deadline: number): Promise; +} + +export interface CarPicks { + /** A pick from the car. Tunes in now, or holds it when only preparing. */ + pick(pick: CarPick, playWhenReady: boolean): Promise; + /** A Play from the car or a remote. Tunes in to a held pick and returns + * true; false when none is held, for the usual remote Play. */ + playPrepared(): boolean; + /** Pause or stop: a held pick is dropped. */ + forget(): void; +} + +export function createCarPicks(log: (msg: string) => void, now: () => number = Date.now): CarPicks { + let prepared: CarPick | null = null; + + async function run(pick: CarPick): Promise { + 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'}`); + } catch (e) { + log(`car ${pick.label} failed: ${e instanceof Error ? e.message : String(e)}`); + } + } + + return { + pick(pick, playWhenReady) { + if (!playWhenReady) { + prepared = pick; + log(`car ${pick.label} prepared`); + return Promise.resolve(); + } + prepared = null; + return run(pick); + }, + playPrepared() { + const pick = prepared; + if (!pick) return false; + prepared = null; + void run(pick); + return true; + }, + forget() { + prepared = null; + }, + }; +} diff --git a/src/intents/car.ts b/src/intents/car.ts new file mode 100644 index 0000000..a82e480 --- /dev/null +++ b/src/intents/car.ts @@ -0,0 +1,19 @@ +// Android Auto. The car's station list is native (modules/android-auto), and +// it can only connect once the player's media session exists, which needs the +// player set up. When the car connects, including when it launched the app +// with no screen, the browse service runs this task to do that. Picking a +// station or asking for one by voice then arrives in service.ts. + +import { AppRegistry, Platform } from 'react-native'; +import { setupPlayer } from '@/audio/player'; + +// Matched by STRING with modules/android-auto/…/CarConnectTask.kt (npm test checks). +const CAR_CONNECT_TASK = 'SubwaveCarConnect'; + +/** Call once, early, outside the React tree: the car can start the app with + * 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()); +} diff --git a/src/intents/tune-flow.ts b/src/intents/tune-flow.ts index 5ce7b46..b84a1f2 100644 --- a/src/intents/tune-flow.ts +++ b/src/intents/tune-flow.ts @@ -11,7 +11,7 @@ import type { IntentReply } from '../../modules/app-intents'; import { splitStationAddress, type StoredStationRef } from '../lib/station-credentials'; -import { findSavedStation } from '../lib/station-store'; +import { findSavedStation, matchStations, stationsForSiri } from '../lib/station-store'; import { NO_STATION_MESSAGE } from './station-messages'; export const NOT_SAVED_MESSAGE = "That station isn't saved in SUB/WAVE. Add it in the app first."; @@ -85,6 +85,19 @@ export async function tuneIn( ); } +/** A station asked for by name ("Hey Google, play Night Shift on SUB/WAVE"), + * matched as Siri matches one. No name, or none that matches, tunes in to + * the station listened to last. The same routing as tuneIn. */ +export async function tuneInByName( + deps: TuneDeps, + query: string, + deadline: number, +): Promise { + const store = await deps.loadStore(); + const [match] = matchStations(stationsForSiri(store.recents), query); + return tuneIn(deps, match?.id, deadline); +} + /** Through the mounted player when there is one, else directly. */ async function load(deps: TuneDeps, direct: () => Promise): Promise { if (deps.playOnMountedPlayer()) { diff --git a/src/intents/tune.ts b/src/intents/tune.ts index b1f10b3..d582893 100644 --- a/src/intents/tune.ts +++ b/src/intents/tune.ts @@ -74,6 +74,12 @@ 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 { + return flow.tuneInByName(deps, query, deadline); +} + export function tuneOut(): Promise { return flow.tuneOut(deps); } diff --git a/src/lib/station-store.ts b/src/lib/station-store.ts index 38be385..87cc5bb 100644 --- a/src/lib/station-store.ts +++ b/src/lib/station-store.ts @@ -64,3 +64,41 @@ export function stationsForSiri(recents: StoredStationRef[]): MirroredStation[] } return out; } + +/** Stations a spoken term names ("Hey Google, play Night Shift on SUB/WAVE"), + * compared folded because speech arrives as "chill wave radio": an exact name + * first, else a name containing the term or contained in it. A generic word + * names no station, so "play radio" stays on the one listened to last. + * The same rule as Siri's, SavedStations.matching in + * targets/live-activity/_shared/StationEntities.swift: change both + * (npm test checks the generic words and the shortest term). */ +export function matchStations(stations: MirroredStation[], term: string): MirroredStation[] { + const wanted = foldName(term); + if (wanted.length < 3 || GENERIC_TERMS.has(wanted)) return []; + const exact = stations.filter((s) => foldName(s.name) === wanted); + if (exact.length) return exact; + return stations.filter((s) => { + const name = foldName(s.name); + return !!name && (name.includes(wanted) || wanted.includes(name)); + }); +} + +const GENERIC_TERMS = new Set([ + 'radio', + 'theradio', + 'station', + 'mystation', + 'music', + 'somemusic', + 'live', + 'subwave', +]); + +/** Lowercased, accents dropped, letters and digits only. */ +function foldName(text: string): string { + return text + .normalize('NFD') + .replace(/\p{M}/gu, '') + .toLowerCase() + .replace(/[^\p{L}\p{N}]/gu, ''); +}