react-native-audio-browser 0.2.0-next.48 → 0.2.0-next.49

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.
@@ -198,10 +198,10 @@ class MediaSessionCallback(private val player: Player) :
198
198
  controller: MediaSession.ControllerInfo,
199
199
  rating: Rating,
200
200
  ): ListenableFuture<SessionResult> {
201
- // A heart rating from a controller (e.g. Google Assistant "I like this") toggles the
202
- // now-playing favorite. setActiveTrackFavorited fires onFavoriteChanged so the consumer
203
- // persists it — the same path as the notification / CarPlay heart button. Report an honest
204
- // result (see onCustomCommand): INVALID_STATE when there is no current track to favorite.
201
+ // A heart rating toggles the now-playing favorite. setActiveTrackFavorited fires
202
+ // onFavoriteChanged so the consumer persists it — the same path as the favorite button. Report
203
+ // an honest result (see onCustomCommand): INVALID_STATE when there is no current track to
204
+ // favorite.
205
205
  RatingFavorites.favoritedFor(rating)?.let { favorited ->
206
206
  val applied = player.setActiveTrackFavorited(favorited)
207
207
  return Futures.immediateFuture(
@@ -11,11 +11,15 @@ import com.margelo.nitro.audiobrowser.RemoteButton
11
11
  import com.margelo.nitro.audiobrowser.RemoteButtonLayout
12
12
  import timber.log.Timber
13
13
 
14
- /** Previous in BACK or Next in FORWARD: where a controller draws its own skip buttons. */
15
- private val SlottedButton.isStandardSkip: Boolean
16
- get() =
17
- (button == RemoteButton.SKIP_TO_PREVIOUS && slot == ButtonSlot.BACK) ||
18
- (button == RemoteButton.SKIP_TO_NEXT && slot == ButtonSlot.FORWARD)
14
+ /**
15
+ * Whether a surface draws this button itself, from the standard PlaybackState: Previous in BACK and
16
+ * Next in FORWARD everywhere (the standard skip actions), and the favorite on Android Automotive OS
17
+ * (the heart `userRating`, drawn as the car media app's rating control).
18
+ */
19
+ private fun SlottedButton.isDrawnBySurface(automotive: Boolean): Boolean =
20
+ (button == RemoteButton.SKIP_TO_PREVIOUS && slot == ButtonSlot.BACK) ||
21
+ (button == RemoteButton.SKIP_TO_NEXT && slot == ButtonSlot.FORWARD) ||
22
+ (automotive && button == RemoteButton.FAVORITE)
19
23
 
20
24
  /**
21
25
  * A slot's Media3 preference list: the requested slot, then OVERFLOW as a fallback.
@@ -130,16 +134,25 @@ class MediaSessionCommandManager(private val automotive: Boolean) {
130
134
  private var currentForwardJumpInterval: Double = DEFAULT_JUMP_INTERVAL
131
135
  private var currentBackwardJumpInterval: Double = DEFAULT_JUMP_INTERVAL
132
136
 
133
- /** The Media3 player command behind each Capability (FAVORITE is a session command). */
134
- private val capabilityPlayerCommands: Map<Capability, @MediaPlayer.Command Int> =
137
+ /**
138
+ * The Media3 player commands behind each Capability (FAVORITE is a session command). Skip has two
139
+ * each: Media3 advertises the platform skip action for either, and its notification's own skip
140
+ * buttons use the media-item one, so a disabled skip must remove both.
141
+ */
142
+ private val capabilityPlayerCommands: Map<Capability, List<@MediaPlayer.Command Int>> =
135
143
  mapOf(
136
- Capability.PLAY_PAUSE to MediaPlayer.COMMAND_PLAY_PAUSE,
137
- Capability.STOP to MediaPlayer.COMMAND_STOP,
138
- Capability.SEEK_TO to MediaPlayer.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM,
139
- Capability.SKIP_TO_NEXT to MediaPlayer.COMMAND_SEEK_TO_NEXT,
140
- Capability.SKIP_TO_PREVIOUS to MediaPlayer.COMMAND_SEEK_TO_PREVIOUS,
141
- Capability.JUMP_FORWARD to MediaPlayer.COMMAND_SEEK_FORWARD,
142
- Capability.JUMP_BACKWARD to MediaPlayer.COMMAND_SEEK_BACK,
144
+ Capability.PLAY_PAUSE to listOf(MediaPlayer.COMMAND_PLAY_PAUSE),
145
+ Capability.STOP to listOf(MediaPlayer.COMMAND_STOP),
146
+ Capability.SEEK_TO to listOf(MediaPlayer.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM),
147
+ Capability.SKIP_TO_NEXT to
148
+ listOf(MediaPlayer.COMMAND_SEEK_TO_NEXT, MediaPlayer.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM),
149
+ Capability.SKIP_TO_PREVIOUS to
150
+ listOf(
151
+ MediaPlayer.COMMAND_SEEK_TO_PREVIOUS,
152
+ MediaPlayer.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM,
153
+ ),
154
+ Capability.JUMP_FORWARD to listOf(MediaPlayer.COMMAND_SEEK_FORWARD),
155
+ Capability.JUMP_BACKWARD to listOf(MediaPlayer.COMMAND_SEEK_BACK),
143
156
  )
144
157
 
145
158
  // Declared above `init` deliberately: `init` calls `buildPlayerCommands`, which reads
@@ -331,15 +344,10 @@ class MediaSessionCommandManager(private val automotive: Boolean) {
331
344
  ): MediaPlayer.Commands {
332
345
  val playerCommandsBuilder = MediaSession.ConnectionResult.DEFAULT_PLAYER_COMMANDS.buildUpon()
333
346
 
334
- // Always filter out direct media item commands to avoid dual-command confusion.
335
- // This forces MediaSession to only use the "smart" commands we can control via capabilities.
336
- playerCommandsBuilder.remove(MediaPlayer.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM)
337
- playerCommandsBuilder.remove(MediaPlayer.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM)
338
-
339
- capabilityPlayerCommands.forEach { (capability, command) ->
347
+ capabilityPlayerCommands.forEach { (capability, commands) ->
340
348
  if (!capabilities.isEnabled(capability)) {
341
- playerCommandsBuilder.remove(command)
342
- Timber.Forest.d("Removed command: $command ($capability disabled)")
349
+ commands.forEach { playerCommandsBuilder.remove(it) }
350
+ Timber.Forest.d("Removed commands: $commands ($capability disabled)")
343
351
  }
344
352
  }
345
353
 
@@ -370,6 +378,12 @@ class MediaSessionCommandManager(private val automotive: Boolean) {
370
378
  Timber.Forest.d("Removed search commands - search not configured")
371
379
  }
372
380
 
381
+ // Media3 always advertises the platform rating action; without this command a rating, which
382
+ // sets the favorite, is refused.
383
+ if (!capabilities.isEnabled(Capability.FAVORITE)) {
384
+ sessionCommandsBuilder.remove(SessionCommand.COMMAND_CODE_SESSION_SET_RATING)
385
+ }
386
+
373
387
  RemoteButton.entries
374
388
  .filter { capabilities.allows(it) }
375
389
  .mapNotNull { customCommandFor(it) }
@@ -438,9 +452,10 @@ class MediaSessionCommandManager(private val automotive: Boolean) {
438
452
  * Assembles the CommandButtons for an already-derived slot layout (see [deriveButtonSlots] — the
439
453
  * slots are pre-filtered by Capability).
440
454
  *
441
- * On Android Automotive OS, Previous in BACK and Next in FORWARD are left out, so Media3 keeps
442
- * them as the PlaybackState's standard skip actions, which the car media app draws either side of
443
- * play/pause. Sent as buttons they arrive as custom actions, which it places by its own rules.
455
+ * Buttons a surface draws itself are left out ([isDrawnBySurface]): Media3 then keeps the
456
+ * standard skip actions and reserves their slots. Sent as buttons they arrive as custom actions,
457
+ * which Android Automotive OS's car media app places by its own rules, not either side of
458
+ * play/pause.
444
459
  *
445
460
  * Each button gets its requested slot followed by OVERFLOW as a fallback. `slots` is an ordered
446
461
  * preference list, and every surface caps how many buttons it renders — a head unit, the
@@ -452,7 +467,7 @@ class MediaSessionCommandManager(private val automotive: Boolean) {
452
467
  favorited: Boolean?,
453
468
  ): List<CommandButton> =
454
469
  slots
455
- .filterNot { automotive && it.isStandardSkip }
470
+ .filterNot { it.isDrawnBySurface(automotive) }
456
471
  .map { (button, slot) ->
457
472
  buttonFor(button, favorited).setSlots(*media3SlotsFor(slot)).build()
458
473
  }
@@ -6,6 +6,7 @@ import android.os.Handler
6
6
  import android.os.Looper
7
7
  import androidx.core.net.toUri
8
8
  import androidx.media3.common.C
9
+ import androidx.media3.common.MediaItem
9
10
  import androidx.media3.common.MediaMetadata
10
11
  import androidx.media3.database.StandaloneDatabaseProvider
11
12
  import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor
@@ -140,6 +141,7 @@ class Player(internal val context: Context) {
140
141
 
141
142
  init {
142
143
  Automotive.device = context.isAutomotive
144
+ TrackFactory.favoriteEnabled = options.capabilities.favoriteEnabled
143
145
  TrackFactory.artworkRoutes =
144
146
  ArtworkRoutes(browseArtworkRegistry, ArtworkUris.authorityFor(context.packageName))
145
147
  }
@@ -746,23 +748,8 @@ class Player(internal val context: Context) {
746
748
  val index = exoPlayer.currentMediaItemIndex
747
749
  if (index == C.INDEX_UNSET) return true
748
750
 
749
- // Create updated Track with new favorited state
750
751
  val updatedTrack = currentTrack.copy(favorited = favorited)
751
-
752
- // Use buildUpon() on the existing MediaItem to update only the metadata
753
- // This preserves internal references and avoids playback interruption
754
- // Note: setTag() requires setUri() to be called, so we must re-set the URI
755
- val currentMediaItem = exoPlayer.getMediaItemAt(index)
756
- val updatedMetadata = currentMediaItem.mediaMetadata.buildUpon().setFavorite(favorited).build()
757
- val updatedMediaItem =
758
- currentMediaItem
759
- .buildUpon()
760
- .setUri(currentMediaItem.localConfiguration?.uri)
761
- .setMediaMetadata(updatedMetadata)
762
- .setTag(updatedTrack)
763
- .build()
764
-
765
- exoPlayer.replaceMediaItem(index, updatedMediaItem)
752
+ restampMediaItem(index, updatedTrack) { setFavorite(favorited) }
766
753
 
767
754
  // Update the heart button icon in notification/Android Auto
768
755
  updateFavoriteButtonState(favorited)
@@ -868,23 +855,44 @@ class Player(internal val context: Context) {
868
855
  MainScope(),
869
856
  )
870
857
 
858
+ /**
859
+ * Restamps every queued item's heart rating after the favorite capability changed, in one
860
+ * replacement: each separate one would be a timeline change, and a queue event to JS.
861
+ */
862
+ private fun restampFavorites() {
863
+ if (!::exoPlayer.isInitialized || exoPlayer.mediaItemCount == 0) return
864
+ val items =
865
+ (0 until exoPlayer.mediaItemCount).map { index ->
866
+ val item = exoPlayer.getMediaItemAt(index)
867
+ val track = item.localConfiguration?.tag as? Track ?: return@map item
868
+ item.restamped(track) { setFavorite(track.favorited) }
869
+ }
870
+ exoPlayer.replaceMediaItems(0, items.size, items)
871
+ }
872
+
871
873
  /** Republishes the item at [index] with mutated metadata, preserving uri and Track tag. */
872
874
  private fun restampMediaItem(
873
875
  index: Int,
874
876
  track: Track,
875
877
  mutate: MediaMetadata.Builder.() -> MediaMetadata.Builder,
876
878
  ) {
877
- val currentMediaItem = exoPlayer.getMediaItemAt(index)
878
- val updatedMediaItem =
879
- currentMediaItem
880
- .buildUpon()
881
- .setUri(currentMediaItem.localConfiguration?.uri)
882
- .setMediaMetadata(currentMediaItem.mediaMetadata.buildUpon().mutate().build())
883
- .setTag(track)
884
- .build()
885
- exoPlayer.replaceMediaItem(index, updatedMediaItem)
879
+ exoPlayer.replaceMediaItem(index, exoPlayer.getMediaItemAt(index).restamped(track, mutate))
886
880
  }
887
881
 
882
+ /**
883
+ * This item with mutated metadata and [track] as its tag, its uri unchanged so ExoPlayer updates
884
+ * it in place instead of reloading it.
885
+ */
886
+ private fun MediaItem.restamped(
887
+ track: Track,
888
+ mutate: MediaMetadata.Builder.() -> MediaMetadata.Builder,
889
+ ): MediaItem =
890
+ buildUpon()
891
+ .setUri(localConfiguration?.uri)
892
+ .setMediaMetadata(mediaMetadata.buildUpon().mutate().build())
893
+ .setTag(track)
894
+ .build()
895
+
888
896
  /**
889
897
  * Resets the retry timer when track changes. Called from PlayerListener.onMediaItemTransition.
890
898
  */
@@ -1324,6 +1332,10 @@ class Player(internal val context: Context) {
1324
1332
  // The `favorite` capability is the single favoriting switch — propagate
1325
1333
  // it to the browser so it can hydrate row hearts.
1326
1334
  browser?.browserManager?.setFavoriteEnabled(options.capabilities.favoriteEnabled)
1335
+ TrackFactory.favoriteEnabled = options.capabilities.favoriteEnabled
1336
+ if (previousOptions.capabilities.favoriteEnabled != options.capabilities.favoriteEnabled) {
1337
+ restampFavorites()
1338
+ }
1327
1339
  }
1328
1340
 
1329
1341
  if (progressUpdateEventIntervalChanged) {
@@ -4,8 +4,8 @@ import androidx.media3.common.HeartRating
4
4
  import androidx.media3.common.Rating
5
5
 
6
6
  /**
7
- * Maps a Media3 [Rating] arriving from a controller (e.g. Google Assistant "I like this") to a
8
- * favorite intent. Only an explicitly-rated heart carries favorite intent: a thumbs / star /
7
+ * Maps a Media3 [Rating] arriving from a controller (e.g. Android Automotive OS's rating control)
8
+ * to a favorite intent. Only an explicitly-rated heart carries favorite intent: a thumbs / star /
9
9
  * percentage rating, or an unrated (cleared) heart, returns null — no favorite change.
10
10
  */
11
11
  object RatingFavorites {
@@ -31,14 +31,26 @@ object TrackFactory {
31
31
  return provider.route(url, headers, isSvg, pinned = true)
32
32
  }
33
33
 
34
+ /** Whether favoriting is on: the `favorite` capability, set by the Player. */
35
+ @Volatile var favoriteEnabled = false
36
+
34
37
  /**
35
- * Stamps [favorited] as the heart `userRating`, which Assistant's "I like this" sets. Not on
36
- * Android Automotive OS, whose car media app draws a heart-rated session as a star among the
37
- * transport controls, beside the favorite button.
38
+ * Sets the heart `userRating`, which a controller's rating sets: [favorited], or unrated when it
39
+ * is unknown on a [playable] item, so Android Automotive OS's car media app, which draws it as
40
+ * its own favorite control, always has one to draw. None while favoriting is off.
38
41
  */
39
- fun MediaMetadata.Builder.setFavorite(favorited: Boolean?): MediaMetadata.Builder = apply {
40
- if (!Automotive.device && favorited != null) setUserRating(HeartRating(favorited))
41
- }
42
+ fun MediaMetadata.Builder.setFavorite(
43
+ favorited: Boolean?,
44
+ playable: Boolean = true,
45
+ ): MediaMetadata.Builder =
46
+ setUserRating(
47
+ when {
48
+ !favoriteEnabled -> null
49
+ favorited != null -> HeartRating(favorited)
50
+ playable -> HeartRating()
51
+ else -> null
52
+ }
53
+ )
42
54
 
43
55
  fun fromMedia3(mediaItem: MediaItem): Track {
44
56
  return mediaItem.localConfiguration!!.tag as Track
@@ -140,7 +152,7 @@ object TrackFactory {
140
152
  .setIsBrowsable(track.src == null)
141
153
  .setIsPlayable(track.src != null)
142
154
  .setExtras(MediaExtrasBuilder.build(track, section))
143
- .setFavorite(track.favorited)
155
+ .setFavorite(track.favorited, playable = track.src != null)
144
156
 
145
157
  private fun buildMediaItem(track: Track, metadata: MediaMetadata): MediaItem {
146
158
  // A playable track's mediaId is the consumer's stable `id` when it has one —
@@ -7,6 +7,8 @@ import android.os.Looper
7
7
  import androidx.media3.common.HeartRating
8
8
  import androidx.media3.session.MediaSession
9
9
  import androidx.media3.session.SessionResult
10
+ import com.audiobrowser.model.PlayerUpdateOptions
11
+ import com.audiobrowser.util.TrackFactory
10
12
  import org.junit.After
11
13
  import org.junit.Assert.assertEquals
12
14
  import org.junit.Test
@@ -51,6 +53,7 @@ class LegacyRatingTest {
51
53
  @After
52
54
  fun destroy() {
53
55
  controller.destroy()
56
+ TrackFactory.favoriteEnabled = false
54
57
  }
55
58
 
56
59
  private fun idle() = shadowOf(Looper.getMainLooper()).idle()
@@ -69,6 +72,9 @@ class LegacyRatingTest {
69
72
 
70
73
  private fun loadTrack() {
71
74
  controller.bind()
75
+ player.applyOptions(
76
+ PlayerUpdateOptions().let { it.copy(capabilities = it.capabilities.copy(favorite = true)) }
77
+ )
72
78
  player.load(TestFixtures.track(id = "a", favorited = false))
73
79
  idle()
74
80
  }
@@ -0,0 +1,109 @@
1
+ package com.audiobrowser.player
2
+
3
+ import android.os.Looper
4
+ import androidx.media3.common.HeartRating
5
+ import androidx.media3.common.MediaItem
6
+ import androidx.media3.common.Player as MediaPlayer
7
+ import androidx.media3.common.Timeline
8
+ import androidx.media3.session.MediaSession
9
+ import com.audiobrowser.TestFixtures
10
+ import com.audiobrowser.model.PlayerSetupOptions
11
+ import com.audiobrowser.model.PlayerUpdateOptions
12
+ import com.audiobrowser.util.TrackFactory
13
+ import org.junit.After
14
+ import org.junit.Assert.assertEquals
15
+ import org.junit.Assert.assertFalse
16
+ import org.junit.Assert.assertNull
17
+ import org.junit.Assert.assertTrue
18
+ import org.junit.Before
19
+ import org.junit.Test
20
+ import org.junit.runner.RunWith
21
+ import org.robolectric.RobolectricTestRunner
22
+ import org.robolectric.RuntimeEnvironment
23
+ import org.robolectric.Shadows.shadowOf
24
+
25
+ @RunWith(RobolectricTestRunner::class)
26
+ class FavoriteCapabilityTest {
27
+
28
+ private val app = RuntimeEnvironment.getApplication()
29
+ private val player = Player(app)
30
+ private lateinit var session: MediaSession
31
+
32
+ @Before
33
+ fun setUp() {
34
+ player.setup(PlayerSetupOptions())
35
+ session = MediaSession.Builder(app, player.exoPlayer).build()
36
+ player.setMediaSession(session)
37
+ }
38
+
39
+ @After
40
+ fun release() {
41
+ session.release()
42
+ player.exoPlayer.release()
43
+ TrackFactory.favoriteEnabled = false
44
+ }
45
+
46
+ private fun favorite(enabled: Boolean) =
47
+ PlayerUpdateOptions().let { it.copy(capabilities = it.capabilities.copy(favorite = enabled)) }
48
+
49
+ private fun rating(index: Int) = player.exoPlayer.getMediaItemAt(index).mediaMetadata.userRating
50
+
51
+ private fun idle() = shadowOf(Looper.getMainLooper()).idle()
52
+
53
+ @Test
54
+ fun `turning favoriting on and off restamps each queued item's own heart rating`() {
55
+ player.add(
56
+ arrayOf(
57
+ TestFixtures.track(title = "a", src = "https://s/a.mp3"),
58
+ TestFixtures.track(title = "b", src = "https://s/b.mp3", favorited = true),
59
+ TestFixtures.track(title = "c", src = "https://s/c.mp3", favorited = false),
60
+ )
61
+ )
62
+ assertNull(rating(0))
63
+ assertNull(rating(1))
64
+
65
+ player.applyOptions(favorite(true))
66
+ assertFalse((rating(0) as HeartRating).isRated)
67
+ assertEquals(HeartRating(true), rating(1))
68
+ assertEquals(HeartRating(false), rating(2))
69
+
70
+ player.applyOptions(favorite(false))
71
+ assertNull(rating(0))
72
+ assertNull(rating(1))
73
+ assertNull(rating(2))
74
+ }
75
+
76
+ @Test
77
+ fun `the restamp is one timeline change, in place`() {
78
+ player.add(
79
+ arrayOf(
80
+ TestFixtures.track(title = "a", src = "https://s/a.mp3"),
81
+ TestFixtures.track(title = "b", src = "https://s/b.mp3"),
82
+ TestFixtures.track(title = "c", src = "https://s/c.mp3"),
83
+ )
84
+ )
85
+ player.exoPlayer.seekTo(1, 0)
86
+ idle()
87
+ var timelineChanges = 0
88
+ var transitions = 0
89
+ player.exoPlayer.addListener(
90
+ object : MediaPlayer.Listener {
91
+ override fun onTimelineChanged(timeline: Timeline, reason: Int) {
92
+ timelineChanges++
93
+ }
94
+
95
+ override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
96
+ transitions++
97
+ }
98
+ }
99
+ )
100
+
101
+ player.applyOptions(favorite(true))
102
+ idle()
103
+
104
+ assertEquals(1, timelineChanges)
105
+ assertEquals(0, transitions)
106
+ assertEquals(1, player.exoPlayer.currentMediaItemIndex)
107
+ assertTrue(rating(1) is HeartRating)
108
+ }
109
+ }
@@ -0,0 +1,151 @@
1
+ package com.audiobrowser.player
2
+
3
+ import androidx.media3.common.ForwardingPlayer
4
+ import androidx.media3.common.Player as MediaPlayer
5
+ import androidx.media3.exoplayer.ExoPlayer
6
+ import androidx.media3.session.CommandButton
7
+ import androidx.media3.session.MediaSession
8
+ import androidx.media3.session.SessionCommand
9
+ import com.margelo.nitro.audiobrowser.PlayerCapabilities
10
+ import com.margelo.nitro.audiobrowser.RemoteButton
11
+ import com.margelo.nitro.audiobrowser.RemoteButtonLayout
12
+ import org.junit.After
13
+ import org.junit.Assert.assertEquals
14
+ import org.junit.Assert.assertFalse
15
+ import org.junit.Assert.assertTrue
16
+ import org.junit.Test
17
+ import org.junit.runner.RunWith
18
+ import org.robolectric.RobolectricTestRunner
19
+ import org.robolectric.RuntimeEnvironment
20
+
21
+ /**
22
+ * Media3 turns a button in the back or forward slot into a custom action and drops the matching
23
+ * standard skip action from the platform PlaybackState; with the slot empty, the standard action
24
+ * stays. Robolectric's MediaController cannot read that state, so these check the buttons and the
25
+ * player commands behind the standard actions.
26
+ */
27
+ @RunWith(RobolectricTestRunner::class)
28
+ class StandardSkipTest {
29
+
30
+ private val app = RuntimeEnvironment.getApplication()
31
+ private val exoPlayer = ExoPlayer.Builder(app).build()
32
+ private val session =
33
+ MediaSession.Builder(
34
+ app,
35
+ object : ForwardingPlayer(exoPlayer) {
36
+ override fun getAvailableCommands() =
37
+ MediaPlayer.Commands.Builder().addAllCommands().build()
38
+
39
+ override fun isCommandAvailable(command: Int) = true
40
+ },
41
+ )
42
+ .build()
43
+ private val manager = MediaSessionCommandManager(automotive = false)
44
+
45
+ @After
46
+ fun release() {
47
+ session.release()
48
+ exoPlayer.release()
49
+ }
50
+
51
+ private fun capabilities(
52
+ skipToNext: Boolean? = null,
53
+ skipToPrevious: Boolean? = null,
54
+ jump: Boolean = false,
55
+ favorite: Boolean = true,
56
+ ) =
57
+ PlayerCapabilities(
58
+ play = null,
59
+ pause = null,
60
+ stop = null,
61
+ seekTo = null,
62
+ skipToNext = skipToNext,
63
+ skipToPrevious = skipToPrevious,
64
+ jumpForward = jump,
65
+ jumpBackward = jump,
66
+ favorite = favorite,
67
+ shuffleMode = null,
68
+ repeatMode = null,
69
+ playbackRate = null,
70
+ )
71
+
72
+ private fun buttons(
73
+ capabilities: PlayerCapabilities,
74
+ layout: RemoteButtonLayout? = null,
75
+ ): List<Pair<String, Int>> {
76
+ manager.updateMediaSession(session, capabilities, layout, searchAvailable = false)
77
+ return manager.buildConnectionResult(session).mediaButtonPreferences!!.map {
78
+ it.displayName.toString() to it.slots[0]
79
+ }
80
+ }
81
+
82
+ private fun commands(capabilities: PlayerCapabilities): MediaPlayer.Commands {
83
+ manager.updateMediaSession(session, capabilities, null, searchAvailable = false)
84
+ return manager.buildConnectionResult(session).availablePlayerCommands
85
+ }
86
+
87
+ @Test
88
+ fun `Previous and Next in their own slots are left to the standard skip actions`() {
89
+ assertEquals(listOf("Add to favorites" to CommandButton.SLOT_OVERFLOW), buttons(capabilities()))
90
+ }
91
+
92
+ @Test
93
+ fun `Android Automotive OS leaves the favorite to its own rating control`() {
94
+ val automotive = MediaSessionCommandManager(automotive = true)
95
+ automotive.updateMediaSession(session, capabilities(), null, searchAvailable = false)
96
+ assertEquals(
97
+ emptyList<CommandButton>(),
98
+ automotive.buildConnectionResult(session).mediaButtonPreferences,
99
+ )
100
+ }
101
+
102
+ @Test
103
+ fun `skip placed anywhere else stays a button, and jump keeps the primary slots`() {
104
+ val layout =
105
+ RemoteButtonLayout(
106
+ back = RemoteButton.JUMP_BACKWARD,
107
+ forward = RemoteButton.JUMP_FORWARD,
108
+ overflow = arrayOf(RemoteButton.SKIP_TO_NEXT),
109
+ )
110
+ assertEquals(
111
+ listOf(
112
+ "Jump Backward" to CommandButton.SLOT_BACK,
113
+ "Jump Forward" to CommandButton.SLOT_FORWARD,
114
+ "Next" to CommandButton.SLOT_OVERFLOW,
115
+ ),
116
+ buttons(capabilities(jump = true), layout),
117
+ )
118
+ }
119
+
120
+ @Test
121
+ fun `an enabled skip grants both of its commands`() {
122
+ val commands = commands(capabilities())
123
+ assertTrue(commands.contains(MediaPlayer.COMMAND_SEEK_TO_NEXT))
124
+ assertTrue(commands.contains(MediaPlayer.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM))
125
+ assertTrue(commands.contains(MediaPlayer.COMMAND_SEEK_TO_PREVIOUS))
126
+ assertTrue(commands.contains(MediaPlayer.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM))
127
+ }
128
+
129
+ @Test
130
+ fun `a disabled skip removes both of its commands, and only those`() {
131
+ val commands = commands(capabilities(skipToNext = false))
132
+ assertFalse(commands.contains(MediaPlayer.COMMAND_SEEK_TO_NEXT))
133
+ assertFalse(commands.contains(MediaPlayer.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM))
134
+ assertTrue(commands.contains(MediaPlayer.COMMAND_SEEK_TO_PREVIOUS))
135
+ assertTrue(commands.contains(MediaPlayer.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM))
136
+ }
137
+
138
+ private fun acceptsRatings(capabilities: PlayerCapabilities): Boolean {
139
+ manager.updateMediaSession(session, capabilities, null, searchAvailable = false)
140
+ return manager
141
+ .buildConnectionResult(session)
142
+ .availableSessionCommands
143
+ .contains(SessionCommand.COMMAND_CODE_SESSION_SET_RATING)
144
+ }
145
+
146
+ @Test
147
+ fun `a rating, which sets the favorite, is accepted only while favoriting is on`() {
148
+ assertTrue(acceptsRatings(capabilities(favorite = true)))
149
+ assertFalse(acceptsRatings(capabilities(favorite = false)))
150
+ }
151
+ }
@@ -6,14 +6,21 @@ import com.audiobrowser.TestFixtures
6
6
  import com.audiobrowser.browser.BrowseArtworkRegistry
7
7
  import org.junit.After
8
8
  import org.junit.Assert.assertEquals
9
+ import org.junit.Assert.assertFalse
9
10
  import org.junit.Assert.assertNull
10
11
  import org.junit.Assert.assertTrue
12
+ import org.junit.Before
11
13
  import org.junit.Test
12
14
  import org.junit.runner.RunWith
13
15
  import org.robolectric.RobolectricTestRunner
14
16
 
15
17
  @RunWith(RobolectricTestRunner::class)
16
18
  class TrackFactoryRatingTest {
19
+ @Before
20
+ fun favoritesOn() {
21
+ TrackFactory.favoriteEnabled = true
22
+ }
23
+
17
24
  @Test
18
25
  fun `favorited true advertises a rated, hearted userRating`() {
19
26
  val item = TrackFactory.toMedia3(TestFixtures.track(favorited = true))
@@ -31,8 +38,22 @@ class TrackFactoryRatingTest {
31
38
  }
32
39
 
33
40
  @Test
34
- fun `favorited null advertises no userRating (favoriting disabled)`() {
41
+ fun `favorited null advertises an unrated heart, so a car still draws its rating control`() {
35
42
  val item = TrackFactory.toMedia3(TestFixtures.track(favorited = null))
43
+ val rating = item.mediaMetadata.userRating as HeartRating
44
+ assertFalse(rating.isRated)
45
+ }
46
+
47
+ @Test
48
+ fun `a browsable item with no known favorite carries no rating`() {
49
+ val item = TrackFactory.toMedia3(TestFixtures.browseTrack())
50
+ assertNull(item.mediaMetadata.userRating)
51
+ }
52
+
53
+ @Test
54
+ fun `favoriting off advertises no userRating`() {
55
+ TrackFactory.favoriteEnabled = false
56
+ val item = TrackFactory.toMedia3(TestFixtures.track(favorited = true))
36
57
  assertNull(item.mediaMetadata.userRating)
37
58
  }
38
59
 
@@ -40,6 +61,7 @@ class TrackFactoryRatingTest {
40
61
  fun resetDevice() {
41
62
  Automotive.device = false
42
63
  TrackFactory.artworkRoutes = null
64
+ TrackFactory.favoriteEnabled = false
43
65
  }
44
66
 
45
67
  private fun automotive(): BrowseArtworkRegistry =
@@ -48,13 +70,6 @@ class TrackFactoryRatingTest {
48
70
  TrackFactory.artworkRoutes = ArtworkRoutes(it, "app.artwork")
49
71
  }
50
72
 
51
- @Test
52
- fun `Android Automotive OS advertises no userRating`() {
53
- automotive()
54
- val item = TrackFactory.toMedia3(TestFixtures.track(favorited = true))
55
- assertNull(item.mediaMetadata.userRating)
56
- }
57
-
58
73
  @Test
59
74
  fun `Android Automotive OS serves http artwork through the provider`() {
60
75
  val registry = automotive()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-audio-browser",
3
- "version": "0.2.0-next.48",
3
+ "version": "0.2.0-next.49",
4
4
  "description": "react-native-audio-browser is a react native package built with Nitro",
5
5
  "keywords": [
6
6
  "react-native",
@@ -1,93 +0,0 @@
1
- package com.audiobrowser.player
2
-
3
- import androidx.media3.common.ForwardingPlayer
4
- import androidx.media3.common.Player as MediaPlayer
5
- import androidx.media3.exoplayer.ExoPlayer
6
- import androidx.media3.session.CommandButton
7
- import androidx.media3.session.MediaSession
8
- import com.margelo.nitro.audiobrowser.PlayerCapabilities
9
- import org.junit.After
10
- import org.junit.Assert.assertEquals
11
- import org.junit.Test
12
- import org.junit.runner.RunWith
13
- import org.robolectric.RobolectricTestRunner
14
- import org.robolectric.RuntimeEnvironment
15
-
16
- /**
17
- * Media3 turns a button in the back or forward slot into a custom action and drops the matching
18
- * standard skip action from the platform PlaybackState; with the slot empty, the standard action
19
- * stays. Robolectric's MediaController cannot read that state, so these check the buttons.
20
- */
21
- @RunWith(RobolectricTestRunner::class)
22
- class AutomotiveSkipTest {
23
-
24
- private val app = RuntimeEnvironment.getApplication()
25
- private val exoPlayer = ExoPlayer.Builder(app).build()
26
- private val session =
27
- MediaSession.Builder(
28
- app,
29
- object : ForwardingPlayer(exoPlayer) {
30
- override fun getAvailableCommands() =
31
- MediaPlayer.Commands.Builder().addAllCommands().build()
32
-
33
- override fun isCommandAvailable(command: Int) = true
34
- },
35
- )
36
- .build()
37
-
38
- @After
39
- fun release() {
40
- session.release()
41
- exoPlayer.release()
42
- }
43
-
44
- private fun capabilities(favorite: Boolean? = null) =
45
- PlayerCapabilities(
46
- play = null,
47
- pause = null,
48
- stop = null,
49
- seekTo = null,
50
- skipToNext = null,
51
- skipToPrevious = null,
52
- jumpForward = false,
53
- jumpBackward = false,
54
- favorite = favorite,
55
- shuffleMode = null,
56
- repeatMode = null,
57
- playbackRate = null,
58
- )
59
-
60
- private fun buttonsFor(automotive: Boolean): List<Pair<String, Int>> =
61
- MediaSessionCommandManager(automotive)
62
- .apply {
63
- updateMediaSession(
64
- session,
65
- capabilities(favorite = true),
66
- remoteButtonLayout = null,
67
- searchAvailable = false,
68
- )
69
- }
70
- .buildConnectionResult(session)
71
- .mediaButtonPreferences!!
72
- .map { it.displayName.toString() to it.slots[0] }
73
-
74
- @Test
75
- fun `a phone places Previous and Next in the back and forward slots`() {
76
- assertEquals(
77
- listOf(
78
- "Previous" to CommandButton.SLOT_BACK,
79
- "Next" to CommandButton.SLOT_FORWARD,
80
- "Add to favorites" to CommandButton.SLOT_OVERFLOW,
81
- ),
82
- buttonsFor(automotive = false),
83
- )
84
- }
85
-
86
- @Test
87
- fun `Android Automotive OS leaves Previous and Next to the standard skip actions`() {
88
- assertEquals(
89
- listOf("Add to favorites" to CommandButton.SLOT_OVERFLOW),
90
- buttonsFor(automotive = true),
91
- )
92
- }
93
- }