react-native-audio-browser 0.2.0-next.75 → 0.2.0-next.76

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 (24) hide show
  1. package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +19 -26
  2. package/android/src/main/java/com/audiobrowser/Service.kt +3 -0
  3. package/android/src/main/java/com/audiobrowser/browser/BrowserManager.kt +16 -8
  4. package/android/src/main/java/com/audiobrowser/browser/TrackLoadHandler.kt +5 -3
  5. package/android/src/main/java/com/audiobrowser/http/RequestConfigBuilder.kt +10 -2
  6. package/android/src/main/java/com/audiobrowser/player/NowPlayingUpdater.kt +3 -0
  7. package/android/src/main/java/com/audiobrowser/player/Player.kt +7 -1
  8. package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +32 -11
  9. package/android/src/main/java/com/audiobrowser/util/AwaitCancellable.kt +45 -0
  10. package/android/src/test/java/com/audiobrowser/GateDecisionTest.kt +128 -0
  11. package/android/src/test/java/com/audiobrowser/ResolveFormattedErrorTest.kt +93 -0
  12. package/android/src/test/java/com/audiobrowser/ServiceTaskRemovedTest.kt +35 -0
  13. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerLayerResolutionTest.kt +75 -5
  14. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerTest.kt +42 -0
  15. package/android/src/test/java/com/audiobrowser/browser/TrackLoadHandlerTest.kt +43 -0
  16. package/android/src/test/java/com/audiobrowser/http/RequestConfigBuilderTest.kt +62 -0
  17. package/android/src/test/java/com/audiobrowser/player/BrowseTilesTest.kt +31 -32
  18. package/android/src/test/java/com/audiobrowser/player/NowPlayingFormatterTest.kt +75 -0
  19. package/android/src/test/java/com/audiobrowser/player/NowPlayingUpdaterTest.kt +25 -0
  20. package/android/src/test/java/com/audiobrowser/player/PlayFromSearchTest.kt +108 -0
  21. package/android/src/test/java/com/audiobrowser/player/PlayerTrackChangeTest.kt +105 -0
  22. package/android/src/test/java/com/audiobrowser/util/AwaitCancellableTest.kt +136 -0
  23. package/android/src/test/java/com/audiobrowser/util/JsPromise.kt +44 -0
  24. package/package.json +2 -1
@@ -34,6 +34,8 @@ import com.audiobrowser.util.BrowserPathHelper
34
34
  import com.audiobrowser.util.OutputMonitor
35
35
  import com.audiobrowser.util.OutputSwitcher
36
36
  import com.audiobrowser.util.SystemVolumeMonitor
37
+ import com.audiobrowser.util.awaitNestedOrTimeout
38
+ import com.audiobrowser.util.awaitOrTimeout
37
39
  import com.facebook.proguard.annotations.DoNotStrip
38
40
  import com.google.common.util.concurrent.ListenableFuture
39
41
  import com.margelo.nitro.NitroModules
@@ -91,7 +93,6 @@ import com.margelo.nitro.core.NullType
91
93
  import com.margelo.nitro.core.Promise
92
94
  import java.util.concurrent.TimeUnit
93
95
  import java.util.concurrent.atomic.AtomicReference
94
- import kotlin.time.Duration.Companion.seconds
95
96
  import kotlinx.coroutines.CancellationException
96
97
  import kotlinx.coroutines.CompletableDeferred
97
98
  import kotlinx.coroutines.CoroutineScope
@@ -99,13 +100,12 @@ import kotlinx.coroutines.CoroutineStart
99
100
  import kotlinx.coroutines.DelicateCoroutinesApi
100
101
  import kotlinx.coroutines.Job
101
102
  import kotlinx.coroutines.MainScope
102
- import kotlinx.coroutines.async
103
103
  import kotlinx.coroutines.cancel
104
104
  import kotlinx.coroutines.cancelChildren
105
+ import kotlinx.coroutines.currentCoroutineContext
105
106
  import kotlinx.coroutines.ensureActive
106
107
  import kotlinx.coroutines.launch
107
108
  import kotlinx.coroutines.runBlocking
108
- import kotlinx.coroutines.withTimeoutOrNull
109
109
  import timber.log.Timber
110
110
 
111
111
  @Keep
@@ -489,7 +489,7 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
489
489
  ): FormattedNavigationError {
490
490
  val default = defaultFormattedError(error)
491
491
  val formatter = _configuration.formatNavigationError ?: return default
492
- return formattedOrDefault(mainScope, default) {
492
+ return formattedOrDefault(default) {
493
493
  formatter(
494
494
  FormatNavigationErrorParams(
495
495
  error,
@@ -498,7 +498,7 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
498
498
  BrowserPathHelper.navigationErrorKind(path),
499
499
  )
500
500
  )
501
- .await()
501
+ .awaitOrTimeout()
502
502
  }
503
503
  }
504
504
 
@@ -749,15 +749,16 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
749
749
  * Whether [request] is gated, and with which chrome. No active gate allows; a gate without a
750
750
  * resolver gates with its stored chrome and never asks JS. A resolver that throws, rejects or
751
751
  * times out fails closed, gating rather than serving content; only a successful `gated: false`
752
- * allows. Chrome falls back from the resolver's to the stored one to [builtInGate].
752
+ * allows. Chrome falls back from the resolver's to the stored one to [builtInGate]. A caller
753
+ * cancelled while it waits gets the cancellation.
753
754
  */
754
755
  suspend fun gateDecision(request: NativeGateRequest): GateOutcome {
755
756
  val s = gateState
756
757
  if (!s.active) return GateOutcome(false, null)
757
758
  if (!s.hasResolver) return GateOutcome(true, s.chrome ?: builtInGate)
758
- val decision =
759
- runCatching { resolveGate(request).await().await() }.getOrNull()
760
- ?: return GateOutcome(true, s.chrome ?: builtInGate)
759
+ val result = runCatching { resolveGate(request).awaitNestedOrTimeout() }
760
+ currentCoroutineContext().ensureActive()
761
+ val decision = result.getOrNull() ?: return GateOutcome(true, s.chrome ?: builtInGate)
761
762
  if (!decision.gated) return GateOutcome(false, null)
762
763
  return GateOutcome(true, decision.gate ?: s.chrome ?: builtInGate)
763
764
  }
@@ -1490,9 +1491,6 @@ private fun NativeRouteEntry.strippingJSCallbacks() =
1490
1491
  artwork = artwork?.strippingJSCallbacks(),
1491
1492
  )
1492
1493
 
1493
- // The budget [Player.awaitBrowser] gives JS, the other JS wait a browse serve blocks on.
1494
- private val FORMATTER_TIMEOUT = 10.seconds
1495
-
1496
1494
  /**
1497
1495
  * The navigation error [e] raises, shared by failed navigations, the rejection
1498
1496
  * [AudioBrowser.search] hands JS and the Android Auto browse-error tile, so one failure is named
@@ -1559,23 +1557,18 @@ internal fun defaultFormattedError(error: NavigationError): FormattedNavigationE
1559
1557
  return FormattedNavigationError(title, error.message.takeIf { it.isNotEmpty() })
1560
1558
  }
1561
1559
 
1562
- /**
1563
- * The app's formatted error from [format], or [default] when it returns null, throws, or outruns
1564
- * [FORMATTER_TIMEOUT].
1565
- *
1566
- * [format] runs in [scope] and is awaited through the Deferred because Nitro's `Promise.await`
1567
- * parks in a plain `suspendCoroutine` that cancellation does not unpark; awaiting the Deferred is
1568
- * cancellable, so the timeout releases the caller instead of holding it until JS answers, which for
1569
- * a browse serve may be never.
1570
- */
1560
+ /** The app's formatted error from [format], or [default] when it returns null or throws. */
1571
1561
  internal suspend fun formattedOrDefault(
1572
- scope: CoroutineScope,
1573
1562
  default: FormattedNavigationError,
1574
1563
  format: suspend () -> FormattedNavigationError?,
1575
- ): FormattedNavigationError {
1576
- val hop = scope.async { runCatching { format() }.getOrNull() }
1577
- return withTimeoutOrNull(FORMATTER_TIMEOUT) { hop.await() } ?: default
1578
- }
1564
+ ): FormattedNavigationError =
1565
+ try {
1566
+ format()
1567
+ } catch (e: CancellationException) {
1568
+ throw e
1569
+ } catch (e: Exception) {
1570
+ null
1571
+ } ?: default
1579
1572
 
1580
1573
  /**
1581
1574
  * Runs [run] in this scope and hands its outcome to [settle] once. Unlike Nitro's `Promise.async`,
@@ -37,6 +37,7 @@ import kotlinx.coroutines.Dispatchers
37
37
  import kotlinx.coroutines.MainScope
38
38
  import kotlinx.coroutines.SupervisorJob
39
39
  import kotlinx.coroutines.cancel
40
+ import kotlinx.coroutines.cancelChildren
40
41
  import kotlinx.coroutines.isActive
41
42
  import timber.log.Timber
42
43
 
@@ -271,6 +272,8 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
271
272
  } else {
272
273
  Timber.d("No car connected - stopping playback, moduleBound = $moduleBound")
273
274
  stopPlaybackAndRemoveNotification()
275
+ // Ends a waiting play-from-search, also while AudioBrowser is bound.
276
+ scope.coroutineContext.cancelChildren()
274
277
  // AudioBrowser keeps the player. Otherwise tear down now: a media controller still bound
275
278
  // keeps the service alive after stopSelf().
276
279
  if (!moduleBound) tearDown()
@@ -8,8 +8,12 @@ import com.audiobrowser.extension.identity
8
8
  import com.audiobrowser.http.HttpClient
9
9
  import com.audiobrowser.http.RequestConfigBuilder
10
10
  import com.audiobrowser.util.BrowserPathHelper
11
+ import com.audiobrowser.util.FALLBACK_TIMEOUT
11
12
  import com.audiobrowser.util.TrackFactory
12
13
  import com.audiobrowser.util.artworkOf
14
+ import com.audiobrowser.util.awaitCancellable
15
+ import com.audiobrowser.util.awaitNested
16
+ import com.audiobrowser.util.awaitOrTimeout
13
17
  import com.margelo.nitro.audiobrowser.ArtworkRequestConfig
14
18
  import com.margelo.nitro.audiobrowser.BrowserSourceCallbackParam
15
19
  import com.margelo.nitro.audiobrowser.Func_std__shared_ptr_Promise_std__shared_ptr_Promise_TransformableRequestConfig____
@@ -25,6 +29,7 @@ import com.margelo.nitro.audiobrowser.StyleDisplay
25
29
  import com.margelo.nitro.audiobrowser.Track
26
30
  import com.margelo.nitro.audiobrowser.TransformableRequestConfig
27
31
  import com.margelo.nitro.core.Promise
32
+ import kotlinx.coroutines.CancellationException
28
33
  import kotlinx.coroutines.Dispatchers
29
34
  import kotlinx.coroutines.async
30
35
  import kotlinx.coroutines.awaitAll
@@ -677,6 +682,8 @@ class BrowserManager {
677
682
  "singleTrack=false - returning ${playableTracks.size} playable tracks (from ${sectionTracks.size} in section), starting at index $selectedIndex"
678
683
  )
679
684
  return Pair(playableTracks.toTypedArray(), selectedIndex)
685
+ } catch (e: CancellationException) {
686
+ throw e
680
687
  } catch (e: Exception) {
681
688
  Timber.e(e, "Error expanding queue from contextual path: $contextualPath")
682
689
  return null
@@ -962,13 +969,13 @@ class BrowserManager {
962
969
  // Nitro flattens `(ResolvedTrack | BrowseError) | Promise<BrowseResult>` into three arms.
963
970
  return callback
964
971
  .invoke(param)
965
- .await()
972
+ .awaitCancellable()
966
973
  .match(
967
974
  first = { resolvedTrack -> resolvedTrack },
968
975
  second = { browseError -> throw CallbackException(browseError.error) },
969
976
  third = { promise ->
970
977
  promise
971
- .await()
978
+ .awaitCancellable()
972
979
  .match(
973
980
  first = { resolvedTrack -> resolvedTrack },
974
981
  second = { browseError -> throw CallbackException(browseError.error) },
@@ -1001,9 +1008,7 @@ class BrowserManager {
1001
1008
 
1002
1009
  searchEntry.searchCallback?.let { callback ->
1003
1010
  Timber.d("Resolving search via callback")
1004
- val promise = callback.invoke(params)
1005
- val innerPromise = promise.await()
1006
- return innerPromise.await()
1011
+ return callback.invoke(params).awaitNested()
1007
1012
  }
1008
1013
 
1009
1014
  searchEntry.searchConfig?.let { apiConfig ->
@@ -1036,7 +1041,7 @@ class BrowserManager {
1036
1041
  ): TransformableRequestConfig? {
1037
1042
  if (resolver == null) return staticConfig
1038
1043
  // The TS layer wraps the thunk in Promise.resolve: await the bridge promise, then the JS one.
1039
- return resolver.invoke().await().await()
1044
+ return resolver.invoke().awaitNested()
1040
1045
  }
1041
1046
 
1042
1047
  // No in-flight dedupe: concurrent first requests may both resolve, which is harmless, and a
@@ -1064,14 +1069,17 @@ class BrowserManager {
1064
1069
  /**
1065
1070
  * The title of the "view more" row appended to a pathed section where the header can't be tapped
1066
1071
  * (Android Auto). Re-read once per generation, so invalidateAllContent picks up a new language.
1067
- * Falls back to [DEFAULT_VIEW_MORE_TITLE] when unset, blank or throwing.
1072
+ * Falls back to [DEFAULT_VIEW_MORE_TITLE] when unset, blank, throwing or outrunning
1073
+ * [FALLBACK_TIMEOUT].
1068
1074
  */
1069
1075
  internal suspend fun viewMoreTitle(): String {
1070
1076
  val generation = layerGeneration
1071
1077
  if (resolvedViewMoreTitleGeneration == generation) return resolvedViewMoreTitle
1072
1078
  val title =
1073
1079
  try {
1074
- config.viewMoreTitle?.invoke()?.await()?.takeIf { it.isNotBlank() }
1080
+ config.viewMoreTitle?.invoke()?.awaitOrTimeout()?.takeIf { it.isNotBlank() }
1081
+ } catch (e: CancellationException) {
1082
+ throw e
1075
1083
  } catch (e: Exception) {
1076
1084
  Timber.e(e, "viewMoreTitle callback failed; falling back to the default")
1077
1085
  null
@@ -1,8 +1,10 @@
1
1
  package com.audiobrowser.browser
2
2
 
3
+ import com.audiobrowser.util.awaitNested
3
4
  import com.margelo.nitro.audiobrowser.Track
4
5
  import com.margelo.nitro.audiobrowser.TrackLoadEvent
5
6
  import com.margelo.nitro.core.Promise
7
+ import kotlinx.coroutines.CancellationException
6
8
  import timber.log.Timber
7
9
 
8
10
  /**
@@ -23,9 +25,9 @@ suspend fun <T> handleTrackLoad(
23
25
  if (handler != null) {
24
26
  val event = TrackLoadEvent(track, queue, startIndex)
25
27
  try {
26
- val outerPromise = handler(event)
27
- val innerPromise = outerPromise.await()
28
- innerPromise.await()
28
+ handler(event).awaitNested()
29
+ } catch (e: CancellationException) {
30
+ throw e
29
31
  } catch (e: Exception) {
30
32
  Timber.e(e, "handleTrackLoad failed")
31
33
  }
@@ -1,6 +1,8 @@
1
1
  package com.audiobrowser.http
2
2
 
3
3
  import com.audiobrowser.util.BrowserPathHelper
4
+ import com.audiobrowser.util.awaitCancellable
5
+ import com.audiobrowser.util.awaitNested
4
6
  import com.margelo.nitro.audiobrowser.ArtworkRequestConfig
5
7
  import com.margelo.nitro.audiobrowser.MediaRequestConfig
6
8
  import com.margelo.nitro.audiobrowser.RequestConfig
@@ -8,6 +10,7 @@ import com.margelo.nitro.audiobrowser.Track
8
10
  import com.margelo.nitro.audiobrowser.TransformableRequestConfig
9
11
  import com.margelo.nitro.core.Promise
10
12
  import java.net.URLEncoder
13
+ import kotlinx.coroutines.CancellationException
11
14
  import kotlinx.coroutines.Dispatchers
12
15
  import kotlinx.coroutines.withContext
13
16
  import timber.log.Timber
@@ -58,9 +61,10 @@ object RequestConfigBuilder {
58
61
  * JS promise); awaiting it once hands a Promise downstream as the config.
59
62
  */
60
63
  suspend fun awaitAsyncConfig(promise: Promise<Promise<RequestConfig>>): RequestConfig =
61
- promise.await().await()
64
+ promise.awaitNested()
62
65
 
63
- suspend fun awaitSyncConfig(promise: Promise<RequestConfig>): RequestConfig = promise.await()
66
+ suspend fun awaitSyncConfig(promise: Promise<RequestConfig>): RequestConfig =
67
+ promise.awaitCancellable()
64
68
 
65
69
  private fun MediaRequestConfig.withRequestFields(c: RequestConfig) =
66
70
  MediaRequestConfig(
@@ -104,6 +108,8 @@ object RequestConfigBuilder {
104
108
  override.transform?.let { result = awaitAsyncConfig(it.invoke(result, routeParams)) }
105
109
  override.transformSync?.let { result = awaitSyncConfig(it.invoke(result, routeParams)) }
106
110
  result
111
+ } catch (e: CancellationException) {
112
+ throw e
107
113
  } catch (e: Exception) {
108
114
  Timber.e(e, "Failed to apply transform function, using base config")
109
115
  base
@@ -147,6 +153,8 @@ object RequestConfigBuilder {
147
153
  val asyncResolved = layered.resolve?.let { awaitAsyncConfig(it.invoke(track)) }
148
154
  val syncResolved = layered.resolveSync?.let { awaitSyncConfig(it.invoke(track)) }
149
155
  composeResolved(asyncResolved, syncResolved) ?: return layered
156
+ } catch (e: CancellationException) {
157
+ throw e
150
158
  } catch (e: Exception) {
151
159
  Timber.e(e, "Failed to apply media.resolve, using layered config")
152
160
  return layered
@@ -10,6 +10,7 @@ import com.margelo.nitro.audiobrowser.PlaybackState
10
10
  import com.margelo.nitro.audiobrowser.StallReason
11
11
  import com.margelo.nitro.audiobrowser.TimedMetadata
12
12
  import com.margelo.nitro.audiobrowser.Track
13
+ import kotlinx.coroutines.CancellationException
13
14
  import kotlinx.coroutines.CoroutineScope
14
15
  import kotlinx.coroutines.Job
15
16
  import kotlinx.coroutines.cancel
@@ -255,6 +256,8 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
255
256
  val formatted =
256
257
  try {
257
258
  activeFormatter(params)
259
+ } catch (e: CancellationException) {
260
+ throw e
258
261
  } catch (e: Exception) {
259
262
  Timber.e(e, "NowPlaying formatter threw; using default")
260
263
  null
@@ -40,6 +40,7 @@ import com.audiobrowser.util.RepeatModeFactory
40
40
  import com.audiobrowser.util.SvgArtworkRenderer
41
41
  import com.audiobrowser.util.TrackFactory
42
42
  import com.audiobrowser.util.TrackFactory.setFavorite
43
+ import com.audiobrowser.util.awaitOrTimeout
43
44
  import com.audiobrowser.util.isAutomotive
44
45
  import com.margelo.nitro.audiobrowser.AppKilledPlaybackBehavior
45
46
  import com.margelo.nitro.audiobrowser.FavoriteChangedEvent
@@ -68,6 +69,8 @@ import kotlinx.coroutines.CoroutineScope
68
69
  import kotlinx.coroutines.Dispatchers
69
70
  import kotlinx.coroutines.MainScope
70
71
  import kotlinx.coroutines.TimeoutCancellationException
72
+ import kotlinx.coroutines.currentCoroutineContext
73
+ import kotlinx.coroutines.ensureActive
71
74
  import kotlinx.coroutines.withContext
72
75
  import kotlinx.coroutines.withTimeout
73
76
  import timber.log.Timber
@@ -411,7 +414,9 @@ internal constructor(
411
414
  nowPlaying.enabled = setupOptions.autoUpdateNowPlayingMetadata
412
415
  // Unwrapped from the Nitro Func so the updater never touches bridge types.
413
416
  nowPlaying.formatter =
414
- setupOptions.nowPlayingMetadataFormatter?.let { f -> { params -> f.invoke(params).await() } }
417
+ setupOptions.nowPlayingMetadataFormatter?.let { f ->
418
+ { params -> f.invoke(params).awaitOrTimeout() }
419
+ }
415
420
 
416
421
  val newEngineOptions = setupOptions.engineOptions()
417
422
  if (newEngineOptions == engineOptions) {
@@ -901,6 +906,7 @@ internal constructor(
901
906
  false
902
907
  }
903
908
  } catch (e: Exception) {
909
+ currentCoroutineContext().ensureActive()
904
910
  Timber.e(e, "Error handling voice search: ${params}")
905
911
  false
906
912
  }
@@ -29,7 +29,7 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
29
29
  private val stuckRecoveryPolicy = StuckRecoveryPolicy()
30
30
 
31
31
  // Main looper: Player.Listener callbacks arrive on the main thread.
32
- private val healthyPlaybackHandler = Handler(Looper.getMainLooper())
32
+ private val mainHandler = Handler(Looper.getMainLooper())
33
33
  private val healthyPlaybackRunnable =
34
34
  object : Runnable {
35
35
  override fun run() {
@@ -39,12 +39,34 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
39
39
  player.resetRetryTimer()
40
40
  // Re-arm while playing: errors the buffer absorbs never flip isPlaying.
41
41
  if (player.isPlaying) {
42
- healthyPlaybackHandler.postDelayed(this, HEALTHY_PLAYBACK_MS)
42
+ mainHandler.postDelayed(this, HEALTHY_PLAYBACK_MS)
43
43
  }
44
44
  }
45
45
  }
46
46
 
47
+ /**
48
+ * Set from an app-started track change until the playback thread has handled it. Until then every
49
+ * metadata delivery is the outgoing item's: its renderer posted them to the main looper before
50
+ * the change, and nothing removes them.
51
+ */
52
+ private var metadataFence: Any? = null
53
+
54
+ /**
55
+ * Its target runs on the playback thread right after the command that changed the item. A
56
+ * main-looper target goes to the back of that thread's queue, where a release would drop it.
57
+ */
58
+ private fun fenceOutgoingMetadata() {
59
+ val fence = Any()
60
+ metadataFence = fence
61
+ player.exoPlayer
62
+ .createMessage { _, _ ->
63
+ mainHandler.post { if (metadataFence === fence) metadataFence = null }
64
+ }
65
+ .send()
66
+ }
67
+
47
68
  override fun onMetadata(metadata: Metadata) {
69
+ if (metadataFence != null) return
48
70
  val chapters = MetadataAdapter.extractChapters(metadata)
49
71
  if (chapters.isNotEmpty()) {
50
72
  player.callbacks?.onChapterMetadata(chapters)
@@ -81,15 +103,14 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
81
103
  index = player.currentIndex?.toDouble(),
82
104
  track = player.currentTrack,
83
105
  )
106
+ val ended =
107
+ reason == MediaPlayer.MEDIA_ITEM_TRANSITION_REASON_AUTO ||
108
+ reason == MediaPlayer.MEDIA_ITEM_TRANSITION_REASON_REPEAT
84
109
  player.nowPlaying.clearOverride()
110
+ if (!ended) fenceOutgoingMetadata()
85
111
  player.callbacks?.onPlaybackActiveTrackChanged(event)
86
112
 
87
- if (
88
- reason == MediaPlayer.MEDIA_ITEM_TRANSITION_REASON_AUTO ||
89
- reason == MediaPlayer.MEDIA_ITEM_TRANSITION_REASON_REPEAT
90
- ) {
91
- player.sleepTimer.onTrackEnd()
92
- }
113
+ if (ended) player.sleepTimer.onTrackEnd()
93
114
 
94
115
  player.lastTrack = player.currentTrack
95
116
  player.lastIndex = player.currentIndex
@@ -107,7 +128,7 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
107
128
  // Emits on its own: the incoming track may hold LOADING/BUFFERING and emit no state change.
108
129
  player.clearRetryingError()
109
130
 
110
- healthyPlaybackHandler.removeCallbacks(healthyPlaybackRunnable)
131
+ mainHandler.removeCallbacks(healthyPlaybackRunnable)
111
132
  stuckRecoveryPolicy.reset()
112
133
 
113
134
  player.playbackStateStore.save()
@@ -115,9 +136,9 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
115
136
  }
116
137
 
117
138
  override fun onIsPlayingChanged(isPlaying: Boolean) {
118
- healthyPlaybackHandler.removeCallbacks(healthyPlaybackRunnable)
139
+ mainHandler.removeCallbacks(healthyPlaybackRunnable)
119
140
  if (isPlaying) {
120
- healthyPlaybackHandler.postDelayed(healthyPlaybackRunnable, HEALTHY_PLAYBACK_MS)
141
+ mainHandler.postDelayed(healthyPlaybackRunnable, HEALTHY_PLAYBACK_MS)
121
142
  }
122
143
  }
123
144
 
@@ -0,0 +1,45 @@
1
+ package com.audiobrowser.util
2
+
3
+ import com.margelo.nitro.core.Promise
4
+ import java.util.concurrent.TimeoutException
5
+ import kotlin.coroutines.resume
6
+ import kotlin.coroutines.resumeWithException
7
+ import kotlin.time.Duration.Companion.seconds
8
+ import kotlinx.coroutines.TimeoutCancellationException
9
+ import kotlinx.coroutines.currentCoroutineContext
10
+ import kotlinx.coroutines.ensureActive
11
+ import kotlinx.coroutines.suspendCancellableCoroutine
12
+ import kotlinx.coroutines.withTimeout
13
+
14
+ /** How long a JS callback may take where its caller falls back on a failure. */
15
+ internal val FALLBACK_TIMEOUT = 10.seconds
16
+
17
+ /** Awaits this JS promise. Unlike Nitro's `await`, a cancelled caller resumes at once. */
18
+ internal suspend fun <T> Promise<T>.awaitCancellable(): T = settled()
19
+
20
+ /** [awaitCancellable] for a JS callback that returns a promise, behind Nitro's bridge promise. */
21
+ internal suspend fun <T> Promise<Promise<T>>.awaitNested(): T = settled().settled()
22
+
23
+ /**
24
+ * [awaitCancellable], failing with a [TimeoutException], which is not a cancellation, after
25
+ * [FALLBACK_TIMEOUT].
26
+ */
27
+ internal suspend fun <T> Promise<T>.awaitOrTimeout(): T = withTimeoutAsFailure { settled() }
28
+
29
+ /** [awaitNested], failing as [awaitOrTimeout] does; the timeout covers both promises. */
30
+ internal suspend fun <T> Promise<Promise<T>>.awaitNestedOrTimeout(): T = withTimeoutAsFailure {
31
+ settled().settled()
32
+ }
33
+
34
+ private suspend fun <T> withTimeoutAsFailure(block: suspend () -> T): T =
35
+ try {
36
+ withTimeout(FALLBACK_TIMEOUT) { block() }
37
+ } catch (e: TimeoutCancellationException) {
38
+ currentCoroutineContext().ensureActive()
39
+ throw TimeoutException("JS callback outran $FALLBACK_TIMEOUT")
40
+ }
41
+
42
+ private suspend fun <T> Promise<T>.settled(): T = suspendCancellableCoroutine { c ->
43
+ then { c.resume(it) }
44
+ catch { c.resumeWithException(it) }
45
+ }
@@ -0,0 +1,128 @@
1
+ package com.audiobrowser
2
+
3
+ import com.audiobrowser.util.FALLBACK_TIMEOUT
4
+ import com.audiobrowser.util.JsPromise
5
+ import com.margelo.nitro.audiobrowser.Gate
6
+ import com.margelo.nitro.audiobrowser.GateDecision
7
+ import com.margelo.nitro.audiobrowser.GateReason
8
+ import com.margelo.nitro.audiobrowser.NativeGateRequest
9
+ import com.margelo.nitro.core.Promise
10
+ import kotlin.time.Duration.Companion.seconds
11
+ import kotlinx.coroutines.CancellationException
12
+ import kotlinx.coroutines.Job
13
+ import kotlinx.coroutines.async
14
+ import kotlinx.coroutines.launch
15
+ import kotlinx.coroutines.test.advanceTimeBy
16
+ import kotlinx.coroutines.test.runCurrent
17
+ import kotlinx.coroutines.test.runTest
18
+ import org.junit.Assert.assertFalse
19
+ import org.junit.Assert.assertNull
20
+ import org.junit.Assert.assertTrue
21
+ import org.junit.Test
22
+ import org.mockito.Mockito.CALLS_REAL_METHODS
23
+ import org.mockito.Mockito.mock
24
+
25
+ class GateDecisionTest {
26
+
27
+ // AudioBrowser's constructor needs JNI, so the browser is a mock that runs its real methods,
28
+ // with an active gate written to the field setGate writes.
29
+ private fun gatedBrowser(
30
+ resolveGate: (NativeGateRequest) -> Promise<Promise<GateDecision>>
31
+ ): AudioBrowser {
32
+ val browser = mock(AudioBrowser::class.java, CALLS_REAL_METHODS)
33
+ val gateState =
34
+ Class.forName("com.audiobrowser.AudioBrowser\$GateState")
35
+ .getDeclaredConstructor(Boolean::class.java, Gate::class.java, Boolean::class.java)
36
+ .apply { isAccessible = true }
37
+ .newInstance(true, Gate("Gated", null), true)
38
+ AudioBrowser::class
39
+ .java
40
+ .getDeclaredField("gateState")
41
+ .apply { isAccessible = true }
42
+ .set(browser, gateState)
43
+ browser.resolveGate = resolveGate
44
+ return browser
45
+ }
46
+
47
+ private val request = NativeGateRequest(GateReason.SEARCH, null, null)
48
+
49
+ @Test
50
+ fun `a decision whose caller is cancelled while it waits returns nothing`() = runTest {
51
+ var outcome: AudioBrowser.GateOutcome? = null
52
+ lateinit var caller: Job
53
+ val browser = gatedBrowser {
54
+ caller.cancel()
55
+ // Cancelled while the resolver runs, which then fails.
56
+ throw RuntimeException("Rejected")
57
+ }
58
+
59
+ caller = launch { outcome = browser.gateDecision(request) }
60
+ caller.join()
61
+
62
+ assertNull(outcome)
63
+ }
64
+
65
+ @Test
66
+ fun `a resolver's own cancellation fails closed while its caller is active`() = runTest {
67
+ val browser = gatedBrowser { throw CancellationException("Timed out") }
68
+
69
+ assertTrue(browser.gateDecision(request).gated)
70
+ }
71
+
72
+ /** A gated browser whose resolver's JS promise the test settles. */
73
+ private fun pendingResolver(): Pair<AudioBrowser, JsPromise<GateDecision>> {
74
+ val decision = JsPromise<GateDecision>()
75
+ val bridge = JsPromise<Promise<GateDecision>>().apply { resolve(decision.promise) }
76
+ return gatedBrowser { bridge.promise } to decision
77
+ }
78
+
79
+ @Test
80
+ fun `a resolver answering inside the timeout decides`() =
81
+ runTest(timeout = 5.seconds) {
82
+ val (browser, decision) = pendingResolver()
83
+ val outcome = backgroundScope.async { browser.gateDecision(request) }
84
+ runCurrent()
85
+
86
+ advanceTimeBy(FALLBACK_TIMEOUT - 1.seconds)
87
+ decision.resolve(GateDecision(false, null))
88
+ runCurrent()
89
+
90
+ assertTrue(outcome.isCompleted)
91
+ assertFalse(outcome.await().gated)
92
+ }
93
+
94
+ @Test
95
+ fun `a resolver that never answers fails closed at the timeout`() =
96
+ runTest(timeout = 5.seconds) {
97
+ val (browser, _) = pendingResolver()
98
+ val outcome = backgroundScope.async { browser.gateDecision(request) }
99
+
100
+ advanceTimeBy(FALLBACK_TIMEOUT - 1.seconds)
101
+ runCurrent()
102
+ assertFalse(outcome.isCompleted)
103
+ advanceTimeBy(2.seconds)
104
+ runCurrent()
105
+
106
+ assertTrue(outcome.isCompleted)
107
+ assertTrue(outcome.await().gated)
108
+ }
109
+
110
+ @Test
111
+ fun `a caller cancelled while the resolver is silent stops waiting`() =
112
+ runTest(timeout = 5.seconds) {
113
+ val (browser, _) = pendingResolver()
114
+ var returned = false
115
+ val outcome =
116
+ backgroundScope.launch {
117
+ browser.gateDecision(request)
118
+ returned = true
119
+ }
120
+ runCurrent()
121
+
122
+ outcome.cancel()
123
+ runCurrent()
124
+
125
+ assertTrue(outcome.isCompleted)
126
+ assertFalse(returned)
127
+ }
128
+ }