react-native-audio-browser 0.2.0-next.35 → 0.2.0-next.37

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.
@@ -69,6 +69,7 @@ android {
69
69
  // android.util.LruCache.evictAll() is what this flag used to paper over.
70
70
  testOptions {
71
71
  unitTests.returnDefaultValues = false
72
+ unitTests.includeAndroidResources = true
72
73
  }
73
74
 
74
75
  defaultConfig {
@@ -205,9 +206,12 @@ dependencies {
205
206
  implementation "org.jetbrains.kotlinx:kotlinx-coroutines-guava:1.8.0"
206
207
  implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3"
207
208
 
208
- // HTTP client for browser API requests
209
- implementation 'com.squareup.okhttp3:okhttp:5.3.0'
210
- implementation 'com.squareup.okhttp3:logging-interceptor:5.3.0'
209
+ // HTTP client for browser API requests. The BOM also aligns the app's other
210
+ // okhttp3 modules: React Native's okhttp-urlconnection 4 calls a class
211
+ // OkHttp 5 removed, and crashes on the first fetch that carries a cookie.
212
+ implementation platform('com.squareup.okhttp3:okhttp-bom:5.3.0')
213
+ implementation 'com.squareup.okhttp3:okhttp'
214
+ implementation 'com.squareup.okhttp3:logging-interceptor'
211
215
 
212
216
  // JSON parsing
213
217
  implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0'
@@ -0,0 +1,131 @@
1
+ package com.audiobrowser
2
+
3
+ import android.app.ForegroundServiceStartNotAllowedException
4
+ import android.app.Notification
5
+ import android.app.NotificationManager
6
+ import android.content.Intent
7
+ import android.content.pm.ServiceInfo
8
+ import android.os.Build
9
+ import android.view.KeyEvent
10
+ import androidx.annotation.OptIn
11
+ import androidx.core.app.NotificationChannelCompat
12
+ import androidx.core.app.NotificationCompat
13
+ import androidx.core.app.NotificationManagerCompat
14
+ import androidx.core.app.ServiceCompat
15
+ import androidx.core.content.IntentCompat
16
+ import androidx.core.os.bundleOf
17
+ import androidx.media3.common.util.UnstableApi
18
+ import androidx.media3.session.DefaultMediaNotificationProvider
19
+ import androidx.media3.session.MediaSessionService
20
+ import kotlinx.coroutines.CoroutineScope
21
+ import kotlinx.coroutines.launch
22
+ import timber.log.Timber
23
+
24
+ /**
25
+ * Runs [play] for a start sent with `startForegroundService`, holding the service in the foreground
26
+ * meanwhile ([holdForeground]). When [play] returns false the placeholder is released, and the
27
+ * service stops unless [hasMedia] says the player still has something to keep it for. [play]
28
+ * reports failure by returning false, not by throwing.
29
+ */
30
+ internal fun <S> S.playInForeground(
31
+ scope: CoroutineScope,
32
+ startId: Int,
33
+ hasMedia: () -> Boolean,
34
+ play: suspend () -> Boolean,
35
+ ) where S : MediaSessionService, S : MediaSessionService.Listener {
36
+ holdForeground()
37
+ scope.launch {
38
+ if (play()) return@launch
39
+ releasePlaceholder()
40
+ if (!hasMedia()) stopSelf(startId)
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Satisfies a `startForegroundService` start, which Android kills the app for unless the service
46
+ * calls `startForeground()` within seconds, by going foreground at once under Media3's notification
47
+ * id and channel (valid while the library sets no notification provider of its own): with the media
48
+ * notification already showing there, else with a placeholder. Media3's next notification update
49
+ * replaces or removes either; [releasePlaceholder] removes the placeholder when no update will
50
+ * come. Holds nothing below API 26, when the service is already foreground (below API 29, where
51
+ * that can't be read, it holds Media3's notification again), or when Android refuses the start,
52
+ * which is reported to [MediaSessionService.Listener.onForegroundServiceStartNotAllowedException].
53
+ */
54
+ internal fun <S> S.holdForeground()
55
+ where S : MediaSessionService, S : MediaSessionService.Listener {
56
+ if (Build.VERSION.SDK_INT < 26 || isForeground()) return
57
+ try {
58
+ startForeground(mediaNotification()?.notification ?: placeholder())
59
+ } catch (e: IllegalStateException) {
60
+ if (Build.VERSION.SDK_INT < 31 || e !is ForegroundServiceStartNotAllowedException) throw e
61
+ Timber.w(e, "Foreground start refused")
62
+ onForegroundServiceStartNotAllowedException()
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Removes the placeholder [holdForeground] posted, if it is still up, and has Media3 post the
68
+ * notification the player warrants. For a start whose play request changed nothing in the player:
69
+ * Media3 tracks the session only once a controller has connected, so its update alone may never
70
+ * come.
71
+ */
72
+ @OptIn(UnstableApi::class)
73
+ internal fun MediaSessionService.releasePlaceholder() {
74
+ if (mediaNotification()?.notification?.extras?.getBoolean(PLACEHOLDER_EXTRA) == true) {
75
+ ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
76
+ }
77
+ triggerNotificationUpdate()
78
+ }
79
+
80
+ /**
81
+ * Whether [this] is a press `MediaButtonReceiver.onReceive` starts the service in the foreground
82
+ * for.
83
+ */
84
+ internal fun Intent.isForegroundStartKey(): Boolean =
85
+ action == Intent.ACTION_MEDIA_BUTTON &&
86
+ IntentCompat.getParcelableExtra(this, Intent.EXTRA_KEY_EVENT, KeyEvent::class.java)?.keyCode in
87
+ PLAY_KEYS
88
+
89
+ private val PLAY_KEYS =
90
+ setOf(
91
+ KeyEvent.KEYCODE_MEDIA_PLAY,
92
+ KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,
93
+ KeyEvent.KEYCODE_HEADSETHOOK,
94
+ )
95
+
96
+ private const val PLACEHOLDER_EXTRA = "com.audiobrowser.placeholder"
97
+
98
+ private fun MediaSessionService.mediaNotification() =
99
+ getSystemService(NotificationManager::class.java).activeNotifications.firstOrNull {
100
+ it.id == DefaultMediaNotificationProvider.DEFAULT_NOTIFICATION_ID
101
+ }
102
+
103
+ private fun MediaSessionService.isForeground(): Boolean =
104
+ Build.VERSION.SDK_INT >= 29 && foregroundServiceType != ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE
105
+
106
+ private fun MediaSessionService.startForeground(notification: Notification) =
107
+ ServiceCompat.startForeground(
108
+ this,
109
+ DefaultMediaNotificationProvider.DEFAULT_NOTIFICATION_ID,
110
+ notification,
111
+ if (Build.VERSION.SDK_INT >= 29) ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK else 0,
112
+ )
113
+
114
+ @OptIn(UnstableApi::class)
115
+ private fun MediaSessionService.placeholder(): Notification {
116
+ NotificationManagerCompat.from(this)
117
+ .createNotificationChannel(
118
+ NotificationChannelCompat.Builder(
119
+ DefaultMediaNotificationProvider.DEFAULT_CHANNEL_ID,
120
+ NotificationManagerCompat.IMPORTANCE_LOW,
121
+ )
122
+ .setName(getString(DefaultMediaNotificationProvider.DEFAULT_CHANNEL_NAME_RESOURCE_ID))
123
+ .build()
124
+ )
125
+ return NotificationCompat.Builder(this, DefaultMediaNotificationProvider.DEFAULT_CHANNEL_ID)
126
+ .setSmallIcon(androidx.media3.session.R.drawable.media3_notification_small_icon)
127
+ .setVisibility(NotificationCompat.VISIBILITY_SECRET)
128
+ .setCategory(Notification.CATEGORY_TRANSPORT)
129
+ .addExtras(bundleOf(PLACEHOLDER_EXTRA to true))
130
+ .build()
131
+ }
@@ -37,7 +37,6 @@ import kotlinx.coroutines.Dispatchers
37
37
  import kotlinx.coroutines.MainScope
38
38
  import kotlinx.coroutines.SupervisorJob
39
39
  import kotlinx.coroutines.cancel
40
- import kotlinx.coroutines.launch
41
40
  import timber.log.Timber
42
41
 
43
42
  /**
@@ -120,6 +119,7 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
120
119
  // Store references in Player for artwork URL transformation and SVG pre-rendering
121
120
  player.coilBitmapLoader = coilBitmapLoader
122
121
  player.imageLoader = imageLoader
122
+ player.onPlaybackResumptionFailed = { releasePlaceholder() }
123
123
 
124
124
  // Populate the artwork content provider holder so ArtworkContentProvider can serve
125
125
  // browse artwork to Android Auto / AAOS over content:// URIs.
@@ -183,8 +183,14 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
183
183
  ?.let { searchIntent ->
184
184
  val searchParams = parseSearchIntent(searchIntent)
185
185
  Timber.d("MEDIA_PLAY_FROM_SEARCH intent received: $searchParams")
186
- scope.launch { player.playFromSearch(searchParams) }
186
+ // A search that plays has waited for AudioBrowser, whose MediaBrowser connecting hands
187
+ // the notification to Media3.
188
+ playInForeground(scope, startId, hasMedia = { player.currentTrack != null }) {
189
+ player.playFromSearch(searchParams)
190
+ }
187
191
  }
192
+ // Released by Media3's update after the play request, or by a failed resumption.
193
+ if (intent?.isForegroundStartKey() == true) holdForeground()
188
194
 
189
195
  return super.onStartCommand(intent, flags, startId)
190
196
  }
@@ -1,6 +1,7 @@
1
1
  package com.audiobrowser.player
2
2
 
3
3
  import android.os.Bundle
4
+ import androidx.core.content.ContextCompat
4
5
  import androidx.media3.common.MediaItem
5
6
  import androidx.media3.common.MediaMetadata
6
7
  import androidx.media3.common.Rating
@@ -23,6 +24,7 @@ import com.audiobrowser.util.BrowserPathHelper
23
24
  import com.audiobrowser.util.RatingFavorites
24
25
  import com.audiobrowser.util.TrackFactory
25
26
  import com.google.common.collect.ImmutableList
27
+ import com.google.common.util.concurrent.FutureCallback
26
28
  import com.google.common.util.concurrent.Futures
27
29
  import com.google.common.util.concurrent.ListenableFuture
28
30
  import com.margelo.nitro.audiobrowser.FormattedNavigationError
@@ -927,6 +929,25 @@ class MediaSessionCallback(private val player: Player) :
927
929
  mediaSession: MediaSession,
928
930
  controller: MediaSession.ControllerInfo,
929
931
  isForPlayback: Boolean,
932
+ ): ListenableFuture<MediaSession.MediaItemsWithStartPosition> {
933
+ val resumption = resume(controller, isForPlayback)
934
+ if (isForPlayback) {
935
+ Futures.addCallback(
936
+ resumption,
937
+ object : FutureCallback<MediaSession.MediaItemsWithStartPosition> {
938
+ override fun onSuccess(result: MediaSession.MediaItemsWithStartPosition) {}
939
+
940
+ override fun onFailure(t: Throwable) = player.onPlaybackResumptionFailed()
941
+ },
942
+ ContextCompat.getMainExecutor(player.context),
943
+ )
944
+ }
945
+ return resumption
946
+ }
947
+
948
+ private fun resume(
949
+ controller: MediaSession.ControllerInfo,
950
+ isForPlayback: Boolean,
930
951
  ): ListenableFuture<MediaSession.MediaItemsWithStartPosition> {
931
952
  Timber.d("${controller.packageName}")
932
953
 
@@ -127,6 +127,9 @@ class Player(internal val context: Context) {
127
127
  */
128
128
  var imageLoader: coil3.ImageLoader? = null
129
129
 
130
+ /** Called on the main thread when a resumption meant to start playback fails. Set by Service. */
131
+ var onPlaybackResumptionFailed: () -> Unit = {}
132
+
130
133
  /** Registry that maps content:// tokens to artwork URLs for the browse content provider. */
131
134
  val browseArtworkRegistry = com.audiobrowser.browser.BrowseArtworkRegistry()
132
135
 
@@ -0,0 +1,152 @@
1
+ package com.audiobrowser
2
+
3
+ import android.app.Notification
4
+ import android.app.NotificationManager
5
+ import android.content.Intent
6
+ import android.content.pm.ServiceInfo
7
+ import android.view.KeyEvent
8
+ import androidx.annotation.OptIn
9
+ import androidx.core.app.NotificationCompat
10
+ import androidx.core.app.ServiceCompat
11
+ import androidx.media3.common.util.UnstableApi
12
+ import androidx.media3.session.DefaultMediaNotificationProvider
13
+ import androidx.media3.session.MediaSession
14
+ import androidx.media3.session.MediaSessionService
15
+ import kotlinx.coroutines.CoroutineScope
16
+ import kotlinx.coroutines.Dispatchers
17
+ import org.junit.Assert.assertEquals
18
+ import org.junit.Assert.assertFalse
19
+ import org.junit.Assert.assertTrue
20
+ import org.junit.Test
21
+ import org.junit.runner.RunWith
22
+ import org.robolectric.Robolectric
23
+ import org.robolectric.RobolectricTestRunner
24
+ import org.robolectric.Shadows.shadowOf
25
+ import org.robolectric.annotation.Config
26
+
27
+ // Robolectric: startForeground/stopForeground/stopSelf only exist under the framework, and
28
+ // ShadowService records each.
29
+ @OptIn(UnstableApi::class)
30
+ @RunWith(RobolectricTestRunner::class)
31
+ class ForegroundStartTest {
32
+
33
+ class SessionlessService : MediaSessionService(), MediaSessionService.Listener {
34
+ override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = null
35
+ }
36
+
37
+ private val service = Robolectric.buildService(SessionlessService::class.java).create().get()
38
+ private val scope = CoroutineScope(Dispatchers.Unconfined)
39
+ private val mediaNotificationId = DefaultMediaNotificationProvider.DEFAULT_NOTIFICATION_ID
40
+
41
+ private fun notification(title: String): Notification =
42
+ NotificationCompat.Builder(service, DefaultMediaNotificationProvider.DEFAULT_CHANNEL_ID)
43
+ .setContentTitle(title)
44
+ .build()
45
+
46
+ @Test
47
+ fun `a cold search goes foreground before the search runs`() {
48
+ var foregroundIdDuringSearch: Int? = null
49
+
50
+ service.playInForeground(scope, startId = 1, hasMedia = { false }) {
51
+ foregroundIdDuringSearch = shadowOf(service).lastForegroundNotificationId
52
+ true
53
+ }
54
+
55
+ // Media3's id, so its own notification replaces the placeholder once playback starts.
56
+ assertEquals(mediaNotificationId, foregroundIdDuringSearch)
57
+ assertFalse(shadowOf(service).isForegroundStopped)
58
+ assertEquals(NEVER_STOPPED, shadowOf(service).stopSelfId)
59
+ }
60
+
61
+ @Test
62
+ fun `a cold search that finds nothing stops the service`() {
63
+ service.playInForeground(scope, startId = 7, hasMedia = { false }) { false }
64
+
65
+ assertTrue(shadowOf(service).isForegroundStopped)
66
+ assertTrue(shadowOf(service).notificationShouldRemoved)
67
+ assertEquals(7, shadowOf(service).stopSelfId)
68
+ }
69
+
70
+ @Test
71
+ fun `a search that finds nothing leaves the service running while the player has media`() {
72
+ service.playInForeground(scope, startId = 2, hasMedia = { true }) { false }
73
+
74
+ assertTrue(shadowOf(service).isForegroundStopped)
75
+ assertEquals(NEVER_STOPPED, shadowOf(service).stopSelfId)
76
+ }
77
+
78
+ @Test
79
+ fun `a search while Media3's notification shows holds that notification and leaves it to Media3`() {
80
+ val media = notification("Now playing")
81
+ service.getSystemService(NotificationManager::class.java).notify(mediaNotificationId, media)
82
+
83
+ service.playInForeground(scope, startId = 3, hasMedia = { true }) {
84
+ assertEquals(
85
+ "Now playing",
86
+ shadowOf(service).lastForegroundNotification.extras.getString(Notification.EXTRA_TITLE),
87
+ )
88
+ false
89
+ }
90
+
91
+ assertFalse(shadowOf(service).isForegroundStopped)
92
+ }
93
+
94
+ @Test
95
+ fun `a release while Media3's notification is in the foreground leaves it there`() {
96
+ val media = notification("Now playing")
97
+ ServiceCompat.startForeground(
98
+ service,
99
+ mediaNotificationId,
100
+ media,
101
+ ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK,
102
+ )
103
+ service.getSystemService(NotificationManager::class.java).notify(mediaNotificationId, media)
104
+
105
+ service.releasePlaceholder()
106
+
107
+ assertFalse(shadowOf(service).isForegroundStopped)
108
+ }
109
+
110
+ @Test
111
+ fun `the foreground start keys are the ones MediaButtonReceiver starts the service for`() {
112
+ fun press(keyCode: Int) =
113
+ Intent(Intent.ACTION_MEDIA_BUTTON)
114
+ .putExtra(Intent.EXTRA_KEY_EVENT, KeyEvent(KeyEvent.ACTION_DOWN, keyCode))
115
+
116
+ assertTrue(press(KeyEvent.KEYCODE_MEDIA_PLAY).isForegroundStartKey())
117
+ assertTrue(press(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE).isForegroundStartKey())
118
+ assertTrue(press(KeyEvent.KEYCODE_HEADSETHOOK).isForegroundStartKey())
119
+ assertFalse(press(KeyEvent.KEYCODE_MEDIA_PAUSE).isForegroundStartKey())
120
+ assertFalse(press(KeyEvent.KEYCODE_MEDIA_NEXT).isForegroundStartKey())
121
+ assertFalse(Intent(Intent.ACTION_MEDIA_BUTTON).isForegroundStartKey())
122
+ }
123
+
124
+ @Test
125
+ @Config(sdk = [28])
126
+ fun `below API 29 a playing service holds Media3's notification again and keeps it`() {
127
+ val media = notification("Now playing")
128
+ ServiceCompat.startForeground(service, mediaNotificationId, media, 0)
129
+ service.getSystemService(NotificationManager::class.java).notify(mediaNotificationId, media)
130
+
131
+ service.playInForeground(scope, startId = 5, hasMedia = { true }) { false }
132
+
133
+ assertEquals(
134
+ "Now playing",
135
+ shadowOf(service).lastForegroundNotification.extras.getString(Notification.EXTRA_TITLE),
136
+ )
137
+ assertFalse(shadowOf(service).isForegroundStopped)
138
+ }
139
+
140
+ @Test
141
+ @Config(sdk = [25])
142
+ fun `below API 26 nothing is held, as startForegroundService does not exist`() {
143
+ service.holdForeground()
144
+
145
+ assertEquals(0, shadowOf(service).lastForegroundNotificationId)
146
+ }
147
+
148
+ private companion object {
149
+ // ShadowService's stopSelfId before any stopSelf(startId); Android's start ids begin at 1.
150
+ const val NEVER_STOPPED = 0
151
+ }
152
+ }
@@ -20,6 +20,7 @@ class ServiceBindingTest {
20
20
 
21
21
  private val app = RuntimeEnvironment.getApplication()
22
22
  private val intent = Intent(app, Service::class.java)
23
+ private val unbindableIntent = Intent("unbindable").setPackage(app.packageName)
23
24
 
24
25
  private val connection =
25
26
  object : ServiceConnection {
@@ -65,7 +66,7 @@ class ServiceBindingTest {
65
66
  val binding = ServiceBinding(app)
66
67
  shadowOf(app).declareActionUnbindable("unbindable")
67
68
 
68
- assertFalse(binding.bind(Intent("unbindable"), connection))
69
+ assertFalse(binding.bind(unbindableIntent, connection))
69
70
 
70
71
  assertTrue(binding.isBound)
71
72
 
@@ -83,8 +84,8 @@ class ServiceBindingTest {
83
84
  val binding = ServiceBinding(app)
84
85
  shadowOf(app).declareActionUnbindable("unbindable")
85
86
 
86
- assertFalse(binding.bind(Intent("unbindable"), connection))
87
- assertFalse(binding.bind(Intent("unbindable"), connection))
87
+ assertFalse(binding.bind(unbindableIntent, connection))
88
+ assertFalse(binding.bind(unbindableIntent, connection))
88
89
  }
89
90
 
90
91
  @Test
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-audio-browser",
3
- "version": "0.2.0-next.35",
3
+ "version": "0.2.0-next.37",
4
4
  "description": "react-native-audio-browser is a react native package built with Nitro",
5
5
  "keywords": [
6
6
  "react-native",