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

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 (147) hide show
  1. package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +19 -2
  2. package/android/src/main/java/com/audiobrowser/browser/BrowserManager.kt +29 -8
  3. package/android/src/main/java/com/audiobrowser/http/RequestConfigBuilder.kt +8 -10
  4. package/android/src/main/java/com/audiobrowser/model/PlayerSetupOptions.kt +2 -2
  5. package/android/src/main/java/com/audiobrowser/player/AutomaticBufferManager.kt +17 -16
  6. package/android/src/main/java/com/audiobrowser/player/InterceptingPlayer.kt +11 -0
  7. package/android/src/main/java/com/audiobrowser/player/Player.kt +8 -4
  8. package/android/src/test/java/com/audiobrowser/ContentRefreshNavigationErrorTest.kt +236 -0
  9. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerUnparsableResponseTest.kt +82 -0
  10. package/android/src/test/java/com/audiobrowser/browser/BrowserUrlResolutionTest.kt +15 -0
  11. package/android/src/test/java/com/audiobrowser/http/RequestConfigBuilderTest.kt +26 -0
  12. package/android/src/test/java/com/audiobrowser/model/PlayerSetupOptionsTest.kt +19 -2
  13. package/android/src/test/java/com/audiobrowser/player/AutomaticBufferManagerTest.kt +17 -0
  14. package/android/src/test/java/com/audiobrowser/player/SessionQueueShuffleOrderTest.kt +38 -0
  15. package/ios/Browser/BrowserError.swift +8 -0
  16. package/ios/Browser/BrowserManager.swift +29 -28
  17. package/ios/Browser/BrowserPathHelper.swift +26 -24
  18. package/ios/Browser/FavoriteSet.swift +16 -8
  19. package/ios/Browser/Favorites.swift +66 -0
  20. package/ios/Browser/JsonModels.swift +27 -7
  21. package/ios/Browser/NavigationErrorState.swift +18 -1
  22. package/ios/Browser/PageResolver.swift +2 -2
  23. package/ios/Browser/RequestLayer.swift +11 -4
  24. package/ios/Browser/RequestPipeline.swift +8 -4
  25. package/ios/Browser/TabBarEntries.swift +7 -0
  26. package/ios/CarPlay/CarPlayImageLoader.swift +3 -7
  27. package/ios/CarPlay/CarPlaySession+Navigator.swift +3 -1
  28. package/ios/CarPlay/IntentHandlers.swift +1 -7
  29. package/ios/CarPlay/MediaIntentCriteria.swift +4 -4
  30. package/ios/Extension/CGSize+AspectFit.swift +11 -0
  31. package/ios/Extension/Dictionary+Headers.swift +8 -0
  32. package/ios/Extension/NavigationError+Conversion.swift +4 -3
  33. package/ios/Extension/ResolvedTrack+Copying.swift +15 -0
  34. package/ios/Http/HttpClient.swift +37 -11
  35. package/ios/HybridAudioBrowser+Browser.swift +9 -16
  36. package/ios/HybridAudioBrowser+Options.swift +1 -0
  37. package/ios/HybridAudioBrowser+Player.swift +24 -23
  38. package/ios/HybridAudioBrowser+PlayerCallbacks.swift +1 -2
  39. package/ios/Model/NitroTypeStubs.swift +39 -0
  40. package/ios/Model/TrackPlayerError.swift +21 -2
  41. package/ios/Player/AudioSessionController.swift +2 -2
  42. package/ios/Player/MediaLoader.swift +1 -1
  43. package/ios/Player/PlaybackStateMachine.swift +13 -12
  44. package/ios/Player/Player.swift +60 -21
  45. package/ios/Player/PlayerEngine.swift +5 -0
  46. package/ios/Player/QueueManager.swift +21 -4
  47. package/ios/Tests/BrowserErrorTests.swift +21 -0
  48. package/ios/Tests/BrowserPathHelperTests.swift +18 -0
  49. package/ios/Tests/CGSizeAspectFitTests.swift +36 -0
  50. package/ios/Tests/ClampedVolumeTests.swift +26 -0
  51. package/ios/Tests/FavoriteSetTests.swift +68 -3
  52. package/ios/Tests/FavoritesTests.swift +102 -0
  53. package/ios/Tests/HttpClientUserAgentTests.swift +45 -0
  54. package/ios/Tests/JsonModelsTests.swift +74 -6
  55. package/ios/Tests/MediaIntentCriteriaTests.swift +11 -1
  56. package/ios/Tests/MediaLoaderAssetOptionsTests.swift +7 -0
  57. package/ios/Tests/NavigationErrorStateTests.swift +73 -0
  58. package/ios/Tests/PlaybackStateMachineTests.swift +21 -12
  59. package/ios/Tests/PlayerPolicyTests.swift +103 -0
  60. package/ios/Tests/PlayerProgressTests.swift +109 -0
  61. package/ios/Tests/PlayerTests.swift +106 -0
  62. package/ios/Tests/QueueIndexTests.swift +43 -0
  63. package/ios/Tests/QueueManagerTests.swift +79 -15
  64. package/ios/Tests/RequestLayerTests.swift +22 -3
  65. package/ios/Tests/TabBarEntriesTests.swift +19 -0
  66. package/ios/Tests/TrackSelectorTests.swift +154 -0
  67. package/ios/Tests/UnparsableResponseTests.swift +91 -0
  68. package/ios/TrackSelector.swift +28 -8
  69. package/ios/Util/ArtworkImageFetcher.swift +9 -8
  70. package/ios/Util/SVGProcessor.swift +6 -17
  71. package/lib/commonjs/features/browser-config.js +6 -3
  72. package/lib/commonjs/features/browser-config.js.map +1 -1
  73. package/lib/commonjs/features/errors.js +12 -7
  74. package/lib/commonjs/features/errors.js.map +1 -1
  75. package/lib/commonjs/features/nowPlaying.js +9 -3
  76. package/lib/commonjs/features/nowPlaying.js.map +1 -1
  77. package/lib/commonjs/features/playback/trackPlaybackTime.js +2 -1
  78. package/lib/commonjs/features/playback/trackPlaybackTime.js.map +1 -1
  79. package/lib/commonjs/features/player/setup.js +2 -2
  80. package/lib/commonjs/features/queue/activeTrack.js +4 -2
  81. package/lib/commonjs/features/queue/activeTrack.js.map +1 -1
  82. package/lib/commonjs/features/sleepTimer.js +6 -5
  83. package/lib/commonjs/features/sleepTimer.js.map +1 -1
  84. package/lib/commonjs/utils/LazyNativeEmitter.js +2 -1
  85. package/lib/commonjs/utils/LazyNativeEmitter.js.map +1 -1
  86. package/lib/commonjs/utils/NativeUpdatedValue.js +2 -1
  87. package/lib/commonjs/utils/NativeUpdatedValue.js.map +1 -1
  88. package/lib/commonjs/utils/callListener.js +23 -0
  89. package/lib/commonjs/utils/callListener.js.map +1 -0
  90. package/lib/module/features/browser-config.js +6 -3
  91. package/lib/module/features/browser-config.js.map +1 -1
  92. package/lib/module/features/errors.js +12 -7
  93. package/lib/module/features/errors.js.map +1 -1
  94. package/lib/module/features/nowPlaying.js +9 -3
  95. package/lib/module/features/nowPlaying.js.map +1 -1
  96. package/lib/module/features/playback/trackPlaybackTime.js +2 -1
  97. package/lib/module/features/playback/trackPlaybackTime.js.map +1 -1
  98. package/lib/module/features/player/setup.js +2 -2
  99. package/lib/module/features/queue/activeTrack.js +4 -2
  100. package/lib/module/features/queue/activeTrack.js.map +1 -1
  101. package/lib/module/features/sleepTimer.js +6 -5
  102. package/lib/module/features/sleepTimer.js.map +1 -1
  103. package/lib/module/utils/LazyNativeEmitter.js +2 -1
  104. package/lib/module/utils/LazyNativeEmitter.js.map +1 -1
  105. package/lib/module/utils/NativeUpdatedValue.js +2 -1
  106. package/lib/module/utils/NativeUpdatedValue.js.map +1 -1
  107. package/lib/module/utils/callListener.js +19 -0
  108. package/lib/module/utils/callListener.js.map +1 -0
  109. package/lib/typescript/src/features/browser-config.d.ts.map +1 -1
  110. package/lib/typescript/src/features/errors.d.ts +8 -6
  111. package/lib/typescript/src/features/errors.d.ts.map +1 -1
  112. package/lib/typescript/src/features/nowPlaying.d.ts +2 -1
  113. package/lib/typescript/src/features/nowPlaying.d.ts.map +1 -1
  114. package/lib/typescript/src/features/playback/trackPlaybackTime.d.ts.map +1 -1
  115. package/lib/typescript/src/features/player/setup.d.ts +2 -2
  116. package/lib/typescript/src/features/queue/activeTrack.d.ts +2 -1
  117. package/lib/typescript/src/features/queue/activeTrack.d.ts.map +1 -1
  118. package/lib/typescript/src/features/sleepTimer.d.ts +2 -1
  119. package/lib/typescript/src/features/sleepTimer.d.ts.map +1 -1
  120. package/lib/typescript/src/types/browser.d.ts +3 -2
  121. package/lib/typescript/src/types/browser.d.ts.map +1 -1
  122. package/lib/typescript/src/utils/LazyNativeEmitter.d.ts.map +1 -1
  123. package/lib/typescript/src/utils/NativeUpdatedValue.d.ts.map +1 -1
  124. package/lib/typescript/src/utils/callListener.d.ts +7 -0
  125. package/lib/typescript/src/utils/callListener.d.ts.map +1 -0
  126. package/package.json +1 -1
  127. package/src/features/browser-config.test.ts +15 -0
  128. package/src/features/browser-config.ts +6 -3
  129. package/src/features/errors.test.ts +83 -0
  130. package/src/features/errors.ts +12 -7
  131. package/src/features/hook-wiring.test.ts +11 -10
  132. package/src/features/nowPlaying.ts +9 -3
  133. package/src/features/playback/trackPlaybackTime.test.ts +24 -1
  134. package/src/features/playback/trackPlaybackTime.ts +2 -1
  135. package/src/features/player/setup.ts +2 -2
  136. package/src/features/queue/activeTrack.test.ts +32 -0
  137. package/src/features/queue/activeTrack.ts +8 -2
  138. package/src/features/sleepTimer.test.ts +24 -0
  139. package/src/features/sleepTimer.ts +6 -5
  140. package/src/types/browser.ts +3 -2
  141. package/src/utils/LazyNativeEmitter.test.ts +32 -0
  142. package/src/utils/LazyNativeEmitter.ts +3 -1
  143. package/src/utils/NativeUpdatedValue.test.ts +32 -0
  144. package/src/utils/NativeUpdatedValue.ts +3 -1
  145. package/src/utils/callListener.ts +17 -0
  146. package/website/guide/configuration.md +3 -3
  147. package/website/guide/errors.md +3 -1
@@ -697,7 +697,7 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
697
697
  launchInScope { connectedService?.player?.notifyContentChanged(path) }
698
698
 
699
699
  if (browserManager.getPath() == path) {
700
- mainScope.launch { browserManager.refresh() }
700
+ refreshContent()
701
701
  }
702
702
  }
703
703
 
@@ -713,7 +713,24 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
713
713
  runCatching { browserManager.queryTabs() }
714
714
  .onFailure { Timber.e(it, "Re-querying tabs failed") }
715
715
  }
716
- mainScope.launch { browserManager.refresh() }
716
+ refreshContent()
717
+ }
718
+
719
+ /**
720
+ * Reloads the current path. A reload that publishes clears the navigation error; one that fails
721
+ * reports it, unless a later navigation or reload has overtaken it.
722
+ */
723
+ private fun refreshContent() {
724
+ mainScope.launch {
725
+ val path = browserManager.getPath()
726
+ try {
727
+ if (browserManager.refresh()) clearNavigationError()
728
+ } catch (e: CancellationException) {
729
+ throw e
730
+ } catch (e: Exception) {
731
+ handleBrowserException(e, path, "refreshing path: $path")
732
+ }
733
+ }
717
734
  }
718
735
 
719
736
  override fun setFavorites(favorites: Array<String>) {
@@ -709,8 +709,14 @@ class BrowserManager {
709
709
  return content
710
710
  }
711
711
 
712
- /** Re-resolves the current path, bypassing the cache. Errors are logged, never thrown. */
713
- suspend fun refresh() {
712
+ /**
713
+ * Re-resolves the current path, bypassing the cache, and returns whether it published the
714
+ * content. Overtaken by a later navigation or refresh, it publishes nothing and returns false,
715
+ * its failure only logged.
716
+ *
717
+ * @throws Exception when resolution fails and nothing has overtaken it
718
+ */
719
+ suspend fun refresh(): Boolean {
714
720
  val navigationId = ++currentNavigationId
715
721
 
716
722
  val currentPath = path
@@ -720,11 +726,15 @@ class BrowserManager {
720
726
  contentCache.remove(currentPath)
721
727
  val content = resolve(currentPath, useCache = false)
722
728
 
723
- if (navigationId == currentNavigationId) {
724
- this.content = content
725
- }
729
+ if (navigationId != currentNavigationId) return false
730
+ this.content = content
731
+ return true
732
+ } catch (e: CancellationException) {
733
+ throw e
726
734
  } catch (e: Exception) {
727
- Timber.e(e, "Error refreshing content for path: $currentPath")
735
+ if (navigationId == currentNavigationId) throw e
736
+ Timber.e(e, "Error in overtaken refresh for path: $currentPath")
737
+ return false
728
738
  }
729
739
  }
730
740
 
@@ -1145,7 +1155,16 @@ class BrowserManager {
1145
1155
  response.fold(
1146
1156
  onSuccess = { httpResponse ->
1147
1157
  if (httpResponse.isSuccessful) {
1148
- val jsonResolvedTrack = json.decodeFromString<JsonResolvedTrack>(httpResponse.body)
1158
+ val jsonResolvedTrack =
1159
+ try {
1160
+ json.decodeFromString<JsonResolvedTrack>(httpResponse.body)
1161
+ } catch (e: Exception) {
1162
+ throw HttpStatusException(
1163
+ httpResponse.code,
1164
+ "Server returned ${httpResponse.code} with a response that is not a page: ${e.message}",
1165
+ e,
1166
+ )
1167
+ }
1149
1168
  jsonResolvedTrack.toNitro()
1150
1169
  } else {
1151
1170
  Timber.w(
@@ -1219,7 +1238,9 @@ class BrowserManager {
1219
1238
 
1220
1239
  class ContentNotFoundException(val path: String) : Exception("Content not found")
1221
1240
 
1222
- class HttpStatusException(val statusCode: Int, message: String) : Exception(message)
1241
+ /** A non-2xx response, or a 2xx response whose body does not parse. */
1242
+ class HttpStatusException(val statusCode: Int, message: String, cause: Throwable? = null) :
1243
+ Exception(message, cause)
1223
1244
 
1224
1245
  class NetworkException(message: String, cause: Throwable? = null) : Exception(message, cause)
1225
1246
 
@@ -230,17 +230,15 @@ object RequestConfigBuilder {
230
230
 
231
231
  val url = BrowserPathHelper.buildUrl(baseUrl, path)
232
232
 
233
+ val query = config.query
234
+ if (query.isNullOrEmpty()) return url
235
+
233
236
  val queryString =
234
- config.query?.let { query ->
235
- if (query.isNotEmpty()) {
236
- "?" +
237
- query.entries.joinToString("&") { (key, value) ->
238
- "${encodeUrlParam(key)}=${encodeUrlParam(value)}"
239
- }
240
- } else ""
241
- } ?: ""
242
-
243
- return "$url$queryString"
237
+ query.entries.joinToString("&") { (key, value) ->
238
+ "${encodeUrlParam(key)}=${encodeUrlParam(value)}"
239
+ }
240
+ val separator = if (url.contains('?')) "&" else "?"
241
+ return "$url$separator$queryString"
244
242
  }
245
243
 
246
244
  private fun encodeUrlParam(param: String): String {
@@ -131,8 +131,8 @@ data class PlayerSetupOptions(
131
131
 
132
132
  options.keepSessionAliveOnError?.let { keepSessionAliveOnError = it }
133
133
  options.autoUpdateNowPlayingMetadata?.let { autoUpdateNowPlayingMetadata = it }
134
- options.nowPlayingMetadataFormatter?.let { nowPlayingMetadataFormatter = it }
135
- // Unlike the fields above, an absent value turns remote outputs off.
134
+ // Unlike the fields above, an absent value removes the formatter and turns remote outputs off.
135
+ nowPlayingMetadataFormatter = options.nowPlayingMetadataFormatter
136
136
  remoteOutputs = options.remoteOutputs
137
137
  }
138
138
  }
@@ -12,8 +12,8 @@ import timber.log.Timber
12
12
  /**
13
13
  * Raises [DynamicLoadControl]'s `bufferForPlaybackAfterRebufferMs` after each underrun, to what the
14
14
  * measured drain rate says would last [targetPlaybackDurationMs]. The threshold only rises, up to
15
- * [maxRebufferBufferMs], until a playlist change or a seek to another item resets it to
16
- * [defaultConfig].
15
+ * [maxRebufferBufferMs], or stays where the setup put it if that is higher, until a playlist change
16
+ * or a seek to another item resets it to [defaultConfig].
17
17
  *
18
18
  * An underrun is a rebuffer while every load delivers, however slowly: a connection that stays open
19
19
  * and stalls counts. A rebuffer while media3 retries a failed load in place does not, nor does a
@@ -241,9 +241,13 @@ class AutomaticBufferManager(
241
241
  )
242
242
 
243
243
  if (playbackDurationMs > 0 && bufferAtPlaybackStartMs > 0) {
244
- val newRebufferBuffer =
245
- calculateOptimalRebufferBuffer(playbackDurationMs, bufferAtPlaybackStartMs)
246
244
  val currentConfig = loadControl.getBufferConfig()
245
+ val newRebufferBuffer =
246
+ calculateOptimalRebufferBuffer(
247
+ playbackDurationMs,
248
+ bufferAtPlaybackStartMs,
249
+ currentConfig.bufferForPlaybackAfterRebufferMs,
250
+ )
247
251
  if (newRebufferBuffer != currentConfig.bufferForPlaybackAfterRebufferMs) {
248
252
  Timber.d(
249
253
  "Adjusting rebuffer threshold: %dms -> %dms",
@@ -270,18 +274,14 @@ class AutomaticBufferManager(
270
274
 
271
275
  /**
272
276
  * Assumes the buffer held at ready drained to empty over [playbackDurationMs], and returns the
273
- * threshold that would last [targetPlaybackDurationMs]: 1000ms lasting 30s needs 2000ms.
277
+ * threshold that would last [targetPlaybackDurationMs]: 1000ms lasting 30s needs 2000ms. Both
278
+ * durations must be positive.
274
279
  */
275
- private fun calculateOptimalRebufferBuffer(playbackDurationMs: Long, initialBufferMs: Long): Int {
276
- val currentConfig = loadControl.getBufferConfig()
277
-
278
- if (playbackDurationMs <= 0 || initialBufferMs <= 0) {
279
- Timber.d("Insufficient timing data, using 1.5x fallback")
280
- return (currentConfig.bufferForPlaybackAfterRebufferMs * 1.5)
281
- .toInt()
282
- .coerceIn(defaultConfig.bufferForPlaybackAfterRebufferMs, maxRebufferBufferMs)
283
- }
284
-
280
+ private fun calculateOptimalRebufferBuffer(
281
+ playbackDurationMs: Long,
282
+ initialBufferMs: Long,
283
+ currentThresholdMs: Int,
284
+ ): Int {
285
285
  val drainRateMsPerSec = (initialBufferMs.toFloat() / (playbackDurationMs / 1000f))
286
286
 
287
287
  val neededBufferMs = (drainRateMsPerSec * (targetPlaybackDurationMs / 1000)).toLong()
@@ -295,7 +295,8 @@ class AutomaticBufferManager(
295
295
  // The current threshold as the floor: it never drops within an item.
296
296
  return neededBufferMs
297
297
  .toInt()
298
- .coerceIn(currentConfig.bufferForPlaybackAfterRebufferMs, maxRebufferBufferMs)
298
+ .coerceAtMost(maxRebufferBufferMs)
299
+ .coerceAtLeast(currentThresholdMs)
299
300
  }
300
301
 
301
302
  // endregion
@@ -1,6 +1,8 @@
1
1
  package com.audiobrowser.player
2
2
 
3
+ import androidx.media3.common.C
3
4
  import androidx.media3.common.ForwardingPlayer
5
+ import androidx.media3.common.MediaItem
4
6
  import androidx.media3.common.PlaybackException
5
7
  import androidx.media3.common.Player as MediaPlayer
6
8
  import com.audiobrowser.Callbacks
@@ -59,6 +61,8 @@ internal class InterceptingPlayer(
59
61
  private val engineView: (Int) -> Int,
60
62
  /** Whether the engine's playing is a blip the retry loop hides. */
61
63
  private val masksPlaying: () -> Boolean,
64
+ /** Leads the engine's shuffle order with a start index, given the queue's size. */
65
+ private val leadShuffleOrder: (startIndex: Int, count: Int) -> Unit,
62
66
  private val playPlayer: () -> Unit,
63
67
  private val stopPlayer: () -> Unit,
64
68
  ) : ForwardingPlayer(player) {
@@ -201,4 +205,11 @@ internal class InterceptingPlayer(
201
205
  intercept({ it.handleRemoteSeek(RemoteSeekEvent(position = positionMs.toDouble() / 1000.0)) }) {
202
206
  super.seekTo(positionMs)
203
207
  }
208
+
209
+ // Media3 sets here the queue of a track picked on an external surface and of playback
210
+ // resumption. An unset start index is skipped: shuffleOrderLedBy would clamp it to 0.
211
+ override fun setMediaItems(mediaItems: List<MediaItem>, startIndex: Int, startPositionMs: Long) {
212
+ super.setMediaItems(mediaItems, startIndex, startPositionMs)
213
+ if (startIndex != C.INDEX_UNSET) leadShuffleOrder(startIndex, mediaItems.size)
214
+ }
204
215
  }
@@ -674,6 +674,7 @@ internal constructor(
674
674
  playerState = { playbackState },
675
675
  engineView = ::retryView,
676
676
  masksPlaying = { retryMasksPlaying },
677
+ leadShuffleOrder = ::leadShuffleOrder,
677
678
  playPlayer = ::play,
678
679
  stopPlayer = ::stop,
679
680
  )
@@ -796,14 +797,17 @@ internal constructor(
796
797
  ) {
797
798
  val mediaItems = TrackFactory.toMedia3(tracks).toMutableList()
798
799
  sessionPlayer.setMediaItems(mediaItems, startIndex, startPositionMs)
799
- // While remote, the queue plays in list order.
800
- if (mediaItems.isNotEmpty()) {
801
- localEngine.setShuffleOrder(shuffleOrderLedBy(startIndex, mediaItems.size))
802
- }
800
+ leadShuffleOrder(startIndex, mediaItems.size)
803
801
  queueSourcePath = sourcePath
804
802
  sessionPlayer.prepare()
805
803
  }
806
804
 
805
+ /** Call after setting a queue of [count] tracks that starts on [startIndex]. */
806
+ private fun leadShuffleOrder(startIndex: Int, count: Int) {
807
+ // While remote, the queue plays in list order.
808
+ if (count > 0) localEngine.setShuffleOrder(shuffleOrderLedBy(startIndex, count))
809
+ }
810
+
807
811
  /** @throws IllegalArgumentException if [index] is out of bounds. */
808
812
  fun replaceTrack(index: Int, track: Track) {
809
813
  validateIndex(index)
@@ -0,0 +1,236 @@
1
+ package com.audiobrowser
2
+
3
+ import com.audiobrowser.TestFixtures.resolvedTrack
4
+ import com.audiobrowser.TestFixtures.staticRoute
5
+ import com.audiobrowser.browser.BrowserConfig
6
+ import com.audiobrowser.browser.BrowserManager
7
+ import com.audiobrowser.util.JsPromise
8
+ import com.margelo.nitro.audiobrowser.BrowseError
9
+ import com.margelo.nitro.audiobrowser.FormattedNavigationError
10
+ import com.margelo.nitro.audiobrowser.Func_std__shared_ptr_Promise_std__variant_ResolvedTrack__BrowseError__std__shared_ptr_Promise_std__variant_ResolvedTrack__BrowseError_______BrowserSourceCallbackParam
11
+ import com.margelo.nitro.audiobrowser.NativeBrowserConfiguration
12
+ import com.margelo.nitro.audiobrowser.NavigationError
13
+ import com.margelo.nitro.audiobrowser.NavigationErrorType
14
+ import com.margelo.nitro.audiobrowser.Variant_ResolvedTrack_BrowseError_Promise_BrowseResult_
15
+ import kotlin.time.Duration.Companion.seconds
16
+ import kotlinx.coroutines.CoroutineScope
17
+ import kotlinx.coroutines.test.StandardTestDispatcher
18
+ import kotlinx.coroutines.test.TestScope
19
+ import kotlinx.coroutines.test.runCurrent
20
+ import kotlinx.coroutines.test.runTest
21
+ import org.junit.Assert.assertEquals
22
+ import org.junit.Assert.assertNull
23
+ import org.junit.Test
24
+ import org.junit.runner.RunWith
25
+ import org.mockito.Mockito.CALLS_REAL_METHODS
26
+ import org.mockito.Mockito.mock
27
+ import org.robolectric.RobolectricTestRunner
28
+
29
+ /**
30
+ * The navigation error across the reload behind `notifyContentChanged` and `invalidateAllContent`.
31
+ * Every page is served by a callback route whose answer the test settles, so a reload can load or
32
+ * fail on demand. Robolectric provides `android.net.Uri` and `android.util.LruCache`.
33
+ */
34
+ @RunWith(RobolectricTestRunner::class)
35
+ class ContentRefreshNavigationErrorTest {
36
+
37
+ private class Request(val path: String) {
38
+ private val js = JsPromise<Variant_ResolvedTrack_BrowseError_Promise_BrowseResult_>()
39
+ val promise = js.promise
40
+
41
+ fun load(title: String = "Loaded") =
42
+ js.resolve(
43
+ Variant_ResolvedTrack_BrowseError_Promise_BrowseResult_.create(
44
+ resolvedTrack(path = path, title = title)
45
+ )
46
+ )
47
+
48
+ fun fail() =
49
+ js.resolve(
50
+ Variant_ResolvedTrack_BrowseError_Promise_BrowseResult_.create(BrowseError("Offline"))
51
+ )
52
+ }
53
+
54
+ private val requests = mutableListOf<Request>()
55
+ private val errorEvents = mutableListOf<NavigationError?>()
56
+ private val formattedEvents = mutableListOf<FormattedNavigationError?>()
57
+
58
+ private fun callbackRoute(path: String) =
59
+ staticRoute(path, resolvedTrack(path = path))
60
+ .copy(
61
+ browseStatic = null,
62
+ browseCallback =
63
+ Func_std__shared_ptr_Promise_std__variant_ResolvedTrack__BrowseError__std__shared_ptr_Promise_std__variant_ResolvedTrack__BrowseError_______BrowserSourceCallbackParam {
64
+ Request(it.path).also { request -> requests += request }.promise
65
+ },
66
+ )
67
+
68
+ // AudioBrowser's constructor needs JNI: a mock running its real methods, with the fields the
69
+ // navigation and reload paths read written in its place.
70
+ private fun TestScope.browser(): AudioBrowser {
71
+ val browser = mock(AudioBrowser::class.java, CALLS_REAL_METHODS)
72
+ val manager = BrowserManager()
73
+ manager.config = BrowserConfig(routes = arrayOf(callbackRoute("/a"), callbackRoute("/b")))
74
+ set(browser, "browserManager", manager)
75
+ set(browser, "mainScope", CoroutineScope(StandardTestDispatcher(testScheduler)))
76
+ set(
77
+ browser,
78
+ "_configuration",
79
+ NativeBrowserConfiguration(
80
+ path = null,
81
+ request = null,
82
+ requestResolver = null,
83
+ browse = null,
84
+ browseResolver = null,
85
+ media = null,
86
+ artwork = null,
87
+ nowPlayingArtwork = null,
88
+ routes = null,
89
+ singleTrack = null,
90
+ handleTrackLoad = null,
91
+ androidControllerOfflineError = null,
92
+ viewMoreTitle = null,
93
+ carPlayLoadingTitle = null,
94
+ resolveAlbumPath = null,
95
+ formatNavigationError = null,
96
+ ),
97
+ )
98
+ browser.onNavigationError = { errorEvents += it.error }
99
+ browser.onFormattedNavigationError = { formattedEvents += it }
100
+ return browser
101
+ }
102
+
103
+ private fun set(browser: AudioBrowser, field: String, value: Any) {
104
+ AudioBrowser::class
105
+ .java
106
+ .getDeclaredField(field)
107
+ .apply { isAccessible = true }
108
+ .set(browser, value)
109
+ }
110
+
111
+ /** Leaves [path] displayed with a navigation error, as a navigation that failed offline does. */
112
+ private fun TestScope.failNavigation(browser: AudioBrowser, path: String) {
113
+ browser.navigatePath(path)
114
+ runCurrent()
115
+ requests.removeAt(0).fail()
116
+ runCurrent()
117
+ assertEquals(NavigationErrorType.CALLBACK_ERROR, browser.getNavigationError()?.code)
118
+ }
119
+
120
+ /** Leaves [path] displayed with its page and no navigation error. */
121
+ private fun TestScope.loadNavigation(browser: AudioBrowser, path: String) {
122
+ browser.navigatePath(path)
123
+ runCurrent()
124
+ requests.removeAt(0).load(title = "First")
125
+ runCurrent()
126
+ assertEquals("First", browser.getContent()?.title)
127
+ assertNull(browser.getNavigationError())
128
+ }
129
+
130
+ private fun TestScope.settleReload(settle: Request.() -> Unit) {
131
+ runCurrent()
132
+ requests.removeAt(0).settle()
133
+ runCurrent()
134
+ }
135
+
136
+ @Test
137
+ fun `a notifyContentChanged reload that loads clears an earlier navigation error`() =
138
+ runTest(timeout = 5.seconds) {
139
+ val browser = browser()
140
+ failNavigation(browser, "/a")
141
+
142
+ browser.notifyContentChanged("/a")
143
+ settleReload { load() }
144
+
145
+ assertEquals("Loaded", browser.getContent()?.title)
146
+ assertNull(browser.getNavigationError())
147
+ assertNull(browser.getFormattedNavigationError())
148
+ assertNull(errorEvents.last())
149
+ assertNull(formattedEvents.last())
150
+ }
151
+
152
+ @Test
153
+ fun `an invalidateAllContent reload that loads clears an earlier navigation error`() =
154
+ runTest(timeout = 5.seconds) {
155
+ val browser = browser()
156
+ failNavigation(browser, "/a")
157
+
158
+ browser.invalidateAllContent()
159
+ settleReload { load() }
160
+
161
+ assertEquals("Loaded", browser.getContent()?.title)
162
+ assertNull(browser.getNavigationError())
163
+ assertNull(browser.getFormattedNavigationError())
164
+ assertNull(errorEvents.last())
165
+ assertNull(formattedEvents.last())
166
+ }
167
+
168
+ @Test
169
+ fun `a notifyContentChanged reload that fails is reported as a navigation error`() =
170
+ runTest(timeout = 5.seconds) {
171
+ val browser = browser()
172
+ loadNavigation(browser, "/a")
173
+
174
+ browser.notifyContentChanged("/a")
175
+ settleReload { fail() }
176
+
177
+ assertEquals(NavigationErrorType.CALLBACK_ERROR, browser.getNavigationError()?.code)
178
+ assertEquals(browser.getNavigationError(), errorEvents.last())
179
+ assertEquals(browser.getFormattedNavigationError(), formattedEvents.last())
180
+ assertEquals("First", browser.getContent()?.title)
181
+ }
182
+
183
+ @Test
184
+ fun `an invalidateAllContent reload that fails is reported as a navigation error`() =
185
+ runTest(timeout = 5.seconds) {
186
+ val browser = browser()
187
+ loadNavigation(browser, "/a")
188
+
189
+ browser.invalidateAllContent()
190
+ settleReload { fail() }
191
+
192
+ assertEquals(NavigationErrorType.CALLBACK_ERROR, browser.getNavigationError()?.code)
193
+ assertEquals(browser.getNavigationError(), errorEvents.last())
194
+ assertEquals(browser.getFormattedNavigationError(), formattedEvents.last())
195
+ assertEquals("First", browser.getContent()?.title)
196
+ }
197
+
198
+ @Test
199
+ fun `a failed reload overtaken by a navigation reports nothing`() =
200
+ runTest(timeout = 5.seconds) {
201
+ val browser = browser()
202
+ loadNavigation(browser, "/a")
203
+ browser.notifyContentChanged("/a")
204
+ runCurrent()
205
+ browser.navigatePath("/b")
206
+ runCurrent()
207
+
208
+ requests.removeAt(0).fail()
209
+ runCurrent()
210
+ requests.removeAt(0).load()
211
+ runCurrent()
212
+
213
+ assertEquals("Loaded", browser.getContent()?.title)
214
+ assertNull(browser.getNavigationError())
215
+ assertEquals(emptyList<NavigationError?>(), errorEvents)
216
+ }
217
+
218
+ @Test
219
+ fun `a reload overtaken by a navigation that fails leaves its navigation error`() =
220
+ runTest(timeout = 5.seconds) {
221
+ val browser = browser()
222
+ loadNavigation(browser, "/a")
223
+ browser.notifyContentChanged("/a")
224
+ runCurrent()
225
+ browser.navigatePath("/b")
226
+ runCurrent()
227
+
228
+ requests.removeAt(1).fail()
229
+ runCurrent()
230
+ requests.removeAt(0).load()
231
+ runCurrent()
232
+
233
+ assertNull(browser.getContent())
234
+ assertEquals(NavigationErrorType.CALLBACK_ERROR, browser.getNavigationError()?.code)
235
+ }
236
+ }
@@ -0,0 +1,82 @@
1
+ package com.audiobrowser.browser
2
+
3
+ import com.audiobrowser.TestFixtures.transformableConfig
4
+ import com.audiobrowser.navigationErrorFor
5
+ import com.margelo.nitro.audiobrowser.NavigationError
6
+ import com.margelo.nitro.audiobrowser.NavigationErrorType
7
+ import kotlinx.coroutines.runBlocking
8
+ import okhttp3.mockwebserver.MockResponse
9
+ import okhttp3.mockwebserver.MockWebServer
10
+ import org.junit.After
11
+ import org.junit.Assert.assertEquals
12
+ import org.junit.Assert.fail
13
+ import org.junit.Before
14
+ import org.junit.Test
15
+ import org.junit.runner.RunWith
16
+ import org.robolectric.RobolectricTestRunner
17
+
18
+ /** A page fetch answered 2xx with a body that is not a page. */
19
+ @RunWith(RobolectricTestRunner::class)
20
+ class BrowserManagerUnparsableResponseTest {
21
+
22
+ private lateinit var server: MockWebServer
23
+ private lateinit var browserManager: BrowserManager
24
+
25
+ @Before
26
+ fun setup() {
27
+ server = MockWebServer()
28
+ server.start()
29
+ browserManager = BrowserManager()
30
+ browserManager.config =
31
+ BrowserConfig(
32
+ request = transformableConfig(baseUrl = server.url("/").toString().trimEnd('/'))
33
+ )
34
+ }
35
+
36
+ @After
37
+ fun tearDown() {
38
+ server.shutdown()
39
+ }
40
+
41
+ private fun navigationErrorOfPage(response: MockResponse): NavigationError {
42
+ server.enqueue(response)
43
+ try {
44
+ runBlocking { browserManager.resolve("/page") }
45
+ } catch (e: Exception) {
46
+ return navigationErrorFor(e)
47
+ }
48
+ fail("resolve returned a page")
49
+ throw AssertionError()
50
+ }
51
+
52
+ private fun assertSuccessfulHttpError(statusCode: Int, error: NavigationError) {
53
+ assertEquals(NavigationErrorType.HTTP_ERROR, error.code)
54
+ assertEquals(statusCode.toDouble(), error.statusCode!!, 0.0)
55
+ assertEquals(true, error.statusCodeSuccess)
56
+ }
57
+
58
+ @Test
59
+ fun `a 2xx body that is not JSON is an http-error with a successful status`() {
60
+ val error = navigationErrorOfPage(MockResponse().setBody("<html>Sign in</html>"))
61
+
62
+ assertSuccessfulHttpError(200, error)
63
+ }
64
+
65
+ @Test
66
+ fun `a 2xx JSON body that is not a page is an http-error with a successful status`() {
67
+ val error =
68
+ navigationErrorOfPage(MockResponse().setResponseCode(203).setBody("""{"path":"/page"}"""))
69
+
70
+ assertSuccessfulHttpError(203, error)
71
+ }
72
+
73
+ @Test
74
+ fun `a 2xx page with artwork of the wrong shape is an http-error with a successful status`() {
75
+ val error =
76
+ navigationErrorOfPage(
77
+ MockResponse().setBody("""{"path":"/page","title":"Page","artwork":{"light":"l.png"}}""")
78
+ )
79
+
80
+ assertSuccessfulHttpError(200, error)
81
+ }
82
+ }
@@ -167,6 +167,21 @@ class BrowserUrlResolutionTest {
167
167
  assertTrue(source.uri.contains("h=256"))
168
168
  }
169
169
 
170
+ @Test
171
+ fun `resolveArtworkUrl adds image query params to an artwork url that has a query`() = runTest {
172
+ bm.config =
173
+ BrowserConfig(
174
+ artwork = artworkConfig(imageQueryParams = ImageQueryParams(width = "w", height = "h"))
175
+ )
176
+ val source =
177
+ bm.resolveArtworkUrl(
178
+ track(artwork = "https://img.example.com/a.jpg?v=2"),
179
+ perRouteConfig = null,
180
+ imageContext = ImageContext(256.0, 256.0),
181
+ )
182
+ assertEquals("https://img.example.com/a.jpg?v=2&w=256&h=256", source?.uri)
183
+ }
184
+
170
185
  @Test
171
186
  fun `displayArtworkSource re-resolves a registered uri with the display size`() = runTest {
172
187
  bm.config =
@@ -245,6 +245,32 @@ class RequestConfigBuilderTest {
245
245
  assertEquals("https://api.example.com/albums", result.url)
246
246
  }
247
247
 
248
+ @Test
249
+ fun `buildUrl joins the query with an ampersand when the path already has one`() = runTest {
250
+ val relative =
251
+ RequestConfig(
252
+ method = null,
253
+ path = "/stations?genre=rock",
254
+ baseUrl = "https://api.example.com",
255
+ headers = null,
256
+ query = mapOf("locale" to "en"),
257
+ body = null,
258
+ contentType = null,
259
+ userAgent = null,
260
+ )
261
+ val absolute =
262
+ relative.copy(path = "https://img.example.com/a.jpg?v=2", query = mapOf("w" to "512"))
263
+
264
+ assertEquals(
265
+ "https://api.example.com/stations?genre=rock&locale=en",
266
+ RequestConfigBuilder.buildHttpRequest(relative).url,
267
+ )
268
+ assertEquals(
269
+ "https://img.example.com/a.jpg?v=2&w=512",
270
+ RequestConfigBuilder.buildHttpRequest(absolute).url,
271
+ )
272
+ }
273
+
248
274
  @Test
249
275
  fun `composeResolved merges async then sync with sync winning`() {
250
276
  val async =
@@ -1,19 +1,24 @@
1
1
  package com.audiobrowser.model
2
2
 
3
+ import com.margelo.nitro.audiobrowser.Func_std__shared_ptr_Promise_std__optional_NowPlayingUpdate____FormatNowPlayingParams as NowPlayingFormatter
3
4
  import com.margelo.nitro.audiobrowser.NativeSetupPlayerOptions
4
5
  import com.margelo.nitro.audiobrowser.RemoteOutputsOptions
5
6
  import org.junit.Assert.assertEquals
6
7
  import org.junit.Assert.assertNull
8
+ import org.junit.Assert.assertSame
7
9
  import org.junit.Test
8
10
 
9
11
  class PlayerSetupOptionsTest {
10
- private fun setup(remoteOutputs: RemoteOutputsOptions?) =
12
+ private fun setup(
13
+ remoteOutputs: RemoteOutputsOptions? = null,
14
+ nowPlayingMetadataFormatter: NowPlayingFormatter? = null,
15
+ ) =
11
16
  NativeSetupPlayerOptions(
12
17
  android = null,
13
18
  ios = null,
14
19
  options = null,
15
20
  autoUpdateNowPlayingMetadata = null,
16
- nowPlayingMetadataFormatter = null,
21
+ nowPlayingMetadataFormatter = nowPlayingMetadataFormatter,
17
22
  playWhenReady = null,
18
23
  repeatMode = null,
19
24
  retry = null,
@@ -32,4 +37,16 @@ class PlayerSetupOptionsTest {
32
37
  options.update(setup(null))
33
38
  assertNull(options.remoteOutputs)
34
39
  }
40
+
41
+ @Test
42
+ fun `a setup without a formatter removes the earlier one`() {
43
+ val options = PlayerSetupOptions()
44
+ val formatter = NowPlayingFormatter { error("not called") }
45
+
46
+ options.update(setup(nowPlayingMetadataFormatter = formatter))
47
+ assertSame(formatter, options.nowPlayingMetadataFormatter)
48
+
49
+ options.update(setup())
50
+ assertNull(options.nowPlayingMetadataFormatter)
51
+ }
35
52
  }