react-native-audio-browser 0.2.0-next.44 → 0.2.0-next.46

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.
@@ -6,7 +6,6 @@ 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.HeartRating
10
9
  import androidx.media3.common.MediaMetadata
11
10
  import androidx.media3.database.StandaloneDatabaseProvider
12
11
  import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor
@@ -23,11 +22,17 @@ import com.audiobrowser.extension.NumberExt.Companion.toSeconds
23
22
  import com.audiobrowser.extension.identity
24
23
  import com.audiobrowser.model.PlayerSetupOptions
25
24
  import com.audiobrowser.model.PlayerUpdateOptions
25
+ import com.audiobrowser.util.ArtworkRoutes
26
+ import com.audiobrowser.util.ArtworkUris
27
+ import com.audiobrowser.util.Automotive
26
28
  import com.audiobrowser.util.CoilBitmapLoader
27
29
  import com.audiobrowser.util.NetworkConnectivityMonitor
28
30
  import com.audiobrowser.util.PlayingStateFactory
29
31
  import com.audiobrowser.util.RepeatModeFactory
32
+ import com.audiobrowser.util.SvgArtworkRenderer
30
33
  import com.audiobrowser.util.TrackFactory
34
+ import com.audiobrowser.util.TrackFactory.setFavorite
35
+ import com.audiobrowser.util.isAutomotive
31
36
  import com.margelo.nitro.audiobrowser.AppKilledPlaybackBehavior
32
37
  import com.margelo.nitro.audiobrowser.FavoriteChangedEvent
33
38
  import com.margelo.nitro.audiobrowser.GateEvent
@@ -133,6 +138,12 @@ class Player(internal val context: Context) {
133
138
  /** Registry that maps content:// tokens to artwork URLs for the browse content provider. */
134
139
  val browseArtworkRegistry = com.audiobrowser.browser.BrowseArtworkRegistry()
135
140
 
141
+ init {
142
+ Automotive.device = context.isAutomotive
143
+ TrackFactory.artworkRoutes =
144
+ ArtworkRoutes(browseArtworkRegistry, ArtworkUris.authorityFor(context.packageName))
145
+ }
146
+
136
147
  /**
137
148
  * Set the CoilBitmapLoader for display-time bitmap loading. Called from Service after creation.
138
149
  */
@@ -704,7 +715,10 @@ class Player(internal val context: Context) {
704
715
  */
705
716
  fun replaceTrack(index: Int, track: Track) {
706
717
  validateIndex(index)
718
+ val isCurrent = index == currentIndex
719
+ if (isCurrent) nowPlaying.forgetPublished()
707
720
  exoPlayer.replaceMediaItem(index, TrackFactory.toMedia3(track))
721
+ if (isCurrent) nowPlaying.render()
708
722
  }
709
723
 
710
724
  /**
@@ -739,8 +753,7 @@ class Player(internal val context: Context) {
739
753
  // This preserves internal references and avoids playback interruption
740
754
  // Note: setTag() requires setUri() to be called, so we must re-set the URI
741
755
  val currentMediaItem = exoPlayer.getMediaItemAt(index)
742
- val updatedMetadata =
743
- currentMediaItem.mediaMetadata.buildUpon().setUserRating(HeartRating(favorited)).build()
756
+ val updatedMetadata = currentMediaItem.mediaMetadata.buildUpon().setFavorite(favorited).build()
744
757
  val updatedMediaItem =
745
758
  currentMediaItem
746
759
  .buildUpon()
@@ -839,11 +852,13 @@ class Player(internal val context: Context) {
839
852
  null
840
853
  }
841
854
  val uri = resolved?.uri?.takeIf { it.isNotEmpty() } ?: return null
855
+ val published =
856
+ TrackFactory.sessionArtworkUri(uri, resolved.headers, SvgArtworkRenderer.isSvgUrl(uri))
842
857
  // Remember how this URI was produced: Media3 hands it back to the bitmap loader, which
843
858
  // re-resolves Track-first (with the nowPlayingArtwork kind, not the global artwork
844
859
  // config).
845
- browserManager.artworkResolutions.register(uri, track, config)
846
- return uri
860
+ browserManager.artworkResolutions.register(published, track, config)
861
+ return published
847
862
  }
848
863
 
849
864
  override fun emitNowPlayingChanged(metadata: NowPlayingMetadata) {
@@ -917,6 +932,14 @@ class Player(internal val context: Context) {
917
932
  browserManager.displayArtworkSource(uri, imageContext)?.let {
918
933
  return it
919
934
  }
935
+ // On Android Automotive OS the queue publishes provider URIs; the resolutions are keyed by URL.
936
+ TrackFactory.artworkRoutes
937
+ ?.publicUrl(uri.toUri())
938
+ ?.takeIf { it != uri }
939
+ ?.let { browserManager.displayArtworkSource(it, imageContext) }
940
+ ?.let {
941
+ return it
942
+ }
920
943
  withContext(Dispatchers.Main) { findQueueTrackByArtworkUri(uri) }
921
944
  ?.let { track ->
922
945
  return browserManager.resolveArtworkUrl(track, null, imageContext)
@@ -0,0 +1,39 @@
1
+ package com.audiobrowser.util
2
+
3
+ import android.net.Uri
4
+ import com.audiobrowser.browser.BrowseArtworkRegistry
5
+ import com.audiobrowser.browser.ResolvedArtwork
6
+
7
+ /** Routes artwork URLs through the [ArtworkContentProvider]: its registry and authority. */
8
+ class ArtworkRoutes(val registry: BrowseArtworkRegistry, val authority: String) {
9
+ /**
10
+ * The `content://` URI that serves http(s) [url], registered with the provider; any other URI as
11
+ * it is. A [pinned] registration survives the registry's clear, as does a pinned URI of this
12
+ * provider's own.
13
+ */
14
+ fun route(url: String, headers: Map<String, String>?, isSvg: Boolean, pinned: Boolean): String {
15
+ val uri = Uri.parse(url)
16
+ val scheme = uri.scheme?.lowercase()
17
+ if (scheme != "http" && scheme != "https") {
18
+ if (pinned && uri.authority == authority) {
19
+ ArtworkUris.parseToken(uri)?.let { token ->
20
+ registry.lookup(token)?.let { registry.pin(token, it) }
21
+ }
22
+ }
23
+ return url
24
+ }
25
+ val token = ArtworkUris.tokenFor(url)
26
+ val artwork = ResolvedArtwork(url, headers, isSvg)
27
+ if (pinned) registry.pin(token, artwork) else registry.register(token, artwork)
28
+ return ArtworkUris.contentUri(authority, token)
29
+ }
30
+
31
+ /**
32
+ * The URL a URI shows to JS: for one of this provider's URIs the URL it serves, or null once the
33
+ * registry has forgotten it; any other URI as it is.
34
+ */
35
+ fun publicUrl(uri: Uri): String? {
36
+ if (uri.authority != authority) return uri.toString()
37
+ return ArtworkUris.parseToken(uri)?.let { registry.lookup(it)?.finalUrl }
38
+ }
39
+ }
@@ -0,0 +1,15 @@
1
+ package com.audiobrowser.util
2
+
3
+ import android.content.Context
4
+ import android.content.pm.PackageManager
5
+
6
+ /**
7
+ * Whether this is an Android Automotive OS device, as opposed to a phone projecting Android Auto.
8
+ */
9
+ val Context.isAutomotive: Boolean
10
+ get() = packageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)
11
+
12
+ /** Whether the process runs on Android Automotive OS: false until the Player sets it. */
13
+ object Automotive {
14
+ @Volatile var device = false
15
+ }
@@ -61,8 +61,7 @@ object BrowserPathHelper {
61
61
  }
62
62
 
63
63
  /**
64
- * The tile sentinels a drill-in dead-ends on: Android Auto ignores the tiles' non-browsable flag
65
- * and subscribes anyway, so these serve no children rather than stacking another page.
64
+ * The tile sentinels a drill-in dead-ends on (see `deadEndChildren` for what they serve).
66
65
  * [GATE_PATH] is not one of them — it re-serves the gate tile so the message stays readable.
67
66
  */
68
67
  fun isDeadEndPath(path: String): Boolean {
@@ -81,7 +81,11 @@ sealed class MetadataAdapter {
81
81
  albumTitle = metadata.albumTitle as String?,
82
82
  subtitle = metadata.subtitle as String?,
83
83
  description = metadata.description as String?,
84
- artworkUri = metadata.artworkUri?.toString(),
84
+ artworkUri =
85
+ metadata.artworkUri?.let { uri ->
86
+ val routes = TrackFactory.artworkRoutes
87
+ if (routes == null) uri.toString() else routes.publicUrl(uri)
88
+ },
85
89
  trackNumber = metadata.trackNumber?.toString(),
86
90
  composer = metadata.composer as String?,
87
91
  conductor = metadata.conductor as String?,
@@ -1,12 +1,10 @@
1
1
  package com.audiobrowser.util
2
2
 
3
- import android.net.Uri
4
3
  import androidx.core.net.toUri
5
4
  import androidx.media3.common.HeartRating
6
5
  import androidx.media3.common.MediaItem
7
6
  import androidx.media3.common.MediaMetadata
8
7
  import com.audiobrowser.browser.BrowseArtworkRegistry
9
- import com.audiobrowser.browser.ResolvedArtwork
10
8
  import com.margelo.nitro.audiobrowser.Section
11
9
  import com.margelo.nitro.audiobrowser.Track
12
10
  import com.margelo.nitro.audiobrowser.TrackStyle
@@ -20,6 +18,28 @@ import com.margelo.nitro.audiobrowser.TrackStyle
20
18
  * pipeline; see the Now Playing Metadata guide).
21
19
  */
22
20
  object TrackFactory {
21
+ /** Set once by the Player. */
22
+ @Volatile var artworkRoutes: ArtworkRoutes? = null
23
+
24
+ /**
25
+ * The artwork URI the session publishes for [url]. On Android Automotive OS, whose car media app
26
+ * loads artwork only from `content://`, `android.resource://` and `file://` URIs, http(s) artwork
27
+ * is served through the provider, as browse artwork always is.
28
+ */
29
+ fun sessionArtworkUri(url: String, headers: Map<String, String>?, isSvg: Boolean): String {
30
+ val provider = artworkRoutes?.takeIf { Automotive.device } ?: return url
31
+ return provider.route(url, headers, isSvg, pinned = true)
32
+ }
33
+
34
+ /**
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
+ */
39
+ fun MediaMetadata.Builder.setFavorite(favorited: Boolean?): MediaMetadata.Builder = apply {
40
+ if (!Automotive.device && favorited != null) setUserRating(HeartRating(favorited))
41
+ }
42
+
23
43
  fun fromMedia3(mediaItem: MediaItem): Track {
24
44
  return mediaItem.localConfiguration!!.tag as Track
25
45
  }
@@ -72,7 +92,9 @@ object TrackFactory {
72
92
  }
73
93
 
74
94
  fun toMedia3(track: Track): MediaItem {
75
- val metadata = metadataBuilder(track).setArtworkUri(artworkUri(track)?.toUri()).build()
95
+ val artwork =
96
+ artworkUri(track)?.let { sessionArtworkUri(it, track.artworkSource?.headers, isSvg(track)) }
97
+ val metadata = metadataBuilder(track).setArtworkUri(artwork?.toUri()).build()
76
98
  return buildMediaItem(track, metadata)
77
99
  }
78
100
 
@@ -80,7 +102,7 @@ object TrackFactory {
80
102
  * Browse-surface conversion. Routes http(s) artwork through the content:// provider (so headers +
81
103
  * SVG apply in our process, and no bytes cross the Binder), registering it in [registry].
82
104
  * Non-http artwork (android.resource:// tab icons, file://) passes through to setArtworkUri
83
- * unchanged so vector/category icons survive. Plain toMedia3 (queue/now-playing) is unaffected.
105
+ * unchanged so vector/category icons survive.
84
106
  */
85
107
  fun toBrowseMediaItem(
86
108
  track: Track,
@@ -88,21 +110,19 @@ object TrackFactory {
88
110
  authority: String,
89
111
  section: Section? = null,
90
112
  ): MediaItem {
91
- val rawUrl = artworkUri(track) // artworkSource.uri ?: artwork
92
- val scheme = rawUrl?.let { Uri.parse(it).scheme?.lowercase() }
93
- val builder = metadataBuilder(track, section)
94
- if (rawUrl != null && (scheme == "http" || scheme == "https")) {
95
- val isSvg =
96
- SvgArtworkRenderer.isSvgUrl(rawUrl) || SvgArtworkRenderer.isSvgUrl(track.artwork?.url)
97
- val token = ArtworkUris.tokenFor(rawUrl)
98
- registry.register(token, ResolvedArtwork(rawUrl, track.artworkSource?.headers, isSvg))
99
- builder.setArtworkUri(ArtworkUris.contentUri(authority, token).toUri())
100
- } else if (rawUrl != null) {
101
- builder.setArtworkUri(rawUrl.toUri())
102
- }
103
- return buildMediaItem(track, builder.build())
113
+ val artwork =
114
+ artworkUri(track)?.let {
115
+ ArtworkRoutes(registry, authority)
116
+ .route(it, track.artworkSource?.headers, isSvg(track), pinned = false)
117
+ }
118
+ val metadata = metadataBuilder(track, section).setArtworkUri(artwork?.toUri()).build()
119
+ return buildMediaItem(track, metadata)
104
120
  }
105
121
 
122
+ private fun isSvg(track: Track): Boolean =
123
+ SvgArtworkRenderer.isSvgUrl(artworkUri(track)) ||
124
+ SvgArtworkRenderer.isSvgUrl(track.artwork?.url)
125
+
106
126
  /** The transformed artworkSource wins over the raw artwork field. */
107
127
  private fun artworkUri(track: Track): String? = track.artworkSource?.uri ?: track.artwork?.url
108
128
 
@@ -120,7 +140,7 @@ object TrackFactory {
120
140
  .setIsBrowsable(track.src == null)
121
141
  .setIsPlayable(track.src != null)
122
142
  .setExtras(MediaExtrasBuilder.build(track, section))
123
- .apply { track.favorited?.let { setUserRating(HeartRating(it)) } }
143
+ .setFavorite(track.favorited)
124
144
 
125
145
  private fun buildMediaItem(track: Track, metadata: MediaMetadata): MediaItem {
126
146
  // A playable track's mediaId is the consumer's stable `id` when it has one —
@@ -0,0 +1,93 @@
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
+ }
@@ -12,6 +12,7 @@ import com.audiobrowser.browser.NetworkException
12
12
  import com.audiobrowser.defaultFormattedError
13
13
  import com.audiobrowser.formattedOrDefault
14
14
  import com.audiobrowser.navigationErrorFor
15
+ import com.audiobrowser.util.Automotive
15
16
  import com.audiobrowser.util.BrowserPathHelper
16
17
  import com.margelo.nitro.audiobrowser.FormattedNavigationError
17
18
  import com.margelo.nitro.audiobrowser.NavigationError
@@ -20,6 +21,7 @@ import kotlin.coroutines.Continuation
20
21
  import kotlin.coroutines.resume
21
22
  import kotlin.coroutines.suspendCoroutine
22
23
  import kotlinx.coroutines.test.runTest
24
+ import org.junit.After
23
25
  import org.junit.Assert.assertEquals
24
26
  import org.junit.Assert.assertFalse
25
27
  import org.junit.Assert.assertNotEquals
@@ -85,6 +87,96 @@ class BrowseTilesTest {
85
87
  }
86
88
  }
87
89
 
90
+ @After
91
+ fun resetDevice() {
92
+ Automotive.device = false
93
+ }
94
+
95
+ private val offlineTile = createOfflineMediaItem(FormattedNavigationError("Offline", "Message"))
96
+
97
+ @Test
98
+ fun `a phone's drill into a tile dead-ends`() {
99
+ assertTrue(
100
+ deadEndChildren(
101
+ BrowserPathHelper.OFFLINE_PATH,
102
+ offlineTile,
103
+ automotive = false,
104
+ offline = true,
105
+ )
106
+ .isEmpty()
107
+ )
108
+ }
109
+
110
+ @Test
111
+ fun `Android Automotive OS serves the root's tile again on its own path`() {
112
+ assertEquals(
113
+ listOf(offlineTile),
114
+ deadEndChildren(
115
+ BrowserPathHelper.OFFLINE_PATH,
116
+ offlineTile,
117
+ automotive = true,
118
+ offline = true,
119
+ ),
120
+ )
121
+ }
122
+
123
+ @Test
124
+ fun `Android Automotive OS serves no tile for another sentinel, or offline once back online`() {
125
+ assertTrue(
126
+ deadEndChildren(BrowserPathHelper.ERROR_PATH, offlineTile, automotive = true, offline = true)
127
+ .isEmpty()
128
+ )
129
+ assertTrue(
130
+ deadEndChildren(
131
+ BrowserPathHelper.OFFLINE_PATH,
132
+ offlineTile,
133
+ automotive = true,
134
+ offline = false,
135
+ )
136
+ .isEmpty()
137
+ )
138
+ }
139
+
140
+ @Test
141
+ fun `Android Automotive OS serves an error tile again while online`() {
142
+ val errorTile = createBrowseErrorMediaItem(FormattedNavigationError("Failed", "Message"))
143
+ assertEquals(
144
+ listOf(errorTile),
145
+ deadEndChildren(BrowserPathHelper.ERROR_PATH, errorTile, automotive = true, offline = false),
146
+ )
147
+ }
148
+
149
+ @Test
150
+ fun `a level serving only a dead-end tile yields that tile`() {
151
+ val tile = createOfflineMediaItem(FormattedNavigationError("Offline", "Message"))
152
+ assertSame(tile, deadEndTileOf(listOf(tile)))
153
+ }
154
+
155
+ @Test
156
+ fun `a level of items, or the gate tile, yields no dead-end tile`() {
157
+ val tile = createOfflineMediaItem(FormattedNavigationError("Offline", "Message"))
158
+ val gate = createErrorMediaItem(BrowserPathHelper.GATE_PATH, "Title", "Message")
159
+ assertNull(deadEndTileOf(listOf(tile, tile)))
160
+ assertNull(deadEndTileOf(listOf(gate)))
161
+ assertNull(deadEndTileOf(emptyList()))
162
+ }
163
+
164
+ @Test
165
+ fun `on Android Automotive OS every tile is browsable, so its car media app shows it`() {
166
+ Automotive.device = true
167
+ val copy = FormattedNavigationError("Title", "Message")
168
+ for (tile in
169
+ listOf(
170
+ createEmptyMediaItem(copy),
171
+ createOfflineMediaItem(copy),
172
+ createBrowseErrorMediaItem(copy),
173
+ createErrorMediaItem(BrowserPathHelper.GATE_PATH, "Title", "Message"),
174
+ )) {
175
+ assertTrue(tile.mediaId, tile.mediaMetadata.isBrowsable!!)
176
+ assertFalse(tile.mediaId, tile.mediaMetadata.isPlayable!!)
177
+ }
178
+ }
179
+
88
180
  @Test
89
181
  fun `an empty favorites page serves one tile carrying the app's copy for that path`() = runTest {
90
182
  val items = browseLevelItems(emptyList()) { appCopy(emptyContentError(), "/favorites") }
@@ -36,7 +36,7 @@ class LiveSeekCommandTest {
36
36
  },
37
37
  )
38
38
  .build()
39
- private val manager = MediaSessionCommandManager()
39
+ private val manager = MediaSessionCommandManager(automotive = false)
40
40
 
41
41
  @After
42
42
  fun release() {
@@ -87,6 +87,8 @@ class NowPlayingUpdaterTest {
87
87
 
88
88
  assertEquals(listOf(FakeSurface.Stamp(0, "Station", "Station", "Place", null)), surface.stamps)
89
89
  assertEquals(1, surface.emitted.size)
90
+ assertEquals("Place", surface.emitted.last().artist)
91
+ assertEquals(surface.emitted.last(), updater.getNowPlaying())
90
92
  }
91
93
 
92
94
  @Test
@@ -122,6 +124,16 @@ class NowPlayingUpdaterTest {
122
124
  assertEquals("Station", surface.stamps.last().title)
123
125
  }
124
126
 
127
+ @Test
128
+ fun `disabled updater still reports the override to JS`() = runTest {
129
+ val surface = FakeSurface().apply { currentTrack = track("Station") }
130
+ val updater = NowPlayingUpdater(surface, backgroundScope).apply { enabled = false }
131
+ updater.updateNowPlaying(update(title = "Song"))
132
+
133
+ assertEquals("Song", surface.emitted.last().title)
134
+ assertEquals("Song", updater.getNowPlaying()?.title)
135
+ }
136
+
125
137
  // MARK: dedupe
126
138
 
127
139
  @Test
@@ -192,6 +204,164 @@ class NowPlayingUpdaterTest {
192
204
  assertEquals("Place", surface.stamps.last().secondary) // per-field fallback
193
205
  }
194
206
 
207
+ @Test
208
+ fun `the formatter's lines reach the event and getNowPlaying`() = runTest {
209
+ val surface =
210
+ FakeSurface().apply {
211
+ currentTrack =
212
+ track("Station", artist = "Place", album = "Country", artwork = "https://s/a.png")
213
+ }
214
+ val updater = NowPlayingUpdater(surface, backgroundScope)
215
+ updater.formatter = { update(artist = "Song - Artist") }
216
+
217
+ updater.render()
218
+ runCurrent()
219
+
220
+ val emitted = surface.emitted.last()
221
+ assertEquals("Station", emitted.title)
222
+ assertEquals("Song - Artist", emitted.artist)
223
+ assertEquals("Country", emitted.album)
224
+ assertEquals(emitted, updater.getNowPlaying())
225
+ assertNull(emitted.elapsedTime)
226
+ assertEquals("https://s/a.png", emitted.artwork)
227
+ assertEquals("https://s/a.mp3", emitted.mediaId)
228
+ }
229
+
230
+ @Test
231
+ fun `a re-render keeps the formatter's line up while the formatter runs`() = runTest {
232
+ val surface = FakeSurface().apply { currentTrack = track("Station", artist = "Place") }
233
+ val updater = NowPlayingUpdater(surface, backgroundScope)
234
+ val gate = CompletableDeferred<Unit>()
235
+ var calls = 0
236
+ updater.formatter = {
237
+ if (++calls > 1) gate.await()
238
+ update(artist = "Song - Artist")
239
+ }
240
+ updater.render()
241
+ runCurrent()
242
+
243
+ updater.render()
244
+ runCurrent()
245
+ assertEquals("Song - Artist", updater.getNowPlaying()?.artist)
246
+ gate.complete(Unit)
247
+ runCurrent()
248
+
249
+ assertEquals(listOf("Place", "Song - Artist"), surface.emitted.map { it.artist })
250
+ assertEquals(listOf("Place", "Song - Artist"), surface.stamps.map { it.secondary })
251
+ }
252
+
253
+ @Test
254
+ fun `a formatter that stops customizing restores the default`() = runTest {
255
+ val surface = FakeSurface().apply { currentTrack = track("Station", artist = "Place") }
256
+ val updater = NowPlayingUpdater(surface, backgroundScope)
257
+ var line: String? = "Song - Artist"
258
+ updater.formatter = { update(artist = line) }
259
+ updater.render()
260
+ runCurrent()
261
+
262
+ line = null
263
+ updater.render()
264
+ runCurrent()
265
+
266
+ assertEquals("Place", surface.stamps.last().secondary)
267
+ assertEquals("Place", surface.emitted.last().artist)
268
+ assertEquals("Place", updater.getNowPlaying()?.artist)
269
+ }
270
+
271
+ @Test
272
+ fun `a throwing formatter after a result restores the default`() = runTest {
273
+ val surface = FakeSurface().apply { currentTrack = track("Station", artist = "Place") }
274
+ val updater = NowPlayingUpdater(surface, backgroundScope)
275
+ var fail = false
276
+ updater.formatter = { if (fail) error("boom") else update(artist = "Song - Artist") }
277
+ updater.render()
278
+ runCurrent()
279
+
280
+ fail = true
281
+ updater.render()
282
+ runCurrent()
283
+
284
+ assertEquals("Place", surface.stamps.last().secondary)
285
+ assertEquals("Place", updater.getNowPlaying()?.artist)
286
+ }
287
+
288
+ @Test
289
+ fun `getNowPlaying keeps the formatter's line when the playing item moves in the queue`() =
290
+ runTest {
291
+ val surface = FakeSurface().apply { currentTrack = track("Station", artist = "Place") }
292
+ val updater = NowPlayingUpdater(surface, backgroundScope)
293
+ updater.formatter = { update(artist = "Song - Artist") }
294
+ updater.render()
295
+ runCurrent()
296
+
297
+ surface.currentIndex = 1
298
+
299
+ assertEquals("Song - Artist", updater.getNowPlaying()?.artist)
300
+ }
301
+
302
+ @Test
303
+ fun `a track replaced in place is stamped even with unchanged lines`() = runTest {
304
+ val surface = FakeSurface().apply { currentTrack = track("Station") }
305
+ val updater = NowPlayingUpdater(surface, backgroundScope)
306
+ updater.render()
307
+
308
+ updater.forgetPublished()
309
+ surface.currentTrack = track("Station")
310
+ updater.render()
311
+
312
+ assertEquals(listOf("Station", "Station"), surface.stamps.map { it.title })
313
+ }
314
+
315
+ @Test
316
+ fun `a new item of the same track gets the formatter's line stamped again`() = runTest {
317
+ val surface = FakeSurface().apply { currentTrack = track("Station", artist = "Place") }
318
+ val updater = NowPlayingUpdater(surface, backgroundScope)
319
+ updater.formatter = { update(artist = "Song - Artist") }
320
+ updater.render()
321
+ runCurrent()
322
+
323
+ surface.currentTrack = track("Station", artist = "Place")
324
+ updater.clearOverride()
325
+ updater.render()
326
+ runCurrent()
327
+
328
+ assertEquals(
329
+ listOf("Place", "Song - Artist", "Place", "Song - Artist"),
330
+ surface.stamps.map { it.secondary },
331
+ )
332
+ assertEquals("Song - Artist", updater.getNowPlaying()?.artist)
333
+ }
334
+
335
+ @Test
336
+ fun `a copy of the playing track keeps the formatter's line`() = runTest {
337
+ val surface = FakeSurface().apply { currentTrack = track("Station", artist = "Place") }
338
+ val updater = NowPlayingUpdater(surface, backgroundScope)
339
+ updater.formatter = { update(artist = "Song - Artist") }
340
+ updater.render()
341
+ runCurrent()
342
+
343
+ surface.currentTrack = surface.currentTrack?.copy(favorited = true)
344
+ assertEquals("Song - Artist", updater.getNowPlaying()?.artist)
345
+ updater.render()
346
+ runCurrent()
347
+
348
+ assertEquals(listOf("Place", "Song - Artist"), surface.emitted.map { it.artist })
349
+ }
350
+
351
+ @Test
352
+ fun `getNowPlaying shows a new track before it renders`() = runTest {
353
+ val surface = FakeSurface().apply { currentTrack = track("A", src = "https://s/a.mp3") }
354
+ val updater = NowPlayingUpdater(surface, backgroundScope)
355
+ updater.formatter = { update(artist = "Song on A") }
356
+ updater.render()
357
+ runCurrent()
358
+
359
+ surface.currentTrack = track("B", src = "https://s/b.mp3", artist = "Place B")
360
+
361
+ assertEquals("B", updater.getNowPlaying()?.title)
362
+ assertEquals("Place B", updater.getNowPlaying()?.artist)
363
+ }
364
+
195
365
  @Test
196
366
  fun `formatter params carry surface state`() = runTest {
197
367
  var seen: FormatNowPlayingParams? = null