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
@@ -278,6 +278,8 @@ internal constructor(
278
278
  browserRegistered = CompletableDeferred()
279
279
  }
280
280
  field = value
281
+ // Covers a browser assigned after its options were applied.
282
+ value?.browserManager?.setFavoriteEnabled(options.capabilities.favoriteEnabled)
281
283
  }
282
284
 
283
285
  /**
@@ -1120,33 +1122,11 @@ internal constructor(
1120
1122
  */
1121
1123
  suspend fun playFromSearch(params: SearchParams): Boolean {
1122
1124
  return try {
1123
- val audioBrowser = awaitBrowser()
1124
- // Gated like browsing, or voice search would be a way around the gate.
1125
- val gateOutcome =
1126
- audioBrowser.gateDecision(
1127
- NativeGateRequest(reason = GateReason.SEARCH, path = null, search = params)
1128
- )
1129
- if (gateOutcome.gated) {
1130
- Timber.i("playFromSearch refused — request is gated")
1131
- audioBrowser.onGate(GateEvent(GateReason.SEARCH))
1132
- return false
1133
- }
1134
- val browserManager = audioBrowser.browserManager
1135
-
1136
- Timber.d(
1137
- "Executing voice search: mode=${params.mode}, query='${params.query}', artist='${params.artist}', album='${params.album}'"
1138
- )
1139
- val tracks = browserManager.searchPlayable(params)
1140
-
1141
- if (tracks != null && tracks.isNotEmpty()) {
1142
- Timber.d("Found ${tracks.size} track(s), playing first: ${tracks[0].title}")
1143
- setQueue(tracks)
1144
- play()
1145
- true
1146
- } else {
1147
- Timber.w("No tracks found for search: ${params}")
1148
- false
1149
- }
1125
+ val tracks = voiceSearch(params) ?: return false
1126
+ Timber.d("Found ${tracks.size} track(s), playing first: ${tracks[0].title}")
1127
+ setQueue(tracks)
1128
+ play()
1129
+ true
1150
1130
  } catch (e: Exception) {
1151
1131
  currentCoroutineContext().ensureActive()
1152
1132
  Timber.e(e, "Error handling voice search: ${params}")
@@ -1154,6 +1134,32 @@ internal constructor(
1154
1134
  }
1155
1135
  }
1156
1136
 
1137
+ /**
1138
+ * The playable results of a voice search, from the first. Gated like browsing, or voice search
1139
+ * would be a way around the gate.
1140
+ *
1141
+ * @return null when gated (after onGate) or when nothing playable is found
1142
+ * @throws Exception when the browser is not registered in time or the search callback fails
1143
+ */
1144
+ suspend fun voiceSearch(params: SearchParams): Array<Track>? {
1145
+ val audioBrowser = awaitBrowser()
1146
+ val gateOutcome =
1147
+ audioBrowser.gateDecision(
1148
+ NativeGateRequest(reason = GateReason.SEARCH, path = null, search = params)
1149
+ )
1150
+ if (gateOutcome.gated) {
1151
+ Timber.i("Voice search refused: request is gated")
1152
+ audioBrowser.onGate(GateEvent(GateReason.SEARCH))
1153
+ return null
1154
+ }
1155
+ Timber.d(
1156
+ "Executing voice search: mode=${params.mode}, query='${params.query}', artist='${params.artist}', album='${params.album}'"
1157
+ )
1158
+ return audioBrowser.browserManager.searchPlayable(params).also {
1159
+ if (it == null) Timber.w("No tracks found for search: ${params}")
1160
+ }
1161
+ }
1162
+
1157
1163
  /** An ended queue stays ended, as on an ended engine. */
1158
1164
  fun prepare() {
1159
1165
  if (liveStreamParked) return
@@ -87,6 +87,10 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
87
87
  player.dropFailureReports()
88
88
  }
89
89
  }
90
+ // The periodic save runs only while set to play.
91
+ if (reason == MediaPlayer.DISCONTINUITY_REASON_SEEK && !player.playWhenReady) {
92
+ player.playbackStateStore.save()
93
+ }
90
94
  }
91
95
 
92
96
  override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
@@ -0,0 +1,38 @@
1
+ package com.audiobrowser.player
2
+
3
+ import androidx.media3.exoplayer.source.MediaPeriod
4
+ import androidx.media3.exoplayer.source.MediaSource
5
+ import androidx.media3.exoplayer.source.WrappingMediaSource
6
+ import androidx.media3.exoplayer.upstream.Allocator
7
+
8
+ /**
9
+ * Has the track's media URL resolved afresh on each reload of [source]: each time the engine
10
+ * prepares it (a stop or an error releases it), and each period after the first, since the engine
11
+ * keeps a queue item's source prepared while others play (a skip back to it, a repeat).
12
+ */
13
+ class ResolvingOnReloadSource(
14
+ source: MediaSource,
15
+ private val urls: TransformingDataSource.Factory,
16
+ ) : WrappingMediaSource(source) {
17
+
18
+ /** Whether a period was created since the last preparation; read on the playback thread only. */
19
+ private var periodCreated = false
20
+
21
+ override fun prepareSourceInternal() {
22
+ periodCreated = false
23
+ urls.resolveOnNextMediaOpen = true
24
+ super.prepareSourceInternal()
25
+ }
26
+
27
+ override fun createPeriod(
28
+ id: MediaSource.MediaPeriodId,
29
+ allocator: Allocator,
30
+ startPositionUs: Long,
31
+ ): MediaPeriod {
32
+ // Not on the first: an HLS source has opened its playlist before it, which marking again would
33
+ // resolve twice.
34
+ if (periodCreated) urls.resolveOnNextMediaOpen = true
35
+ periodCreated = true
36
+ return super.createPeriod(id, allocator, startPositionUs)
37
+ }
38
+ }
@@ -17,8 +17,10 @@ import timber.log.Timber
17
17
  * `createMediaSource`, deadlocks while a synchronous Nitro call such as `seekTo` holds the JS
18
18
  * thread.
19
19
  *
20
- * The first open resolves the media URL and caches the result on the [Factory]; later opens of
21
- * other URLs (HLS segments, keys) keep their own URL and reuse the cached headers and user agent.
20
+ * The first open resolves the media URL and caches the result on the [Factory]. A later open of the
21
+ * media URL (a seek, a playlist refresh) reuses it, unless the track reloaded or the last open or
22
+ * read of it failed: the URL or its token may have expired. Opens of other URLs (HLS segments,
23
+ * keys) keep their own URL and reuse the cached headers and user agent.
22
24
  */
23
25
  class TransformingDataSource(private val upstream: DataSource, private val factory: Factory) :
24
26
  DataSource {
@@ -44,6 +46,8 @@ class TransformingDataSource(private val upstream: DataSource, private val facto
44
46
 
45
47
  private var resolvedUri: Uri? = null
46
48
 
49
+ private var openedMediaUrl = false
50
+
47
51
  override fun open(dataSpec: DataSpec): Long {
48
52
  val originalUrl = dataSpec.uri.toString()
49
53
 
@@ -51,16 +55,10 @@ class TransformingDataSource(private val upstream: DataSource, private val facto
51
55
  val (finalUrl, headers, userAgent) =
52
56
  when {
53
57
  cached == null -> resolveAndCache(originalUrl)
54
- // Re-open of the media URL (a retry) reuses the resolved URL: the original may be
55
- // schemeless ("/listen/<id>/x.mp3"), which DefaultDataSource routes to a file and fails.
56
- // After a failed load it re-resolves once instead, since the URL or token may have expired.
58
+ // The resolved URL, never the original: that may be schemeless ("/listen/<id>/x.mp3"),
59
+ // which DefaultDataSource routes to a file and fails.
57
60
  originalUrl == factory.cachedOriginalUrl ->
58
- if (factory.reresolveOnNextMediaOpen) {
59
- factory.reresolveOnNextMediaOpen = false
60
- resolveAndCache(originalUrl)
61
- } else {
62
- cached
63
- }
61
+ if (factory.resolveOnNextMediaOpen) resolveAndCache(originalUrl) else cached
64
62
  // An already-absolute segment or key URL: keep it, reuse the headers.
65
63
  else -> Triple(originalUrl, cached.second, cached.third)
66
64
  }
@@ -68,9 +66,11 @@ class TransformingDataSource(private val upstream: DataSource, private val facto
68
66
  val requestHeaders = buildMap {
69
67
  putAll(dataSpec.httpRequestHeaders)
70
68
  putAll(headers)
71
- if (userAgent != DEFAULT_USER_AGENT) {
72
- put("User-Agent", userAgent)
73
- }
69
+ val headerAgent =
70
+ keys.filter { it.equals("User-Agent", ignoreCase = true) }.map { remove(it) }.lastOrNull()
71
+ // Under this exact name, so it replaces MediaFactory's default rather than sitting beside it.
72
+ val agent = if (userAgent != DEFAULT_USER_AGENT) userAgent else headerAgent
73
+ agent?.let { put("User-Agent", it) }
74
74
  }
75
75
  val mergedHeaders =
76
76
  if (wantsOpenEndedRange(dataSpec, requestHeaders)) {
@@ -83,18 +83,20 @@ class TransformingDataSource(private val upstream: DataSource, private val facto
83
83
  dataSpec.buildUpon().setUri(finalUrl.toUri()).setHttpRequestHeaders(mergedHeaders).build()
84
84
 
85
85
  resolvedUri = transformedSpec.uri
86
+ openedMediaUrl = originalUrl == factory.cachedOriginalUrl
86
87
  return try {
87
88
  upstream.open(transformedSpec)
88
89
  } catch (e: IOException) {
89
90
  // Only a media-URL failure refreshes the URL; a failed segment or key leaves it alone.
90
- if (originalUrl == factory.cachedOriginalUrl) {
91
- factory.reresolveOnNextMediaOpen = true
91
+ if (openedMediaUrl) {
92
+ factory.resolveOnNextMediaOpen = true
92
93
  }
93
94
  throw e
94
95
  }
95
96
  }
96
97
 
97
98
  private fun resolveAndCache(originalUrl: String): Triple<String, Map<String, String>, String> {
99
+ factory.resolveOnNextMediaOpen = false
98
100
  val resolved = resolveRequestConfig(originalUrl)
99
101
  factory.cachedTransform = resolved
100
102
  factory.cachedOriginalUrl = originalUrl
@@ -103,7 +105,16 @@ class TransformingDataSource(private val upstream: DataSource, private val facto
103
105
  }
104
106
 
105
107
  override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
106
- return upstream.read(buffer, offset, length)
108
+ return try {
109
+ upstream.read(buffer, offset, length)
110
+ } catch (e: IOException) {
111
+ // An in-place retry reopens the media URL after a dropped read. A load cancelled for a seek,
112
+ // whose thread the loader interrupts, keeps it.
113
+ if (openedMediaUrl && !Thread.currentThread().isInterrupted) {
114
+ factory.resolveOnNextMediaOpen = true
115
+ }
116
+ throw e
117
+ }
107
118
  }
108
119
 
109
120
  override fun addTransferListener(transferListener: TransferListener) {
@@ -127,6 +138,7 @@ class TransformingDataSource(private val upstream: DataSource, private val facto
127
138
  override fun close() {
128
139
  upstream.close()
129
140
  resolvedUri = null
141
+ openedMediaUrl = false
130
142
  }
131
143
 
132
144
  /**
@@ -164,8 +176,11 @@ class TransformingDataSource(private val upstream: DataSource, private val facto
164
176
 
165
177
  @Volatile internal var cachedOriginalUrl: String? = null
166
178
 
167
- // Set by a failed media-URL open; the next media-URL open re-resolves and clears it.
168
- @Volatile internal var reresolveOnNextMediaOpen: Boolean = false
179
+ /**
180
+ * Set by a failed open or read of the media URL and by [ResolvingOnReloadSource] on a reload;
181
+ * the next open of the media URL resolves it again and clears it.
182
+ */
183
+ @Volatile internal var resolveOnNextMediaOpen: Boolean = false
169
184
 
170
185
  override fun createDataSource(): DataSource {
171
186
  return TransformingDataSource(upstream = upstreamFactory.createDataSource(), factory = this)
@@ -12,11 +12,20 @@ internal interface RemotePlayback {
12
12
  * The receiver of the current session; read it only while [isSessionAvailable]. It plays one item
13
13
  * at a time: setting an item loads it there from the given position, and plays it if
14
14
  * `playWhenReady` is set, without [MediaPlayer.prepare]. A new session can bring a new player.
15
+ * While [isSuspended], it drops every command.
15
16
  */
16
17
  val player: MediaPlayer
17
18
 
19
+ /** True while [isSuspended] too: the session is kept, and the receiver plays on. */
18
20
  val isSessionAvailable: Boolean
19
21
 
22
+ /**
23
+ * The session is kept but out of reach: nothing sent to [player] arrives, and its state stands
24
+ * still until the session resumes.
25
+ */
26
+ val isSuspended: Boolean
27
+ get() = false
28
+
20
29
  /** Calls [listener] on the main thread; null stops the calls. */
21
30
  fun setListener(listener: Listener?)
22
31
 
@@ -24,7 +33,7 @@ internal interface RemotePlayback {
24
33
  fun release()
25
34
 
26
35
  interface Listener {
27
- /** [isSessionAvailable] or [player] changed. */
36
+ /** [isSessionAvailable], [isSuspended] or [player] changed. */
28
37
  fun onSessionChanged()
29
38
 
30
39
  /**
@@ -31,6 +31,8 @@ import timber.log.Timber
31
31
  * - Moving between remotes, or to a remote's new session, goes from receiver to receiver.
32
32
  * - A receiver's failure, or an item it hasn't started within [startTimeoutMs] of being sent or
33
33
  * played, is the player error until [prepare] loads the item again. [stop] stops the receiver.
34
+ * - While the remote's session is suspended, playback stays there, and the item loaded or the stop
35
+ * made meanwhile goes to the receiver at the resume. Other commands made then are lost.
34
36
  * - [setVolume] sets the receiver's device volume while remote.
35
37
  */
36
38
  internal class RemoteSwitchingPlayer(
@@ -76,6 +78,12 @@ internal class RemoteSwitchingPlayer(
76
78
 
77
79
  /** The receiver's last timed metadata for the current item; none until it holds that item. */
78
80
  var timedMetadata = NO_TIMED_METADATA
81
+
82
+ /** [RemotePlayback.isSuspended] as last followed: a send or a stop waits for the resume. */
83
+ var suspended = output.isSuspended
84
+
85
+ /** A stop made while [suspended], for the resume; a later send replaces it. */
86
+ var stopHeld = false
79
87
  }
80
88
  }
81
89
 
@@ -194,6 +202,7 @@ internal class RemoteSwitchingPlayer(
194
202
  current.output.isSessionAvailable &&
195
203
  current.output.player === current.receiver
196
204
  ) {
205
+ followSuspension(current)
197
206
  return
198
207
  }
199
208
  val next = remotes.firstOrNull { it.isSessionAvailable }
@@ -209,6 +218,32 @@ internal class RemoteSwitchingPlayer(
209
218
  }
210
219
  }
211
220
 
221
+ /**
222
+ * No start times out while the receiver is out of reach. At the resume, the item sent meanwhile,
223
+ * or sent just before and never seen there, goes to the receiver, and a stop made meanwhile stops
224
+ * it.
225
+ */
226
+ private fun followSuspension(remote: Route.Remote) {
227
+ val suspended = remote.output.isSuspended
228
+ if (suspended == remote.suspended) return
229
+ remote.suspended = suspended
230
+ if (suspended) {
231
+ disarmStart(remote)
232
+ return
233
+ }
234
+ if (remote.stopHeld) {
235
+ remote.stopHeld = false
236
+ stopReceiver(remote)
237
+ }
238
+ when (val load = remote.load) {
239
+ is Load.Sent ->
240
+ if (receiverHolds(remote, load.item)) armStart(remote)
241
+ else send(remote, load.item, load.positionMs)
242
+ is Load.Playing -> if (playIntent && !started(remote)) armStart(remote)
243
+ else -> Unit
244
+ }
245
+ }
246
+
212
247
  private fun handOverToRemote(target: RemotePlayback) {
213
248
  route =
214
249
  Route.HandingOver(
@@ -317,6 +352,11 @@ internal class RemoteSwitchingPlayer(
317
352
  remote.startTimeout = null
318
353
  }
319
354
 
355
+ /** Holds the stop back for the resume while [remote] is suspended. */
356
+ private fun stopReceiver(remote: Route.Remote) {
357
+ if (remote.suspended) remote.stopHeld = true else stopReceiver(remote.receiver)
358
+ }
359
+
320
360
  /** A receiver whose session already ended refuses commands; it has stopped by itself. */
321
361
  private fun stopReceiver(receiver: MediaPlayer) {
322
362
  try {
@@ -332,7 +372,7 @@ internal class RemoteSwitchingPlayer(
332
372
  val item = queue.current
333
373
  if (item == null) {
334
374
  remote.load = Load.Idle(C.TIME_UNSET)
335
- stopReceiver(remote.receiver)
375
+ stopReceiver(remote)
336
376
  return
337
377
  }
338
378
  remote.load =
@@ -351,6 +391,10 @@ internal class RemoteSwitchingPlayer(
351
391
 
352
392
  private fun send(remote: Route.Remote, item: MediaItem, positionMs: Long) {
353
393
  remote.load = Load.Sent(item, positionMs)
394
+ if (remote.suspended) {
395
+ remote.stopHeld = false
396
+ return
397
+ }
354
398
  armStart(remote)
355
399
  try {
356
400
  // Before the load, which autoplays as this says. Told again, a receiver plays what it holds.
@@ -553,7 +597,7 @@ internal class RemoteSwitchingPlayer(
553
597
  // item while the next resolves is not told to play it.
554
598
  if (!playWhenReady || remote.load !is Load.Resolving)
555
599
  remote.receiver.playWhenReady = playWhenReady
556
- if (remote.load is Load.Playing) {
600
+ if (remote.load is Load.Playing && !remote.suspended) {
557
601
  if (resumes) armStart(remote) else if (!playWhenReady) disarmStart(remote)
558
602
  }
559
603
  return done()
@@ -575,7 +619,7 @@ internal class RemoteSwitchingPlayer(
575
619
  if (remote == null) return super.handleStop()
576
620
  val positionMs = positionOn(remote)
577
621
  cancelLoad(remote)
578
- stopReceiver(remote.receiver)
622
+ stopReceiver(remote)
579
623
  remote.load = Load.Idle(positionMs)
580
624
  return done()
581
625
  }
@@ -640,7 +684,7 @@ internal class RemoteSwitchingPlayer(
640
684
  nothingAfter && repeat == REPEAT_MODE_ALL -> queue.moveTo(0)
641
685
  nothingAfter && playing -> {
642
686
  cancelLoad(remote)
643
- stopReceiver(remote.receiver)
687
+ stopReceiver(remote)
644
688
  remote.load = Load.Ended(0)
645
689
  return done()
646
690
  }
@@ -1,7 +1,6 @@
1
1
  package com.audiobrowser.util
2
2
 
3
3
  import android.net.Uri
4
- import androidx.core.net.toUri
5
4
  import com.margelo.nitro.audiobrowser.NavigationErrorKind
6
5
  import java.net.URLEncoder
7
6
 
@@ -11,6 +10,8 @@ import java.net.URLEncoder
11
10
  * playable-only track while keeping its parent for queue restoration (docs/adr/0009).
12
11
  */
13
12
  object BrowserPathHelper {
13
+ private val ABSOLUTE_URL = Regex("^([a-z][a-z0-9+.-]*:|//)", RegexOption.IGNORE_CASE)
14
+
14
15
  const val ROOT_PATH = "/__root"
15
16
 
16
17
  /** Full search paths are `/__search?q=<query>`; see [createSearchPath]. */
@@ -60,28 +61,19 @@ object BrowserPathHelper {
60
61
  }
61
62
 
62
63
  /**
63
- * The parent path: [url] without `__trackId` and `__index`, its other query parameters kept.
64
- * Returns a non-contextual [url] unchanged.
64
+ * The parent path: [url] without `__trackId` and `__index`, every other character as written, so
65
+ * it equals the parent [build] was given. Returns a non-contextual [url] unchanged.
65
66
  */
66
67
  fun stripTrackId(url: String): String {
67
68
  if (!isContextual(url)) {
68
69
  return url
69
70
  }
70
-
71
- val uri = url.toUri()
72
-
73
- val builder = uri.buildUpon()
74
- builder.clearQuery()
75
-
76
- uri.queryParameterNames.forEach { paramName ->
77
- if (paramName != CONTEXTUAL_TRACK_PARAM && paramName != CONTEXTUAL_INDEX_PARAM) {
78
- uri.getQueryParameters(paramName).forEach { value ->
79
- builder.appendQueryParameter(paramName, value)
80
- }
71
+ val (head, pairs) = splitQuery(url) ?: return url
72
+ val kept =
73
+ pairs.filterNot {
74
+ it.startsWith("$CONTEXTUAL_TRACK_PARAM=") || it.startsWith("$CONTEXTUAL_INDEX_PARAM=")
81
75
  }
82
- }
83
-
84
- return builder.build().toString()
76
+ return if (kept.isEmpty()) head else "$head?${kept.joinToString("&")}"
85
77
  }
86
78
 
87
79
  /**
@@ -97,35 +89,39 @@ object BrowserPathHelper {
97
89
  }
98
90
 
99
91
  /** The decoded `__trackId`, or null when [path] is not contextual. */
100
- fun extractTrackId(path: String): String? {
101
- if (!isContextual(path)) {
92
+ fun extractTrackId(path: String): String? = contextualValue(CONTEXTUAL_TRACK_PARAM, path)
93
+
94
+ /** The `__index`, or null when [path] is not contextual or its index is missing or negative. */
95
+ fun extractIndex(path: String): Int? =
96
+ contextualValue(CONTEXTUAL_INDEX_PARAM, path)?.toIntOrNull()?.takeIf { it >= 0 }
97
+
98
+ /**
99
+ * [path] cut at its first `?`: what precedes it, and the `name=value` pairs after it as written.
100
+ */
101
+ private fun splitQuery(path: String): Pair<String, List<String>>? {
102
+ val mark = path.indexOf('?')
103
+ if (mark < 0) {
102
104
  return null
103
105
  }
104
-
105
- val uri = Uri.parse(path)
106
- return uri.getQueryParameter(CONTEXTUAL_TRACK_PARAM)
106
+ return path.substring(0, mark) to path.substring(mark + 1).split('&')
107
107
  }
108
108
 
109
- /** The `__index`, or null when [path] is not contextual or its index is missing or negative. */
110
- fun extractIndex(path: String): Int? {
109
+ /** The percent-decoded value of [name] in a contextual [path]; null when there is none. */
110
+ private fun contextualValue(name: String, path: String): String? {
111
111
  if (!isContextual(path)) {
112
112
  return null
113
113
  }
114
-
115
- val raw = Uri.parse(path).getQueryParameter(CONTEXTUAL_INDEX_PARAM) ?: return null
116
- return raw.toIntOrNull()?.takeIf { it >= 0 }
114
+ val prefix = "$name="
115
+ val pair = splitQuery(path)?.second?.firstOrNull { it.startsWith(prefix) } ?: return null
116
+ return Uri.decode(pair.substring(prefix.length))
117
117
  }
118
118
 
119
119
  /**
120
- * Joins [baseUrl] and [path] with exactly one slash. Returns [path] unchanged when it is already
121
- * an http(s) URL or [baseUrl] is null.
120
+ * Joins [baseUrl] and [path] with exactly one slash. Returns [path] unchanged when it has a URI
121
+ * scheme (`content:`, `file:`, `HTTPS:`, …), starts with `//` or [baseUrl] is null.
122
122
  */
123
123
  fun buildUrl(baseUrl: String?, path: String): String {
124
- if (path.startsWith("http://") || path.startsWith("https://")) {
125
- return path
126
- }
127
-
128
- if (baseUrl == null) {
124
+ if (baseUrl == null || isAbsoluteUrl(path)) {
129
125
  return path
130
126
  }
131
127
 
@@ -133,4 +129,6 @@ object BrowserPathHelper {
133
129
  val normalizedPath = path.trimStart('/')
134
130
  return "$normalizedBase$normalizedPath"
135
131
  }
132
+
133
+ private fun isAbsoluteUrl(url: String): Boolean = ABSOLUTE_URL.containsMatchIn(url)
136
134
  }
@@ -0,0 +1,64 @@
1
+ package com.audiobrowser.util
2
+
3
+ import android.os.Bundle
4
+ import android.provider.MediaStore
5
+ import androidx.media3.common.MediaItem
6
+ import com.margelo.nitro.audiobrowser.MediaReference
7
+ import com.margelo.nitro.audiobrowser.SearchMode
8
+ import com.margelo.nitro.audiobrowser.SearchParams
9
+
10
+ object SearchParamsFactory {
11
+ /** A free-text search, as a car's search surface gives it. */
12
+ fun fromQuery(query: String): SearchParams =
13
+ SearchParams(
14
+ mode = null,
15
+ query = query,
16
+ genre = null,
17
+ artist = null,
18
+ album = null,
19
+ title = null,
20
+ playlist = null,
21
+ reference = MediaReference.UNKNOWN,
22
+ )
23
+
24
+ /**
25
+ * The search a play-from-search request asks for, from its query and the extras of
26
+ * https://developer.android.com/guide/components/intents-common#PlaySearch. The intent and the
27
+ * media session's legacy `playFromSearch` carry the same extras.
28
+ */
29
+ fun fromPlayFromSearch(query: String, extras: Bundle?): SearchParams {
30
+ val mediaFocus = extras?.getString(MediaStore.EXTRA_MEDIA_FOCUS)
31
+
32
+ // The focus picks a vertical. Genre, artist and album focuses are filters, carried by the
33
+ // extras below, so they yield no mode. Android has no station or podcast focus: those
34
+ // verticals are iOS-only.
35
+ val mode =
36
+ when (mediaFocus) {
37
+ "vnd.android.cursor.item/*" -> if (query.isEmpty()) SearchMode.ANY else null
38
+ "vnd.android.cursor.item/audio" -> SearchMode.SONG
39
+ MediaStore.Audio.Playlists.ENTRY_CONTENT_TYPE -> SearchMode.PLAYLIST
40
+ else -> null
41
+ }
42
+
43
+ return SearchParams(
44
+ mode = mode,
45
+ query = query,
46
+ genre = extras?.getString("android.intent.extra.genre"),
47
+ artist = extras?.getString(MediaStore.EXTRA_MEDIA_ARTIST),
48
+ album = extras?.getString(MediaStore.EXTRA_MEDIA_ALBUM),
49
+ title = extras?.getString(MediaStore.EXTRA_MEDIA_TITLE),
50
+ playlist = extras?.getString("android.intent.extra.playlist"),
51
+ reference = MediaReference.UNKNOWN,
52
+ )
53
+ }
54
+
55
+ /**
56
+ * The search [mediaItem] asks to play, or null when it names an item. Media3 gives the legacy
57
+ * `playFromSearch` and `prepareFromSearch` as one item with the query and no media id.
58
+ */
59
+ fun voiceSearchOf(mediaItem: MediaItem): SearchParams? {
60
+ if (mediaItem.mediaId != MediaItem.DEFAULT_MEDIA_ID) return null
61
+ val request = mediaItem.requestMetadata
62
+ return request.searchQuery?.let { fromPlayFromSearch(it, request.extras) }
63
+ }
64
+ }