react-native-audio-browser 0.2.0-next.45 → 0.2.0-next.47

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.
@@ -4,26 +4,39 @@ package com.audiobrowser.browser
4
4
  * Token → resolved browse artwork, the [com.audiobrowser.util.ArtworkContentProvider]'s only data
5
5
  * source. Stores plain resolved data (no Track / Nitro handles), so unlike
6
6
  * [ArtworkResolutionRegistry] it pins no JS closures and can be sized generously. Cleared when the
7
- * browser config is replaced or content is invalidated. Thread-safe: written from browse
8
- * coroutines, read from the provider's IO scope.
7
+ * browser config is replaced or content is invalidated, except for the [pin]ned entries: browse
8
+ * items are rebuilt after a clear, but the media items already in the queue keep their URIs.
9
+ * Thread-safe: written from browse coroutines, read from the provider's IO scope.
9
10
  */
10
- class BrowseArtworkRegistry(private val maxEntries: Int = 2048) {
11
+ class BrowseArtworkRegistry(
12
+ private val maxEntries: Int = 2048,
13
+ private val maxPinnedEntries: Int = 2048,
14
+ ) {
11
15
 
12
- private val entries =
13
- object : LinkedHashMap<String, ResolvedArtwork>(16, 0.75f, true) {
14
- override fun removeEldestEntry(
15
- eldest: MutableMap.MutableEntry<String, ResolvedArtwork>
16
- ): Boolean = size > maxEntries
17
- }
16
+ private val entries = lruMap(maxEntries)
17
+ private val pinned = lruMap(maxPinnedEntries)
18
18
 
19
19
  @Synchronized
20
20
  fun register(token: String, artwork: ResolvedArtwork) {
21
21
  entries[token] = artwork
22
22
  }
23
23
 
24
- @Synchronized fun lookup(token: String): ResolvedArtwork? = entries[token]
24
+ /** Registers artwork that a [clear] keeps. */
25
+ @Synchronized
26
+ fun pin(token: String, artwork: ResolvedArtwork) {
27
+ pinned[token] = artwork
28
+ }
29
+
30
+ @Synchronized fun lookup(token: String): ResolvedArtwork? = entries[token] ?: pinned[token]
25
31
 
26
32
  @Synchronized fun clear() = entries.clear()
33
+
34
+ private fun lruMap(maxEntries: Int) =
35
+ object : LinkedHashMap<String, ResolvedArtwork>(16, 0.75f, true) {
36
+ override fun removeEldestEntry(
37
+ eldest: MutableMap.MutableEntry<String, ResolvedArtwork>
38
+ ): Boolean = size > maxEntries
39
+ }
27
40
  }
28
41
 
29
42
  /** Everything the provider needs to fetch one artwork, resolved at browse-build time. */
@@ -20,9 +20,11 @@ import com.audiobrowser.browser.untitledSection
20
20
  import com.audiobrowser.extension.indexOfTappedTrack
21
21
  import com.audiobrowser.extension.toTrack
22
22
  import com.audiobrowser.navigationErrorFor
23
+ import com.audiobrowser.util.Automotive
23
24
  import com.audiobrowser.util.BrowserPathHelper
24
25
  import com.audiobrowser.util.RatingFavorites
25
26
  import com.audiobrowser.util.TrackFactory
27
+ import com.audiobrowser.util.isAutomotive
26
28
  import com.google.common.collect.ImmutableList
27
29
  import com.google.common.util.concurrent.FutureCallback
28
30
  import com.google.common.util.concurrent.Futures
@@ -61,7 +63,7 @@ import timber.log.Timber
61
63
  */
62
64
  class MediaSessionCallback(private val player: Player) :
63
65
  MediaLibraryService.MediaLibrarySession.Callback {
64
- internal val commandManager = MediaSessionCommandManager()
66
+ internal val commandManager = MediaSessionCommandManager(player.context.isAutomotive)
65
67
  private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
66
68
 
67
69
  // Track which controllers are subscribed to which media IDs.
@@ -119,8 +121,8 @@ class MediaSessionCallback(private val player: Player) :
119
121
  /**
120
122
  * Builds the gate tile from a per-request chrome: while a gate is active, tabs stay visible but a
121
123
  * gated browse/search level serves this single tile (see the gate checks in [onGetChildren] /
122
- * [onGetSearchResult]). Same shape as the error tiles — non-browsable, non-playable — and
123
- * deliberately NOT accompanied by a SessionError: a gate is deliberate app state, not a failure.
124
+ * [onGetSearchResult]). Same shape as the error tiles, and deliberately NOT accompanied by a
125
+ * SessionError: a gate is deliberate app state, not a failure.
124
126
  */
125
127
  private fun createGateMediaItem(gate: Gate): MediaItem =
126
128
  createErrorMediaItem(
@@ -211,6 +213,22 @@ class MediaSessionCallback(private val player: Player) :
211
213
  return super.onSetRating(session, controller, rating)
212
214
  }
213
215
 
216
+ /**
217
+ * Where a legacy controller's `setRating` arrives, naming the current item, and a Media3
218
+ * controller's `setRating(mediaId, rating)`, naming any item: only the current one can be rated.
219
+ */
220
+ override fun onSetRating(
221
+ session: MediaSession,
222
+ controller: MediaSession.ControllerInfo,
223
+ mediaId: String,
224
+ rating: Rating,
225
+ ): ListenableFuture<SessionResult> =
226
+ if (mediaId == session.player.currentMediaItem?.mediaId) {
227
+ onSetRating(session, controller, rating)
228
+ } else {
229
+ super.onSetRating(session, controller, mediaId, rating)
230
+ }
231
+
214
232
  @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
215
233
  override fun onGetLibraryRoot(
216
234
  session: MediaLibraryService.MediaLibrarySession,
@@ -259,102 +277,126 @@ class MediaSessionCallback(private val player: Player) :
259
277
  "onGetChildren: {parentId: $parentId, page: $page, pageSize: $pageSize, isSpecialPath: ${BrowserPathHelper.isSpecialPath(parentId)} }"
260
278
  )
261
279
  return scope.future {
262
- val audioBrowser =
263
- player.awaitBrowser().also { Timber.d("Browser ready, proceeding with onGetChildren") }
264
- val browserManager = audioBrowser.browserManager
265
-
266
- // While a gate is active, tabs stay visible (the root keeps serving them below) but each
267
- // non-root level is resolved per request: a gated path — including re-queries of the gate
268
- // tile's own sentinel path — serves the single gate tile, so drilling into it re-shows the
269
- // message instead of dead-ending in "No items"; an allowed path falls through to real
270
- // children. Checked before the offline guard: gated content isn't coming back with
271
- // connectivity, so the gate copy is the truer message.
272
- if (parentId != BrowserPathHelper.ROOT_PATH) {
273
- val outcome =
274
- audioBrowser.gateDecision(
275
- NativeGateRequest(reason = GateReason.BROWSE, path = parentId, search = null)
276
- )
277
- if (outcome.gated) {
278
- audioBrowser.onGate(GateEvent(GateReason.BROWSE))
279
- // gateDecision guarantees non-null chrome on a gated decision (override → default →
280
- // built-in).
281
- return@future LibraryResult.ofItemList(
282
- ImmutableList.of(createGateMediaItem(outcome.chrome!!)),
283
- params,
284
- )
280
+ children(session, browser, parentId, page, pageSize, params).also {
281
+ if (parentId == BrowserPathHelper.ROOT_PATH && page == 0) {
282
+ rootTile = deadEndTileOf(it.value.orEmpty())
285
283
  }
286
284
  }
285
+ }
286
+ }
287
287
 
288
- // A drill-in on the error / offline / empty tile returns nothing (see isDeadEndPath). For
289
- // the offline tile, re-send the alert when still offline so a tap surfaces the explanation
290
- // again — but only then, since these paths are also re-queried by notifyChildrenChanged
291
- // (e.g. when connectivity returns) without any user action.
292
- if (BrowserPathHelper.isDeadEndPath(parentId)) {
293
- if (parentId == BrowserPathHelper.OFFLINE_PATH && !player.networkMonitor.isOnline.value) {
294
- sendBrowseError(session, browser, offline = true)
295
- }
296
- return@future LibraryResult.ofItemList(ImmutableList.of<MediaItem>(), params)
297
- }
288
+ /**
289
+ * The tile the root last served in place of its tabs, or null. Android Automotive OS shows such a
290
+ * root as one tab that drills into the tile's sentinel path (see [deadEndChildren]).
291
+ */
292
+ @Volatile private var rootTile: MediaItem? = null
298
293
 
299
- if (
300
- !player.networkMonitor.isOnline.value && browserManager.config.androidControllerOfflineError
301
- ) {
302
- Timber.w("Network offline - returning error message for: $parentId")
303
- sendBrowseError(session, browser, offline = true)
304
- return@future LibraryResult.ofItemList(
305
- ImmutableList.of(
306
- createOfflineMediaItem(audioBrowser.resolveFormattedError(offlineError(), parentId))
307
- ),
294
+ private suspend fun children(
295
+ session: MediaLibraryService.MediaLibrarySession,
296
+ browser: MediaSession.ControllerInfo,
297
+ parentId: String,
298
+ page: Int,
299
+ pageSize: Int,
300
+ params: MediaLibraryService.LibraryParams?,
301
+ ): LibraryResult<ImmutableList<MediaItem>> {
302
+ val audioBrowser =
303
+ player.awaitBrowser().also { Timber.d("Browser ready, proceeding with onGetChildren") }
304
+ val browserManager = audioBrowser.browserManager
305
+
306
+ // While a gate is active, tabs stay visible (the root keeps serving them below) but each
307
+ // non-root level is resolved per request: a gated path — including re-queries of the gate
308
+ // tile's own sentinel path — serves the single gate tile, so drilling into it re-shows the
309
+ // message instead of dead-ending in "No items"; an allowed path falls through to real
310
+ // children. Checked before the offline guard: gated content isn't coming back with
311
+ // connectivity, so the gate copy is the truer message.
312
+ if (parentId != BrowserPathHelper.ROOT_PATH) {
313
+ val outcome =
314
+ audioBrowser.gateDecision(
315
+ NativeGateRequest(reason = GateReason.BROWSE, path = parentId, search = null)
316
+ )
317
+ if (outcome.gated) {
318
+ audioBrowser.onGate(GateEvent(GateReason.BROWSE))
319
+ // gateDecision guarantees non-null chrome on a gated decision (override → default →
320
+ // built-in).
321
+ return LibraryResult.ofItemList(
322
+ ImmutableList.of(createGateMediaItem(outcome.chrome!!)),
308
323
  params,
309
324
  )
310
325
  }
326
+ }
311
327
 
312
- try {
313
- val children =
314
- if (parentId == BrowserPathHelper.ROOT_PATH) {
315
- // Disabled tabs hide (Track.disabled) — filtered before the four-tab cap so an
316
- // unavailable tab never costs an available one its slot.
317
- val tabs = browserManager.queryTabs().filterNot { it.disabled == true }
318
- if (tabs.size > 4) {
319
- Timber.w(
320
- "Root has ${tabs.size} tabs; dropping ${tabs.size - 4} (Android Auto root limit)"
321
- )
322
- }
323
- toFlatMediaItems(tabs.take(4))
324
- } else {
325
- // Section styles arrive page-folded (`section ?? page`, ADR 0011).
326
- val resolvedTrack = browserManager.resolve(parentId)
327
- val sections =
328
- resolvedTrack.styleResolvedSections()
329
- ?: throw IllegalStateException("Expected browsed ResolvedTrack to have sections")
330
- browserManager.warnIfGridPageLacksPromise(parentId, sections)
331
- // A page with no children resolved fine, so it raises no SessionError and no event —
332
- // notifyChildrenChanged re-queries these paths without any user action. It serves the
333
- // app's path-aware `empty-content` copy as one inert tile (ADR 0001) instead of
334
- // Android Auto's bare "No items".
335
- browseLevelItems(toMediaItems(sections)) {
336
- audioBrowser.resolveFormattedError(emptyContentError(), parentId)
337
- }
338
- }
328
+ // For the offline tile, re-send the alert when still offline so a tap surfaces the
329
+ // explanation again — but only then, since these paths are also re-queried by
330
+ // notifyChildrenChanged (e.g. when connectivity returns) without any user action.
331
+ if (BrowserPathHelper.isDeadEndPath(parentId)) {
332
+ val offline = !player.networkMonitor.isOnline.value
333
+ if (parentId == BrowserPathHelper.OFFLINE_PATH && offline) {
334
+ sendBrowseError(session, browser, offline = true)
335
+ }
336
+ return LibraryResult.ofItemList(
337
+ deadEndChildren(parentId, rootTile, Automotive.device, offline),
338
+ params,
339
+ )
340
+ }
339
341
 
340
- LibraryResult.ofItemList(ImmutableList.copyOf(children.paginate(page, pageSize)), params)
341
- } catch (e: Exception) {
342
- // A cancelled browse (controller disconnected) is not a failure — don't render it as an
343
- // error tile. awaitBrowser's TimeoutCancellationException IS a real failure, keep that.
344
- if (e is CancellationException && e !is TimeoutCancellationException) throw e
345
- Timber.e(e, "Error getting children for parentId: $parentId")
346
- // A tile rather than a bare ofError() — see createErrorMediaItem and
347
- // https://github.com/androidx/media/issues/2901
348
- sendBrowseError(session, browser, offline = false)
349
- LibraryResult.ofItemList(
350
- ImmutableList.of(
351
- createBrowseErrorMediaItem(
352
- audioBrowser.resolveFormattedError(navigationErrorFor(e), parentId)
342
+ if (
343
+ !player.networkMonitor.isOnline.value && browserManager.config.androidControllerOfflineError
344
+ ) {
345
+ Timber.w("Network offline - returning error message for: $parentId")
346
+ sendBrowseError(session, browser, offline = true)
347
+ return LibraryResult.ofItemList(
348
+ ImmutableList.of(
349
+ createOfflineMediaItem(audioBrowser.resolveFormattedError(offlineError(), parentId))
350
+ ),
351
+ params,
352
+ )
353
+ }
354
+
355
+ return try {
356
+ val children =
357
+ if (parentId == BrowserPathHelper.ROOT_PATH) {
358
+ // Disabled tabs hide (Track.disabled) — filtered before the four-tab cap so an
359
+ // unavailable tab never costs an available one its slot.
360
+ val tabs = browserManager.queryTabs().filterNot { it.disabled == true }
361
+ if (tabs.size > 4) {
362
+ Timber.w(
363
+ "Root has ${tabs.size} tabs; dropping ${tabs.size - 4} (Android Auto root limit)"
353
364
  )
354
- ),
355
- params,
356
- )
357
- }
365
+ }
366
+ toFlatMediaItems(tabs.take(4))
367
+ } else {
368
+ // Section styles arrive page-folded (`section ?? page`, ADR 0011).
369
+ val resolvedTrack = browserManager.resolve(parentId)
370
+ val sections =
371
+ resolvedTrack.styleResolvedSections()
372
+ ?: throw IllegalStateException("Expected browsed ResolvedTrack to have sections")
373
+ browserManager.warnIfGridPageLacksPromise(parentId, sections)
374
+ // A page with no children resolved fine, so it raises no SessionError and no event —
375
+ // notifyChildrenChanged re-queries these paths without any user action. It serves the
376
+ // app's path-aware `empty-content` copy as one inert tile (ADR 0001) instead of
377
+ // Android Auto's bare "No items".
378
+ browseLevelItems(toMediaItems(sections)) {
379
+ audioBrowser.resolveFormattedError(emptyContentError(), parentId)
380
+ }
381
+ }
382
+
383
+ LibraryResult.ofItemList(ImmutableList.copyOf(children.paginate(page, pageSize)), params)
384
+ } catch (e: Exception) {
385
+ // A cancelled browse (controller disconnected) is not a failure — don't render it as an
386
+ // error tile. awaitBrowser's TimeoutCancellationException IS a real failure, keep that.
387
+ if (e is CancellationException && e !is TimeoutCancellationException) throw e
388
+ Timber.e(e, "Error getting children for parentId: $parentId")
389
+ // A tile rather than a bare ofError() — see createErrorMediaItem and
390
+ // https://github.com/androidx/media/issues/2901
391
+ sendBrowseError(session, browser, offline = false)
392
+ LibraryResult.ofItemList(
393
+ ImmutableList.of(
394
+ createBrowseErrorMediaItem(
395
+ audioBrowser.resolveFormattedError(navigationErrorFor(e), parentId)
396
+ )
397
+ ),
398
+ params,
399
+ )
358
400
  }
359
401
  }
360
402
 
@@ -1020,10 +1062,35 @@ class MediaSessionCallback(private val player: Player) :
1020
1062
  }
1021
1063
 
1022
1064
  /**
1023
- * Builds a non-browsable, non-playable [MediaItem] used to surface an error inside an Android Auto
1024
- * / AAOS browse list. Rendered as a greyed-out, non-interactive tile, which is the only
1025
- * side-effect-free way to communicate a browse failure to legacy controllers (Media3 drops
1026
- * [LibraryResult.ofError] on the legacy browse bridge, leaving an empty "No items" screen).
1065
+ * What a drill-in on a tile's sentinel path serves. Nothing, so Android Auto, which drills into a
1066
+ * tile whatever its flags, dead-ends at "No items" rather than stacking error pages. On Android
1067
+ * Automotive OS, a root that serves only a tile shows as one tab that drills in here, and an empty
1068
+ * level as "Media isn't available for this list", so there the [rootTile] is served again, unless
1069
+ * it is the offline tile and the device is back online.
1070
+ */
1071
+ internal fun deadEndChildren(
1072
+ parentId: String,
1073
+ rootTile: MediaItem?,
1074
+ automotive: Boolean,
1075
+ offline: Boolean,
1076
+ ): List<MediaItem> =
1077
+ listOfNotNull(
1078
+ rootTile?.takeIf {
1079
+ automotive &&
1080
+ it.mediaId == parentId &&
1081
+ (parentId != BrowserPathHelper.OFFLINE_PATH || offline)
1082
+ }
1083
+ )
1084
+
1085
+ /** The single tile of a level that serves one in place of its items, or null. */
1086
+ internal fun deadEndTileOf(items: List<MediaItem>): MediaItem? =
1087
+ items.singleOrNull()?.takeIf { BrowserPathHelper.isDeadEndPath(it.mediaId) }
1088
+
1089
+ /**
1090
+ * Builds a non-playable [MediaItem] used to surface an error inside an Android Auto / AAOS browse
1091
+ * list. Rendered as a tile, which is the only side-effect-free way to communicate a browse failure
1092
+ * to legacy controllers (Media3 drops [LibraryResult.ofError] on the legacy browse bridge, leaving
1093
+ * an empty "No items" screen).
1027
1094
  *
1028
1095
  * Tiles are the only in-browse error signal that exists. Verified on a head unit (2026-06): the
1029
1096
  * Android Auto browse list renders no error text for a transient [SessionError], for sticky
@@ -1038,10 +1105,9 @@ internal fun createErrorMediaItem(mediaId: String, title: String, subtitle: Stri
1038
1105
  MediaMetadata.Builder()
1039
1106
  .setTitle(title)
1040
1107
  .setSubtitle(subtitle)
1041
- // Android Auto ignores these flags and drills into a tapped tile anyway; onGetChildren
1042
- // returns an empty list for the sentinel paths, so it dead-ends at "No Items" rather
1043
- // than stacking error pages.
1044
- .setIsBrowsable(false)
1108
+ // Android Automotive OS's car media app drops an item that is neither browsable nor
1109
+ // playable; Android Auto ignores these flags and drills in anyway (see deadEndChildren).
1110
+ .setIsBrowsable(Automotive.device)
1045
1111
  .setIsPlayable(false)
1046
1112
  .build()
1047
1113
  )
@@ -1061,8 +1127,7 @@ private fun createErrorMediaItem(mediaId: String, formatted: FormattedNavigation
1061
1127
  /**
1062
1128
  * Builds the empty tile from the app's formatted `empty-content` copy for the page's path, so an
1063
1129
  * empty Favorites tab and an empty search can be worded apart (ADR 0001). Same shape as the error
1064
- * tiles — non-browsable, non-playable — and deliberately NOT accompanied by a SessionError: an
1065
- * empty page is a successful resolve.
1130
+ * tiles, and deliberately NOT accompanied by a SessionError: an empty page is a successful resolve.
1066
1131
  */
1067
1132
  internal fun createEmptyMediaItem(formatted: FormattedNavigationError): MediaItem =
1068
1133
  createErrorMediaItem(BrowserPathHelper.EMPTY_PATH, formatted)
@@ -11,6 +11,12 @@ 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)
19
+
14
20
  /**
15
21
  * A slot's Media3 preference list: the requested slot, then OVERFLOW as a fallback.
16
22
  *
@@ -49,7 +55,7 @@ internal fun media3SlotsFor(slot: ButtonSlot): IntArray =
49
55
  * extras that Android Auto and the Android 13+ system media controls read. Publishing
50
56
  * per-controller instead would reach neither, since Android Auto connects as a legacy controller.
51
57
  */
52
- class MediaSessionCommandManager {
58
+ class MediaSessionCommandManager(private val automotive: Boolean) {
53
59
 
54
60
  companion object {
55
61
  private const val CUSTOM_ACTION_JUMP_BACKWARD = "JUMP_BACKWARD"
@@ -432,6 +438,10 @@ class MediaSessionCommandManager {
432
438
  * Assembles the CommandButtons for an already-derived slot layout (see [deriveButtonSlots] — the
433
439
  * slots are pre-filtered by Capability).
434
440
  *
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.
444
+ *
435
445
  * Each button gets its requested slot followed by OVERFLOW as a fallback. `slots` is an ordered
436
446
  * preference list, and every surface caps how many buttons it renders — a head unit, the
437
447
  * collapsed notification, the Android 13+ media controls all truncate differently. Without a
@@ -441,7 +451,9 @@ class MediaSessionCommandManager {
441
451
  slots: List<SlottedButton>,
442
452
  favorited: Boolean?,
443
453
  ): List<CommandButton> =
444
- slots.map { (button, slot) ->
445
- buttonFor(button, favorited).setSlots(*media3SlotsFor(slot)).build()
446
- }
454
+ slots
455
+ .filterNot { automotive && it.isStandardSkip }
456
+ .map { (button, slot) ->
457
+ buttonFor(button, favorited).setSlots(*media3SlotsFor(slot)).build()
458
+ }
447
459
  }
@@ -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
  */
@@ -742,8 +753,7 @@ class Player(internal val context: Context) {
742
753
  // This preserves internal references and avoids playback interruption
743
754
  // Note: setTag() requires setUri() to be called, so we must re-set the URI
744
755
  val currentMediaItem = exoPlayer.getMediaItemAt(index)
745
- val updatedMetadata =
746
- currentMediaItem.mediaMetadata.buildUpon().setUserRating(HeartRating(favorited)).build()
756
+ val updatedMetadata = currentMediaItem.mediaMetadata.buildUpon().setFavorite(favorited).build()
747
757
  val updatedMediaItem =
748
758
  currentMediaItem
749
759
  .buildUpon()
@@ -842,11 +852,13 @@ class Player(internal val context: Context) {
842
852
  null
843
853
  }
844
854
  val uri = resolved?.uri?.takeIf { it.isNotEmpty() } ?: return null
855
+ val published =
856
+ TrackFactory.sessionArtworkUri(uri, resolved.headers, SvgArtworkRenderer.isSvgUrl(uri))
845
857
  // Remember how this URI was produced: Media3 hands it back to the bitmap loader, which
846
858
  // re-resolves Track-first (with the nowPlayingArtwork kind, not the global artwork
847
859
  // config).
848
- browserManager.artworkResolutions.register(uri, track, config)
849
- return uri
860
+ browserManager.artworkResolutions.register(published, track, config)
861
+ return published
850
862
  }
851
863
 
852
864
  override fun emitNowPlayingChanged(metadata: NowPlayingMetadata) {
@@ -920,6 +932,14 @@ class Player(internal val context: Context) {
920
932
  browserManager.displayArtworkSource(uri, imageContext)?.let {
921
933
  return it
922
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
+ }
923
943
  withContext(Dispatchers.Main) { findQueueTrackByArtworkUri(uri) }
924
944
  ?.let { track ->
925
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,97 @@
1
+ package com.audiobrowser
2
+
3
+ import android.content.ComponentName
4
+ import android.os.Binder
5
+ import android.os.Bundle
6
+ import android.os.Looper
7
+ import androidx.media3.common.HeartRating
8
+ import androidx.media3.session.MediaSession
9
+ import androidx.media3.session.SessionResult
10
+ import org.junit.After
11
+ import org.junit.Assert.assertEquals
12
+ import org.junit.Test
13
+ import org.junit.runner.RunWith
14
+ import org.robolectric.Robolectric
15
+ import org.robolectric.RobolectricTestRunner
16
+ import org.robolectric.RuntimeEnvironment
17
+ import org.robolectric.Shadows.shadowOf
18
+
19
+ /**
20
+ * Media3 hands a legacy controller's `setRating` to the callback that names a media id, with the
21
+ * current item's id. Robolectric cannot route a MediaControllerCompat to the session, so these call
22
+ * that callback as Media3 does.
23
+ */
24
+ @RunWith(RobolectricTestRunner::class)
25
+ class LegacyRatingTest {
26
+
27
+ private val controller = run {
28
+ val application = RuntimeEnvironment.getApplication()
29
+ shadowOf(application)
30
+ .setComponentNameAndServiceForBindService(
31
+ ComponentName(application, HeadlessTaskService::class.java),
32
+ Binder(),
33
+ )
34
+ Robolectric.buildService(Service::class.java).create()
35
+ }
36
+ private val service = controller.get()
37
+ private val player = service.player
38
+ private val legacyController =
39
+ MediaSession.ControllerInfo.createTestOnlyControllerInfo(
40
+ "legacy",
41
+ 0,
42
+ 0,
43
+ MediaSession.ControllerInfo.LEGACY_CONTROLLER_VERSION,
44
+ MediaSession.ControllerInfo.LEGACY_CONTROLLER_INTERFACE_VERSION,
45
+ false,
46
+ Bundle.EMPTY,
47
+ false,
48
+ )
49
+ private val session = service.onGetSession(legacyController)
50
+
51
+ @After
52
+ fun destroy() {
53
+ controller.destroy()
54
+ }
55
+
56
+ private fun idle() = shadowOf(Looper.getMainLooper()).idle()
57
+
58
+ private fun rate(mediaId: String, heart: Boolean): Int {
59
+ val result =
60
+ player
61
+ .getMediaSessionCallback()
62
+ .onSetRating(session, legacyController, mediaId, HeartRating(heart))
63
+ .get()
64
+ idle()
65
+ return result.resultCode
66
+ }
67
+
68
+ private fun currentMediaId() = session.player.currentMediaItem!!.mediaId
69
+
70
+ private fun loadTrack() {
71
+ controller.bind()
72
+ player.load(TestFixtures.track(id = "a", favorited = false))
73
+ idle()
74
+ }
75
+
76
+ @Test
77
+ fun `a rating of the current item sets its favorite and USER_RATING`() {
78
+ loadTrack()
79
+
80
+ assertEquals(SessionResult.RESULT_SUCCESS, rate(currentMediaId(), true))
81
+ assertEquals(true, player.currentTrack?.favorited)
82
+ assertEquals(HeartRating(true), session.player.mediaMetadata.userRating)
83
+
84
+ assertEquals(SessionResult.RESULT_SUCCESS, rate(currentMediaId(), false))
85
+ assertEquals(false, player.currentTrack?.favorited)
86
+ assertEquals(HeartRating(false), session.player.mediaMetadata.userRating)
87
+ }
88
+
89
+ @Test
90
+ fun `a rating of another item leaves the favorite`() {
91
+ loadTrack()
92
+
93
+ assertEquals(SessionResult.RESULT_ERROR_NOT_SUPPORTED, rate("b", true))
94
+ assertEquals(false, player.currentTrack?.favorited)
95
+ assertEquals(HeartRating(false), session.player.mediaMetadata.userRating)
96
+ }
97
+ }
@@ -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() {
@@ -1,7 +1,10 @@
1
1
  package com.audiobrowser.util
2
2
 
3
+ import androidx.core.net.toUri
3
4
  import androidx.media3.common.HeartRating
4
5
  import com.audiobrowser.TestFixtures
6
+ import com.audiobrowser.browser.BrowseArtworkRegistry
7
+ import org.junit.After
5
8
  import org.junit.Assert.assertEquals
6
9
  import org.junit.Assert.assertNull
7
10
  import org.junit.Assert.assertTrue
@@ -32,4 +35,76 @@ class TrackFactoryRatingTest {
32
35
  val item = TrackFactory.toMedia3(TestFixtures.track(favorited = null))
33
36
  assertNull(item.mediaMetadata.userRating)
34
37
  }
38
+
39
+ @After
40
+ fun resetDevice() {
41
+ Automotive.device = false
42
+ TrackFactory.artworkRoutes = null
43
+ }
44
+
45
+ private fun automotive(): BrowseArtworkRegistry =
46
+ BrowseArtworkRegistry().also {
47
+ Automotive.device = true
48
+ TrackFactory.artworkRoutes = ArtworkRoutes(it, "app.artwork")
49
+ }
50
+
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
+ @Test
59
+ fun `Android Automotive OS serves http artwork through the provider`() {
60
+ val registry = automotive()
61
+ val item = TrackFactory.toMedia3(TestFixtures.track(artwork = "https://a/1.png"))
62
+ val uri = item.mediaMetadata.artworkUri!!
63
+ assertEquals("content", uri.scheme)
64
+ assertEquals("app.artwork", uri.authority)
65
+ assertEquals("https://a/1.png", registry.lookup(ArtworkUris.parseToken(uri)!!)!!.finalUrl)
66
+ }
67
+
68
+ @Test
69
+ fun `a phone keeps the http artwork`() {
70
+ TrackFactory.artworkRoutes = ArtworkRoutes(BrowseArtworkRegistry(), "app.artwork")
71
+ val item = TrackFactory.toMedia3(TestFixtures.track(artwork = "https://a/1.png"))
72
+ assertEquals("https://a/1.png", item.mediaMetadata.artworkUri.toString())
73
+ }
74
+
75
+ @Test
76
+ fun `Android Automotive OS keeps non-http artwork as it is`() {
77
+ automotive()
78
+ assertEquals(
79
+ "android.resource://app/1",
80
+ TrackFactory.sessionArtworkUri("android.resource://app/1", null, isSvg = false),
81
+ )
82
+ }
83
+
84
+ @Test
85
+ fun `the session's artwork outlives a clear of the registry, and maps back to its URL`() {
86
+ val registry = automotive()
87
+ val uri = TrackFactory.sessionArtworkUri("https://a/1.png", null, isSvg = false).toUri()
88
+ registry.clear()
89
+ assertEquals("https://a/1.png", TrackFactory.artworkRoutes!!.publicUrl(uri))
90
+ }
91
+
92
+ @Test
93
+ fun `JS gets another URI as it is, and none for artwork the provider forgot`() {
94
+ automotive()
95
+ val routes = TrackFactory.artworkRoutes!!
96
+ assertEquals("https://a/1.png", routes.publicUrl("https://a/1.png".toUri()))
97
+ assertEquals("content://other/art/x", routes.publicUrl("content://other/art/x".toUri()))
98
+ assertNull(routes.publicUrl("content://app.artwork/art/forgotten".toUri()))
99
+ }
100
+
101
+ @Test
102
+ fun `the session pins a browse item's provider URI it is handed back`() {
103
+ val registry = automotive()
104
+ val browseUri =
105
+ ArtworkRoutes(registry, "app.artwork").route("https://a/1.png", null, false, pinned = false)
106
+ assertEquals(browseUri, TrackFactory.sessionArtworkUri(browseUri, null, isSvg = false))
107
+ registry.clear()
108
+ assertEquals("https://a/1.png", TrackFactory.artworkRoutes!!.publicUrl(browseUri.toUri()))
109
+ }
35
110
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-audio-browser",
3
- "version": "0.2.0-next.45",
3
+ "version": "0.2.0-next.47",
4
4
  "description": "react-native-audio-browser is a react native package built with Nitro",
5
5
  "keywords": [
6
6
  "react-native",