react-native-audio-browser 1.0.0-next.3 → 1.0.0-next.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/android/src/cast/java/com/audiobrowser/cast/CastSupport.kt +37 -14
  2. package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +19 -8
  3. package/android/src/main/java/com/audiobrowser/Service.kt +6 -41
  4. package/android/src/main/java/com/audiobrowser/browser/BrowserManager.kt +12 -27
  5. package/android/src/main/java/com/audiobrowser/browser/BrowserUrlResolution.kt +6 -5
  6. package/android/src/main/java/com/audiobrowser/browser/JsonModels.kt +12 -7
  7. package/android/src/main/java/com/audiobrowser/extension/QueueIndex.kt +19 -0
  8. package/android/src/main/java/com/audiobrowser/http/HttpClient.kt +2 -1
  9. package/android/src/main/java/com/audiobrowser/http/RequestConfigBuilder.kt +24 -8
  10. package/android/src/main/java/com/audiobrowser/player/MediaFactory.kt +5 -1
  11. package/android/src/main/java/com/audiobrowser/player/MediaSessionCallback.kt +28 -21
  12. package/android/src/main/java/com/audiobrowser/player/Player.kt +33 -27
  13. package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +4 -0
  14. package/android/src/main/java/com/audiobrowser/player/ResolvingOnReloadSource.kt +38 -0
  15. package/android/src/main/java/com/audiobrowser/player/TransformingDataSource.kt +34 -19
  16. package/android/src/main/java/com/audiobrowser/remote/RemotePlayback.kt +10 -1
  17. package/android/src/main/java/com/audiobrowser/remote/RemoteSwitchingPlayer.kt +48 -4
  18. package/android/src/main/java/com/audiobrowser/util/BrowserPathHelper.kt +32 -34
  19. package/android/src/main/java/com/audiobrowser/util/SearchParamsFactory.kt +64 -0
  20. package/android/src/test/java/com/audiobrowser/NavigateTrackTest.kt +116 -0
  21. package/android/src/test/java/com/audiobrowser/TestFixtures.kt +41 -0
  22. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerBuildApiRequestTest.kt +21 -4
  23. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerFavoritesTest.kt +49 -0
  24. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerPageShapeTest.kt +93 -0
  25. package/android/src/test/java/com/audiobrowser/browser/BrowserUrlResolutionTest.kt +12 -0
  26. package/android/src/test/java/com/audiobrowser/browser/JsonArtworkTest.kt +7 -1
  27. package/android/src/test/java/com/audiobrowser/browser/JsonFavoritedTest.kt +34 -0
  28. package/android/src/test/java/com/audiobrowser/browser/JsonStyleTest.kt +6 -6
  29. package/android/src/test/java/com/audiobrowser/extension/QueueIndexTest.kt +44 -0
  30. package/android/src/test/java/com/audiobrowser/http/HttpClientTest.kt +34 -0
  31. package/android/src/test/java/com/audiobrowser/http/RequestConfigBuilderTest.kt +64 -7
  32. package/android/src/test/java/com/audiobrowser/player/FavoriteCapabilityTest.kt +41 -0
  33. package/android/src/test/java/com/audiobrowser/player/MediaFactoryTest.kt +39 -0
  34. package/android/src/test/java/com/audiobrowser/player/MediaUrlReloadTest.kt +212 -0
  35. package/android/src/test/java/com/audiobrowser/player/PlayerSeekSnapshotTest.kt +45 -0
  36. package/android/src/test/java/com/audiobrowser/player/SessionVoiceSearchTest.kt +173 -0
  37. package/android/src/test/java/com/audiobrowser/player/TransformingDataSourceTest.kt +127 -1
  38. package/android/src/test/java/com/audiobrowser/remote/FakeRemote.kt +28 -0
  39. package/android/src/test/java/com/audiobrowser/remote/RemoteSwitchingPlayerTest.kt +116 -0
  40. package/android/src/test/java/com/audiobrowser/util/BrowserPathHelperTest.kt +44 -0
  41. package/android/src/testCast/java/com/audiobrowser/cast/SdkCastRemoteTest.kt +188 -0
  42. package/lib/commonjs/features/playback/controls.js +1 -2
  43. package/lib/commonjs/features/playback/controls.js.map +1 -1
  44. package/lib/module/features/playback/controls.js +1 -2
  45. package/lib/module/features/playback/controls.js.map +1 -1
  46. package/lib/typescript/src/features/playback/controls.d.ts +1 -2
  47. package/lib/typescript/src/features/playback/controls.d.ts.map +1 -1
  48. package/package.json +1 -1
  49. package/src/features/playback/controls.ts +1 -2
  50. package/website/guide/live-streams.md +22 -20
@@ -61,11 +61,17 @@ internal fun createCastRemote(context: Context, receiverApplicationId: String?):
61
61
  return SdkCastRemote(Cast.getSingletonInstance(context), player)
62
62
  }
63
63
 
64
- private class SdkCastRemote(private val cast: Cast, override val player: RemoteCastPlayer) :
64
+ internal class SdkCastRemote(private val cast: Cast, override val player: RemoteCastPlayer) :
65
65
  RemotePlayback {
66
66
  private var listener: RemotePlayback.Listener? = null
67
67
  private var client: RemoteMediaClient? = null
68
68
 
69
+ /**
70
+ * Kept through a suspension, while the receiver plays on out of reach: [player] lets go of its
71
+ * session then as it does at an end, so only the SDK's own end or failed resume clears this.
72
+ */
73
+ private var hasSession = player.isCastSessionAvailable
74
+
69
75
  private val ends = CastEnds()
70
76
 
71
77
  private val statusCallback =
@@ -94,17 +100,20 @@ private class SdkCastRemote(private val cast: Cast, override val player: RemoteC
94
100
 
95
101
  override fun onSessionResumed(session: CastSession, wasSuspended: Boolean) = watch(session)
96
102
 
97
- override fun onSessionEnded(session: CastSession, error: Int) = watch(null)
103
+ override fun onSessionEnded(session: CastSession, error: Int) {
104
+ watch(null)
105
+ sessionGone()
106
+ }
98
107
 
99
108
  override fun onSessionStarting(session: CastSession) = Unit
100
109
 
101
110
  override fun onSessionStartFailed(session: CastSession, error: Int) = Unit
102
111
 
103
- override fun onSessionEnding(session: CastSession) = Unit
112
+ override fun onSessionEnding(session: CastSession) = sessionGone()
104
113
 
105
114
  override fun onSessionResuming(session: CastSession, sessionId: String) = Unit
106
115
 
107
- override fun onSessionResumeFailed(session: CastSession, error: Int) = Unit
116
+ override fun onSessionResumeFailed(session: CastSession, error: Int) = sessionGone()
108
117
 
109
118
  override fun onSessionSuspended(session: CastSession, reason: Int) = Unit
110
119
  }
@@ -112,6 +121,24 @@ private class SdkCastRemote(private val cast: Cast, override val player: RemoteC
112
121
  init {
113
122
  cast.addSessionManagerListener(sessions)
114
123
  watch(cast.currentCastSession)
124
+ player.setSessionAvailabilityListener(
125
+ object : SessionAvailabilityListener {
126
+ override fun onCastSessionAvailable() {
127
+ hasSession = true
128
+ listener?.onSessionChanged()
129
+ }
130
+
131
+ override fun onCastSessionUnavailable() {
132
+ listener?.onSessionChanged()
133
+ }
134
+ }
135
+ )
136
+ }
137
+
138
+ private fun sessionGone() {
139
+ if (!hasSession) return
140
+ hasSession = false
141
+ listener?.onSessionChanged()
115
142
  }
116
143
 
117
144
  private fun watch(session: CastSession?) {
@@ -120,20 +147,16 @@ private class SdkCastRemote(private val cast: Cast, override val player: RemoteC
120
147
  client = session?.remoteMediaClient
121
148
  client?.registerCallback(statusCallback)
122
149
  }
150
+
123
151
  override val isSessionAvailable: Boolean
124
- get() = player.isCastSessionAvailable
152
+ get() = hasSession
153
+
154
+ /** [player] has no client between letting go of the session and taking it up again. */
155
+ override val isSuspended: Boolean
156
+ get() = hasSession && !player.isCastSessionAvailable
125
157
 
126
158
  override fun setListener(listener: RemotePlayback.Listener?) {
127
159
  this.listener = listener
128
- player.setSessionAvailabilityListener(
129
- listener?.let {
130
- object : SessionAvailabilityListener {
131
- override fun onCastSessionAvailable() = it.onSessionChanged()
132
-
133
- override fun onCastSessionUnavailable() = it.onSessionChanged()
134
- }
135
- }
136
- )
137
160
  }
138
161
 
139
162
  override fun release() {
@@ -25,6 +25,7 @@ import com.audiobrowser.browser.handleTrackLoad
25
25
  import com.audiobrowser.browser.resolveMediaUrl
26
26
  import com.audiobrowser.extension.NumberExt.Companion.toSeconds
27
27
  import com.audiobrowser.extension.indexOfTappedTrack
28
+ import com.audiobrowser.extension.toQueueIndex
28
29
  import com.audiobrowser.model.PlayerSetupOptions
29
30
  import com.audiobrowser.model.PlayerUpdateOptions
30
31
  import com.audiobrowser.player.Player
@@ -573,6 +574,10 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
573
574
  navigationJob?.cancel()
574
575
 
575
576
  val path = track.path
577
+ val playAlone: suspend () -> Unit = {
578
+ player.load(track)
579
+ player.play()
580
+ }
576
581
  navigationJob =
577
582
  mainScope.launch {
578
583
  try {
@@ -633,7 +638,7 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
633
638
  0.0,
634
639
  startPosition = null,
635
640
  intercepted = {},
636
- defaultBehavior = { player.load(track) },
641
+ defaultBehavior = playAlone,
637
642
  )
638
643
  }
639
644
  }
@@ -650,7 +655,7 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
650
655
  0.0,
651
656
  startPosition = null,
652
657
  intercepted = {},
653
- defaultBehavior = { player.load(track) },
658
+ defaultBehavior = playAlone,
654
659
  )
655
660
  }
656
661
  else -> {
@@ -935,16 +940,18 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
935
940
 
936
941
  override fun add(tracks: Array<Track>, insertBeforeIndex: Double?) =
937
942
  commandPlayer("add") { player ->
938
- val inputIndex = insertBeforeIndex?.toInt() ?: -1
943
+ val inputIndex = insertBeforeIndex?.toQueueIndex() ?: -1
939
944
  player.add(tracks, inputIndex)
940
945
  }
941
946
 
942
947
  override fun move(fromIndex: Double, toIndex: Double) =
943
- commandPlayer("move") { player -> player.move(fromIndex.toInt(), toIndex.toInt()) }
948
+ commandPlayer("move") { player ->
949
+ player.move(fromIndex.toQueueIndex(), toIndex.toQueueIndex())
950
+ }
944
951
 
945
952
  override fun remove(indexes: DoubleArray) =
946
953
  commandPlayer("remove") { player ->
947
- val indexList = indexes.map { it.toInt() }
954
+ val indexList = indexes.map { it.toQueueIndex() }
948
955
  player.remove(indexList)
949
956
  }
950
957
 
@@ -953,7 +960,7 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
953
960
 
954
961
  override fun skip(index: Double, initialPosition: Double?) =
955
962
  commandPlayer("skip") { player ->
956
- player.skipTo(index.toInt())
963
+ player.skipTo(index.toQueueIndex())
957
964
 
958
965
  if (initialPosition != null && initialPosition >= 0) {
959
966
  player.seekTo((initialPosition * 1000).toLong(), TimeUnit.MILLISECONDS)
@@ -980,7 +987,11 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
980
987
 
981
988
  override fun setQueue(tracks: Array<Track>, startIndex: Double?, startPosition: Double?) =
982
989
  commandPlayer("setQueue") { player ->
983
- player.setQueue(tracks, startIndex?.toInt() ?: 0, ((startPosition ?: 0.0) * 1000).toLong())
990
+ player.setQueue(
991
+ tracks,
992
+ startIndex?.toQueueIndex() ?: 0,
993
+ ((startPosition ?: 0.0) * 1000).toLong(),
994
+ )
984
995
  }
985
996
 
986
997
  override fun setActiveTrackFavorited(favorited: Boolean): Unit =
@@ -999,7 +1010,7 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
999
1010
  override fun getTrack(index: Double): Track? =
1000
1011
  readPlayer(null) { player ->
1001
1012
  try {
1002
- player.getTrack(index.toInt())
1013
+ player.getTrack(index.toQueueIndex())
1003
1014
  } catch (e: IllegalArgumentException) {
1004
1015
  null
1005
1016
  }
@@ -8,7 +8,6 @@ import android.content.ServiceConnection
8
8
  import android.content.pm.PackageManager
9
9
  import android.os.Binder
10
10
  import android.os.IBinder
11
- import android.provider.MediaStore
12
11
  import android.util.Log
13
12
  import androidx.annotation.MainThread
14
13
  import androidx.annotation.OptIn
@@ -29,10 +28,8 @@ import com.audiobrowser.util.BatteryWarningStore
29
28
  import com.audiobrowser.util.CoilArtworkLoader
30
29
  import com.audiobrowser.util.CoilArtworkLoaderHolder
31
30
  import com.audiobrowser.util.CoilBitmapLoader
31
+ import com.audiobrowser.util.SearchParamsFactory
32
32
  import com.margelo.nitro.audiobrowser.AppKilledPlaybackBehavior
33
- import com.margelo.nitro.audiobrowser.MediaReference
34
- import com.margelo.nitro.audiobrowser.SearchMode
35
- import com.margelo.nitro.audiobrowser.SearchParams
36
33
  import kotlinx.coroutines.CoroutineScope
37
34
  import kotlinx.coroutines.Dispatchers
38
35
  import kotlinx.coroutines.MainScope
@@ -188,7 +185,11 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
188
185
  intent
189
186
  ?.takeIf { it.action == "android.media.action.MEDIA_PLAY_FROM_SEARCH" }
190
187
  ?.let { searchIntent ->
191
- val searchParams = parseSearchIntent(searchIntent)
188
+ val searchParams =
189
+ SearchParamsFactory.fromPlayFromSearch(
190
+ searchIntent.getStringExtra(SearchManager.QUERY) ?: "",
191
+ searchIntent.extras,
192
+ )
192
193
  Timber.d("MEDIA_PLAY_FROM_SEARCH intent received: $searchParams")
193
194
  // A search that plays has waited for AudioBrowser, whose MediaBrowser connecting hands
194
195
  // the notification to Media3.
@@ -202,42 +203,6 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
202
203
  return super.onStartCommand(intent, flags, startId)
203
204
  }
204
205
 
205
- /** See https://developer.android.com/guide/components/intents-common#PlaySearch */
206
- private fun parseSearchIntent(intent: Intent): SearchParams {
207
- val query = intent.getStringExtra(SearchManager.QUERY) ?: ""
208
-
209
- val mediaFocus = intent.getStringExtra(MediaStore.EXTRA_MEDIA_FOCUS)
210
-
211
- // The focus picks a vertical. Genre, artist and album focuses are filters, carried by the
212
- // extras
213
- // below, so they yield no mode. Android has no station or podcast focus: those verticals are
214
- // iOS-only.
215
- val mode =
216
- when (mediaFocus) {
217
- "vnd.android.cursor.item/*" -> if (query.isEmpty()) SearchMode.ANY else null
218
- "vnd.android.cursor.item/audio" -> SearchMode.SONG
219
- MediaStore.Audio.Playlists.ENTRY_CONTENT_TYPE -> SearchMode.PLAYLIST
220
- else -> null
221
- }
222
-
223
- val genre = intent.getStringExtra("android.intent.extra.genre")
224
- val artist = intent.getStringExtra(MediaStore.EXTRA_MEDIA_ARTIST)
225
- val album = intent.getStringExtra(MediaStore.EXTRA_MEDIA_ALBUM)
226
- val title = intent.getStringExtra(MediaStore.EXTRA_MEDIA_TITLE)
227
- val playlist = intent.getStringExtra("android.intent.extra.playlist")
228
-
229
- return SearchParams(
230
- mode = mode,
231
- query = query,
232
- genre = genre,
233
- artist = artist,
234
- album = album,
235
- title = title,
236
- playlist = playlist,
237
- reference = MediaReference.UNKNOWN,
238
- )
239
- }
240
-
241
206
  override fun onBind(intent: Intent?): IBinder? {
242
207
  Timber.d("action: ${intent?.action}, package: ${intent?.`package`}")
243
208
  return if (intent?.action != null) {
@@ -9,6 +9,7 @@ import com.audiobrowser.http.HttpClient
9
9
  import com.audiobrowser.http.RequestConfigBuilder
10
10
  import com.audiobrowser.util.BrowserPathHelper
11
11
  import com.audiobrowser.util.FALLBACK_TIMEOUT
12
+ import com.audiobrowser.util.SearchParamsFactory
12
13
  import com.audiobrowser.util.TrackFactory
13
14
  import com.audiobrowser.util.artworkOf
14
15
  import com.audiobrowser.util.awaitCancellable
@@ -35,6 +36,7 @@ import kotlinx.coroutines.async
35
36
  import kotlinx.coroutines.awaitAll
36
37
  import kotlinx.coroutines.coroutineScope
37
38
  import kotlinx.coroutines.withContext
39
+ import kotlinx.serialization.SerializationException
38
40
  import kotlinx.serialization.json.Json
39
41
  import timber.log.Timber
40
42
 
@@ -746,18 +748,7 @@ class BrowserManager {
746
748
  }
747
749
 
748
750
  suspend fun searchPlayable(query: String): Array<Track>? {
749
- return searchPlayable(
750
- SearchParams(
751
- query = query,
752
- mode = null,
753
- genre = null,
754
- artist = null,
755
- album = null,
756
- title = null,
757
- playlist = null,
758
- reference = MediaReference.UNKNOWN,
759
- )
760
- )
751
+ return searchPlayable(SearchParamsFactory.fromQuery(query))
761
752
  }
762
753
 
763
754
  /**
@@ -794,18 +785,7 @@ class BrowserManager {
794
785
  }
795
786
 
796
787
  suspend fun search(query: String): ResolvedTrack {
797
- return search(
798
- SearchParams(
799
- query = query,
800
- mode = null,
801
- genre = null,
802
- artist = null,
803
- album = null,
804
- title = null,
805
- playlist = null,
806
- reference = MediaReference.UNKNOWN,
807
- )
808
- )
788
+ return search(SearchParamsFactory.fromQuery(query))
809
789
  }
810
790
 
811
791
  /**
@@ -1157,7 +1137,12 @@ class BrowserManager {
1157
1137
  if (httpResponse.isSuccessful) {
1158
1138
  val jsonResolvedTrack =
1159
1139
  try {
1160
- json.decodeFromString<JsonResolvedTrack>(httpResponse.body)
1140
+ json.decodeFromString<JsonResolvedTrack>(httpResponse.body).also {
1141
+ // A browse page needs its title (BrowserSource); the tabs page does not.
1142
+ if (it.title == null && path != TABS_ROUTE_PATH) {
1143
+ throw SerializationException("Field 'title' is required for a browse page")
1144
+ }
1145
+ }
1161
1146
  } catch (e: Exception) {
1162
1147
  throw HttpStatusException(
1163
1148
  httpResponse.code,
@@ -1165,7 +1150,7 @@ class BrowserManager {
1165
1150
  e,
1166
1151
  )
1167
1152
  }
1168
- jsonResolvedTrack.toNitro()
1153
+ jsonResolvedTrack.toNitro(requestedPath = path)
1169
1154
  } else {
1170
1155
  Timber.w(
1171
1156
  "HTTP request failed with status ${httpResponse.code} for ${httpRequest.url}: ${httpResponse.body}"
@@ -1244,7 +1229,7 @@ class HttpStatusException(val statusCode: Int, message: String, cause: Throwable
1244
1229
 
1245
1230
  class NetworkException(message: String, cause: Throwable? = null) : Exception(message, cause)
1246
1231
 
1247
- class CallbackException(message: String) : Exception(message)
1232
+ class CallbackException(message: String, cause: Throwable? = null) : Exception(message, cause)
1248
1233
 
1249
1234
  /** Mirrors NativeBrowserConfiguration from JS. */
1250
1235
  data class BrowserConfig(
@@ -38,10 +38,10 @@ suspend fun BrowserManager.resolveMediaUrl(originalUrl: String, track: Track): M
38
38
  contentType = null,
39
39
  userAgent = null,
40
40
  )
41
- requestConfig?.let { base = RequestConfigBuilder.mergeConfig(base, it) }
41
+ requestConfig?.let { base = RequestConfigBuilder.mergeConfigOrBase(base, it) }
42
42
  val mediaLayered =
43
43
  if (mediaConfig != null) {
44
- RequestConfigBuilder.mergeConfig(base, mediaConfig)
44
+ RequestConfigBuilder.mergeConfigOrBase(base, mediaConfig)
45
45
  } else {
46
46
  MediaRequestConfig(
47
47
  resolve = null,
@@ -95,7 +95,7 @@ suspend fun BrowserManager.resolveArtworkUrl(
95
95
  userAgent = null,
96
96
  )
97
97
  resolvedRequestConfig()?.let {
98
- mergedConfig = RequestConfigBuilder.mergeConfig(mergedConfig, it, emptyMap())
98
+ mergedConfig = RequestConfigBuilder.mergeConfigOrBase(mergedConfig, it, emptyMap())
99
99
  }
100
100
  if (trackArtwork != null) {
101
101
  mergedConfig = mergedConfig.copy(path = trackArtwork)
@@ -259,10 +259,11 @@ private fun buildHeadersMap(
259
259
  ): Map<String, String>? {
260
260
  val mergedHeaders = mutableMapOf<String, String>()
261
261
  headers?.let { mergedHeaders.putAll(it) }
262
- if (userAgent != null && !mergedHeaders.containsKey("User-Agent")) {
262
+ fun hasHeader(name: String) = mergedHeaders.keys.any { it.equals(name, ignoreCase = true) }
263
+ if (userAgent != null && !hasHeader("User-Agent")) {
263
264
  mergedHeaders["User-Agent"] = userAgent
264
265
  }
265
- if (contentType != null && !mergedHeaders.containsKey("Content-Type")) {
266
+ if (contentType != null && !hasHeader("Content-Type")) {
266
267
  mergedHeaders["Content-Type"] = contentType
267
268
  }
268
269
  return mergedHeaders.ifEmpty { null }
@@ -40,8 +40,8 @@ data class JsonSection(
40
40
  @Serializable
41
41
  data class JsonResolvedTrack(
42
42
  val id: String? = null,
43
- val path: String,
44
- val title: String,
43
+ val path: String? = null,
44
+ val title: String? = null,
45
45
  val subtitle: String? = null,
46
46
  val icon: String? = null,
47
47
  val artwork: JsonArtwork? = null,
@@ -56,6 +56,7 @@ data class JsonResolvedTrack(
56
56
  val src: String? = null,
57
57
  val style: JsonElement? = null,
58
58
  val disabled: Boolean? = null,
59
+ val favorited: Boolean? = null,
59
60
  val live: Boolean? = null,
60
61
  val icyCharset: String? = null,
61
62
  val carPlaySiriListButton: String? = null,
@@ -79,6 +80,7 @@ data class JsonTrack(
79
80
  val request: JsonTrackRequest? = null,
80
81
  val style: JsonElement? = null,
81
82
  val disabled: Boolean? = null,
83
+ val favorited: Boolean? = null,
82
84
  val live: Boolean? = null,
83
85
  val icyCharset: String? = null,
84
86
  )
@@ -140,14 +142,17 @@ fun JsonSection.toNitro(): Section {
140
142
  )
141
143
  }
142
144
 
143
- fun JsonResolvedTrack.toNitro(): ResolvedTrack {
145
+ /**
146
+ * The page, with [requestedPath] as its path when it has none and an empty title when it has none.
147
+ */
148
+ fun JsonResolvedTrack.toNitro(requestedPath: String): ResolvedTrack {
144
149
  return ResolvedTrack(
145
150
  id = id,
146
- path = path,
151
+ path = path ?: requestedPath,
147
152
  sections = sections?.map { it.toNitro() }?.toTypedArray(),
148
153
  children = children?.map { it.toNitro() }?.toTypedArray(),
149
154
  carPlaySiriListButton = carPlaySiriListButton.toCarPlaySiriListButtonPosition(),
150
- title = title,
155
+ title = title ?: "",
151
156
  subtitle = subtitle,
152
157
  artwork = artwork?.toNitro(),
153
158
  artworkSource = null,
@@ -162,7 +167,7 @@ fun JsonResolvedTrack.toNitro(): ResolvedTrack {
162
167
  src = src,
163
168
  style = style.toSectionStyle(),
164
169
  disabled = disabled,
165
- favorited = null,
170
+ favorited = favorited,
166
171
  live = live,
167
172
  icyCharset = icyCharset,
168
173
  )
@@ -186,7 +191,7 @@ fun JsonTrack.toNitro(): Track {
186
191
  src = src,
187
192
  style = style.toTrackStyle(),
188
193
  disabled = disabled,
189
- favorited = null,
194
+ favorited = favorited,
190
195
  live = live,
191
196
  icyCharset = icyCharset,
192
197
  )
@@ -0,0 +1,19 @@
1
+ package com.audiobrowser.extension
2
+
3
+ import kotlin.math.truncate
4
+
5
+ /**
6
+ * The queue index a JS number names, its fraction dropped.
7
+ *
8
+ * @throws IllegalArgumentException for a number no `Int` holds: NaN, infinite, or beyond `Int`'s
9
+ * range.
10
+ */
11
+ fun Double.toQueueIndex(): Int {
12
+ val whole = truncate(this)
13
+ if (whole.isNaN() || whole < Int.MIN_VALUE || whole > Int.MAX_VALUE) {
14
+ throw IllegalArgumentException(
15
+ "Invalid track index: index must be a finite number within the range of Int, got $this"
16
+ )
17
+ }
18
+ return whole.toInt()
19
+ }
@@ -88,7 +88,8 @@ class HttpClient {
88
88
  Headers.Builder()
89
89
  .apply {
90
90
  httpRequest.headers?.forEach { (name, value) -> add(name, value) }
91
- add("User-Agent", httpRequest.userAgent)
91
+ // A `User-Agent` header in any case wins over `userAgent`.
92
+ if (get("User-Agent") == null) add("User-Agent", httpRequest.userAgent)
92
93
  }
93
94
  .build()
94
95
  requestBuilder.headers(headers)
@@ -1,5 +1,6 @@
1
1
  package com.audiobrowser.http
2
2
 
3
+ import com.audiobrowser.browser.CallbackException
3
4
  import com.audiobrowser.util.BrowserPathHelper
4
5
  import com.audiobrowser.util.awaitCancellable
5
6
  import com.audiobrowser.util.awaitNested
@@ -92,8 +93,9 @@ object RequestConfigBuilder {
92
93
  /**
93
94
  * Applies [override] as a Request-Config Layer (GLOSSARY.md): its transforms, async then sync,
94
95
  * replace the config and its static fields are then ignored; without one, its static fields merge
95
- * over [base] except `path`, which stays the base's. Mirrors iOS `applyLayer`. A transform that
96
- * throws yields [base].
96
+ * over [base] except `path`, which stays the base's. Mirrors iOS `applyLayer`.
97
+ *
98
+ * @throws CallbackException when a transform throws
97
99
  */
98
100
  suspend fun mergeConfig(
99
101
  base: RequestConfig,
@@ -111,21 +113,35 @@ object RequestConfigBuilder {
111
113
  } catch (e: CancellationException) {
112
114
  throw e
113
115
  } catch (e: Exception) {
114
- Timber.e(e, "Failed to apply transform function, using base config")
115
- base
116
+ // A JS call that throws reaches here as JSError's `what()`, `message\n\nstack`.
117
+ throw CallbackException(e.message?.substringBefore("\n\n") ?: e.toString(), e)
116
118
  }
117
119
  }
118
120
 
119
121
  /**
120
- * The layer rule of the [TransformableRequestConfig] overload, keeping [override]'s resolve
121
- * callbacks.
122
+ * [mergeConfig] for media and artwork, where a throwing transform costs its own layer and not the
123
+ * stack: the layers under it stand, so a relative path still gets the shared `baseUrl` and a
124
+ * media request keeps the shared credential.
122
125
  */
123
- suspend fun mergeConfig(
126
+ suspend fun mergeConfigOrBase(
127
+ base: RequestConfig,
128
+ override: TransformableRequestConfig,
129
+ routeParams: Map<String, String>? = null,
130
+ ): RequestConfig =
131
+ try {
132
+ mergeConfig(base, override, routeParams)
133
+ } catch (e: CallbackException) {
134
+ Timber.e(e.cause, "Failed to apply transform function, using base config")
135
+ base
136
+ }
137
+
138
+ /** The layer rule of [mergeConfigOrBase], keeping [override]'s resolve callbacks. */
139
+ suspend fun mergeConfigOrBase(
124
140
  base: RequestConfig,
125
141
  override: MediaRequestConfig,
126
142
  routeParams: Map<String, String>? = null,
127
143
  ): MediaRequestConfig =
128
- override.withRequestFields(mergeConfig(base, override.asTransformable(), routeParams))
144
+ override.withRequestFields(mergeConfigOrBase(base, override.asTransformable(), routeParams))
129
145
 
130
146
  private fun MediaRequestConfig.asTransformable() =
131
147
  TransformableRequestConfig(
@@ -135,7 +135,11 @@ class MediaFactory(
135
135
  factory.setLoadErrorHandlingPolicy(
136
136
  RetryLoadErrorHandlingPolicy(sources, { isCurrent(mediaItem) }, cache, onLoadFailure)
137
137
  )
138
- val source = factory.setDataSourceFactory(dataSourceFactory).createMediaSource(mediaItem)
138
+ val source =
139
+ ResolvingOnReloadSource(
140
+ factory.setDataSourceFactory(dataSourceFactory).createMediaSource(mediaItem),
141
+ transformingFactory,
142
+ )
139
143
  // Adaptive sources retry in place: the policy never ends their connection.
140
144
  return if (retrying && sources != RetryLoadErrorHandlingPolicy.Sources.ADAPTIVE)
141
145
  ConnectionEndSource(source)
@@ -24,6 +24,7 @@ import com.audiobrowser.navigationErrorFor
24
24
  import com.audiobrowser.util.Automotive
25
25
  import com.audiobrowser.util.BrowserPathHelper
26
26
  import com.audiobrowser.util.RatingFavorites
27
+ import com.audiobrowser.util.SearchParamsFactory
27
28
  import com.audiobrowser.util.TrackFactory
28
29
  import com.audiobrowser.util.isAutomotive
29
30
  import com.google.common.collect.ImmutableList
@@ -34,13 +35,11 @@ import com.margelo.nitro.audiobrowser.FormattedNavigationError
34
35
  import com.margelo.nitro.audiobrowser.Gate
35
36
  import com.margelo.nitro.audiobrowser.GateEvent
36
37
  import com.margelo.nitro.audiobrowser.GateReason
37
- import com.margelo.nitro.audiobrowser.MediaReference
38
38
  import com.margelo.nitro.audiobrowser.NativeGateRequest
39
39
  import com.margelo.nitro.audiobrowser.NavigationError
40
40
  import com.margelo.nitro.audiobrowser.NavigationErrorType
41
41
  import com.margelo.nitro.audiobrowser.PlayerCapabilities
42
42
  import com.margelo.nitro.audiobrowser.RemoteButtonLayout
43
- import com.margelo.nitro.audiobrowser.SearchParams
44
43
  import com.margelo.nitro.audiobrowser.Section
45
44
  import com.margelo.nitro.audiobrowser.Track
46
45
  import kotlinx.coroutines.CancellationException
@@ -56,9 +55,9 @@ import timber.log.Timber
56
55
 
57
56
  /**
58
57
  * Everything the MediaLibrarySession serves except transport, which reaches the player through
59
- * [InterceptingPlayer]; Assistant's play-from-search arrives as an intent in the service. Callbacks
60
- * answering through [scope] run on IO, so anything touching ExoPlayer hops to [Dispatchers.Main];
61
- * the rest answer on the Media3 application thread.
58
+ * [InterceptingPlayer]. Play-from-search arrives here as a set of one item that has only a query,
59
+ * and as an intent in the service. Callbacks answering through [scope] run on IO, so anything
60
+ * touching ExoPlayer hops to [Dispatchers.Main]; the rest answer on the Media3 application thread.
62
61
  */
63
62
  class MediaSessionCallback(private val player: Player) :
64
63
  MediaLibraryService.MediaLibrarySession.Callback {
@@ -96,19 +95,6 @@ class MediaSessionCallback(private val player: Player) :
96
95
  }
97
96
  }
98
97
 
99
- // Car search surfaces give free text only. Mirrors BrowserManager's query→SearchParams.
100
- private fun searchParams(query: String): SearchParams =
101
- SearchParams(
102
- mode = null,
103
- query = query,
104
- genre = null,
105
- artist = null,
106
- album = null,
107
- title = null,
108
- playlist = null,
109
- reference = MediaReference.UNKNOWN,
110
- )
111
-
112
98
  private fun createGateMediaItem(gate: Gate): MediaItem =
113
99
  createErrorMediaItem(
114
100
  BrowserPathHelper.GATE_PATH,
@@ -614,7 +600,11 @@ class MediaSessionCallback(private val player: Player) :
614
600
 
615
601
  val searchOutcome =
616
602
  audioBrowser.gateDecision(
617
- NativeGateRequest(reason = GateReason.SEARCH, path = null, search = searchParams(query))
603
+ NativeGateRequest(
604
+ reason = GateReason.SEARCH,
605
+ path = null,
606
+ search = SearchParamsFactory.fromQuery(query),
607
+ )
618
608
  )
619
609
  // Search is gated with the browse tree, or it would route around the gate. One result: the
620
610
  // gate tile (see onGetSearchResult).
@@ -721,7 +711,11 @@ class MediaSessionCallback(private val player: Player) :
721
711
 
722
712
  val searchOutcome =
723
713
  audioBrowser.gateDecision(
724
- NativeGateRequest(reason = GateReason.SEARCH, path = null, search = searchParams(query))
714
+ NativeGateRequest(
715
+ reason = GateReason.SEARCH,
716
+ path = null,
717
+ search = SearchParamsFactory.fromQuery(query),
718
+ )
725
719
  )
726
720
  // The one result onSearch announced for a gated search.
727
721
  if (searchOutcome.gated) {
@@ -860,8 +854,21 @@ class MediaSessionCallback(private val player: Player) :
860
854
  }
861
855
  }
862
856
 
857
+ val voiceSearch = mediaItems.singleOrNull()?.let { SearchParamsFactory.voiceSearchOf(it) }
863
858
  val result =
864
- browserManager.resolveMediaItemsForPlayback(mediaItems, startIndex, startPositionMs)
859
+ if (voiceSearch != null) {
860
+ // A failed future leaves current playback untouched.
861
+ val found =
862
+ player.voiceSearch(voiceSearch)
863
+ ?: throw IllegalStateException("Voice search gated or without a playable result")
864
+ MediaSession.MediaItemsWithStartPosition(
865
+ found.map { TrackFactory.toMedia3(it) },
866
+ 0,
867
+ startPositionMs,
868
+ )
869
+ } else {
870
+ browserManager.resolveMediaItemsForPlayback(mediaItems, startIndex, startPositionMs)
871
+ }
865
872
 
866
873
  val tracks = result.mediaItems.map { TrackFactory.fromMedia3(it) }.toTypedArray()
867
874
  // setQueue reads an unset index as "keep the current one". Media3 still gets it unset on the