react-native-audio-browser 1.0.0-next.4 → 1.0.0-next.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/android/src/cast/java/com/audiobrowser/cast/CastSupport.kt +75 -10
  2. package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +41 -6
  3. package/android/src/main/java/com/audiobrowser/browser/BrowseArtworkRegistry.kt +25 -9
  4. package/android/src/main/java/com/audiobrowser/browser/BrowserManager.kt +210 -125
  5. package/android/src/main/java/com/audiobrowser/browser/FavoriteChange.kt +61 -0
  6. package/android/src/main/java/com/audiobrowser/http/HttpClient.kt +2 -59
  7. package/android/src/main/java/com/audiobrowser/http/RequestConfigBuilder.kt +3 -3
  8. package/android/src/main/java/com/audiobrowser/model/PlayerUpdateOptions.kt +2 -0
  9. package/android/src/main/java/com/audiobrowser/player/CapabilityControls.kt +2 -0
  10. package/android/src/main/java/com/audiobrowser/player/InterceptingPlayer.kt +14 -1
  11. package/android/src/main/java/com/audiobrowser/player/MediaSessionCallback.kt +201 -107
  12. package/android/src/main/java/com/audiobrowser/player/MediaSessionCommandManager.kt +2 -0
  13. package/android/src/main/java/com/audiobrowser/player/PlaybackStateMachine.kt +55 -26
  14. package/android/src/main/java/com/audiobrowser/player/Player.kt +168 -51
  15. package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +19 -8
  16. package/android/src/main/java/com/audiobrowser/player/RetryLoop.kt +1 -1
  17. package/android/src/main/java/com/audiobrowser/remote/RemoteSwitchingPlayer.kt +52 -7
  18. package/android/src/main/java/com/audiobrowser/util/ArtworkContentProvider.kt +2 -3
  19. package/android/src/main/java/com/audiobrowser/util/ArtworkRoutes.kt +5 -5
  20. package/android/src/main/java/com/audiobrowser/util/ArtworkUris.kt +5 -0
  21. package/android/src/main/java/com/audiobrowser/util/AwaitCancellable.kt +35 -11
  22. package/android/src/main/java/com/audiobrowser/util/BrowserPathHelper.kt +11 -0
  23. package/android/src/main/java/com/audiobrowser/util/TrackFactory.kt +10 -7
  24. package/android/src/main/res/values/strings.xml +5 -2
  25. package/android/src/test/java/androidx/media3/session/SessionViews.kt +15 -0
  26. package/android/src/test/java/com/audiobrowser/ConfigurationStartTest.kt +72 -0
  27. package/android/src/test/java/com/audiobrowser/ContentRefreshNavigationErrorTest.kt +1 -0
  28. package/android/src/test/java/com/audiobrowser/NavigateTrackTest.kt +1 -0
  29. package/android/src/test/java/com/audiobrowser/ResolveFormattedErrorTest.kt +1 -0
  30. package/android/src/test/java/com/audiobrowser/TestFixtures.kt +9 -6
  31. package/android/src/test/java/com/audiobrowser/browser/BrowseArtworkRegistryTest.kt +19 -0
  32. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerFavoritesTest.kt +58 -0
  33. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerInvalidationTest.kt +15 -0
  34. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerSearchFailureTest.kt +168 -0
  35. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerTest.kt +32 -0
  36. package/android/src/test/java/com/audiobrowser/browser/FavoriteChangeTest.kt +106 -0
  37. package/android/src/test/java/com/audiobrowser/http/RequestConfigBuilderTest.kt +43 -18
  38. package/android/src/test/java/com/audiobrowser/player/CapabilityControlsTest.kt +1 -0
  39. package/android/src/test/java/com/audiobrowser/player/FavoriteCapabilityTest.kt +8 -19
  40. package/android/src/test/java/com/audiobrowser/player/FavoriteRestampTest.kt +117 -0
  41. package/android/src/test/java/com/audiobrowser/player/HandleTrackLoadSeekTest.kt +1 -0
  42. package/android/src/test/java/com/audiobrowser/player/LiveSeekCommandTest.kt +1 -0
  43. package/android/src/test/java/com/audiobrowser/player/PlaybackStateMachineTest.kt +58 -1
  44. package/android/src/test/java/com/audiobrowser/player/PlayerCastTest.kt +40 -1
  45. package/android/src/test/java/com/audiobrowser/player/PlayerRetryTest.kt +115 -2
  46. package/android/src/test/java/com/audiobrowser/player/QueueEventOnSessionPlayersTest.kt +40 -0
  47. package/android/src/test/java/com/audiobrowser/player/QueueEventTest.kt +153 -0
  48. package/android/src/test/java/com/audiobrowser/player/QueueItemPickTest.kt +130 -0
  49. package/android/src/test/java/com/audiobrowser/player/SessionBrowserNeverConfiguredTest.kt +98 -0
  50. package/android/src/test/java/com/audiobrowser/player/SessionUncachedIdTest.kt +396 -0
  51. package/android/src/test/java/com/audiobrowser/player/SessionViewTest.kt +6 -2
  52. package/android/src/test/java/com/audiobrowser/player/SessionVoiceSearchTest.kt +116 -14
  53. package/android/src/test/java/com/audiobrowser/player/StandardSkipTest.kt +26 -0
  54. package/android/src/test/java/com/audiobrowser/player/TabsChangedTest.kt +81 -0
  55. package/android/src/test/java/com/audiobrowser/remote/FakeRemote.kt +12 -1
  56. package/android/src/test/java/com/audiobrowser/remote/RemoteSwitchingPlayerTest.kt +241 -0
  57. package/android/src/test/java/com/audiobrowser/util/ArtworkContentProviderTest.kt +11 -0
  58. package/android/src/test/java/com/audiobrowser/util/ArtworkRoutesTest.kt +25 -0
  59. package/android/src/test/java/com/audiobrowser/util/AwaitCancellableTest.kt +43 -2
  60. package/android/src/test/java/com/audiobrowser/util/CoilArtworkLoaderTest.kt +38 -0
  61. package/android/src/test/java/com/audiobrowser/util/TrackFactoryRatingTest.kt +11 -0
  62. package/android/src/testCast/java/com/audiobrowser/cast/SdkCastRemoteTest.kt +187 -2
  63. package/ios/AVPlayerEngine.swift +2 -2
  64. package/ios/Browser/BrowserPathHelper.swift +11 -9
  65. package/ios/Browser/PageResolver.swift +1 -1
  66. package/ios/CarPlay/CarPlayListItemFactory.swift +2 -2
  67. package/ios/CarPlay/CarPlayNowPlayingManager.swift +64 -31
  68. package/ios/CarPlay/NowPlayingButtonRules.swift +26 -0
  69. package/ios/CarPlay/SectionPresentation.swift +7 -0
  70. package/ios/Extension/Promise+AwaitCallback.swift +13 -4
  71. package/ios/HybridAudioBrowser+Player.swift +3 -2
  72. package/ios/HybridAudioBrowser.swift +1 -1
  73. package/ios/Model/NitroTypeStubs.swift +15 -0
  74. package/ios/Model/PlayerUpdateOptions.swift +2 -1
  75. package/ios/PlaybackEvent.swift +20 -0
  76. package/ios/Player/Player.swift +17 -3
  77. package/ios/Player/QueueManager.swift +23 -41
  78. package/ios/Tests/AwaitCallbackTests.swift +8 -0
  79. package/ios/Tests/BrowserPathHelperTests.swift +18 -0
  80. package/ios/Tests/CapabilityRemoteCommandTests.swift +4 -0
  81. package/ios/Tests/DataURLDecodingTests.swift +25 -0
  82. package/ios/Tests/GenerationMemoTests.swift +136 -0
  83. package/ios/Tests/JSCallbackErrorTests.swift +33 -0
  84. package/ios/Tests/NowPlayingButtonRulesTests.swift +35 -0
  85. package/ios/Tests/PlaybackStateMachineTests.swift +15 -0
  86. package/ios/Tests/PlayerPolicyTests.swift +51 -28
  87. package/ios/Tests/PlayerProgressTests.swift +0 -2
  88. package/ios/Tests/PlayerTests.swift +54 -0
  89. package/ios/Tests/QueueManagerTests.swift +111 -78
  90. package/ios/Tests/RequestLayerTests.swift +11 -0
  91. package/ios/Tests/RoutePickerSourceFrameTests.swift +30 -0
  92. package/ios/Tests/RoutePickerSourceLifetimeTests.swift +79 -0
  93. package/ios/Tests/SectionPresentationTests.swift +13 -0
  94. package/ios/Tests/Support/TestTypes.swift +23 -1
  95. package/ios/Util/ArtworkImageFetcher.swift +40 -16
  96. package/ios/Util/AwaitCallback.swift +16 -10
  97. package/ios/Util/GenerationMemo.swift +81 -17
  98. package/ios/Util/JSCallbackError.swift +23 -0
  99. package/ios/Util/OutputPicker.swift +25 -5
  100. package/ios/Util/RoutePickerSourceFrame.swift +17 -0
  101. package/ios/Util/RoutePickerSourceLifetime.swift +34 -0
  102. package/lib/commonjs/features/browser-config.js +3 -2
  103. package/lib/commonjs/features/browser-config.js.map +1 -1
  104. package/lib/commonjs/features/browser.js +7 -8
  105. package/lib/commonjs/features/browser.js.map +1 -1
  106. package/lib/commonjs/features/output.js +7 -3
  107. package/lib/commonjs/features/output.js.map +1 -1
  108. package/lib/commonjs/features/player/options.js.map +1 -1
  109. package/lib/commonjs/web/NativeAudioBrowser.js +43 -2
  110. package/lib/commonjs/web/NativeAudioBrowser.js.map +1 -1
  111. package/lib/commonjs/web/browser/BrowserManager.js +37 -65
  112. package/lib/commonjs/web/browser/BrowserManager.js.map +1 -1
  113. package/lib/commonjs/web/browser/SearchManager.js +1 -4
  114. package/lib/commonjs/web/browser/SearchManager.js.map +1 -1
  115. package/lib/commonjs/web/http/RequestConfigBuilder.js +53 -55
  116. package/lib/commonjs/web/http/RequestConfigBuilder.js.map +1 -1
  117. package/lib/commonjs/web/player/NowPlayingManager.js +3 -22
  118. package/lib/commonjs/web/player/NowPlayingManager.js.map +1 -1
  119. package/lib/commonjs/web/util/BrowserPathHelper.js +5 -7
  120. package/lib/commonjs/web/util/BrowserPathHelper.js.map +1 -1
  121. package/lib/commonjs/web/util/GenerationMemo.js +92 -0
  122. package/lib/commonjs/web/util/GenerationMemo.js.map +1 -0
  123. package/lib/module/features/browser-config.js +3 -2
  124. package/lib/module/features/browser-config.js.map +1 -1
  125. package/lib/module/features/browser.js +7 -8
  126. package/lib/module/features/browser.js.map +1 -1
  127. package/lib/module/features/output.js +7 -3
  128. package/lib/module/features/output.js.map +1 -1
  129. package/lib/module/features/player/options.js.map +1 -1
  130. package/lib/module/web/NativeAudioBrowser.js +43 -2
  131. package/lib/module/web/NativeAudioBrowser.js.map +1 -1
  132. package/lib/module/web/browser/BrowserManager.js +37 -66
  133. package/lib/module/web/browser/BrowserManager.js.map +1 -1
  134. package/lib/module/web/browser/SearchManager.js +1 -5
  135. package/lib/module/web/browser/SearchManager.js.map +1 -1
  136. package/lib/module/web/http/RequestConfigBuilder.js +53 -55
  137. package/lib/module/web/http/RequestConfigBuilder.js.map +1 -1
  138. package/lib/module/web/player/NowPlayingManager.js +3 -22
  139. package/lib/module/web/player/NowPlayingManager.js.map +1 -1
  140. package/lib/module/web/util/BrowserPathHelper.js +5 -7
  141. package/lib/module/web/util/BrowserPathHelper.js.map +1 -1
  142. package/lib/module/web/util/GenerationMemo.js +87 -0
  143. package/lib/module/web/util/GenerationMemo.js.map +1 -0
  144. package/lib/typescript/src/features/browser-config.d.ts.map +1 -1
  145. package/lib/typescript/src/features/browser.d.ts +7 -8
  146. package/lib/typescript/src/features/browser.d.ts.map +1 -1
  147. package/lib/typescript/src/features/output.d.ts +8 -4
  148. package/lib/typescript/src/features/output.d.ts.map +1 -1
  149. package/lib/typescript/src/features/player/options.d.ts +19 -1
  150. package/lib/typescript/src/features/player/options.d.ts.map +1 -1
  151. package/lib/typescript/src/specs/audio-browser.nitro.d.ts +11 -0
  152. package/lib/typescript/src/specs/audio-browser.nitro.d.ts.map +1 -1
  153. package/lib/typescript/src/types/browser-native.d.ts +2 -1
  154. package/lib/typescript/src/types/browser-native.d.ts.map +1 -1
  155. package/lib/typescript/src/types/browser.d.ts +55 -8
  156. package/lib/typescript/src/types/browser.d.ts.map +1 -1
  157. package/nitrogen/generated/android/AudioBrowserOnLoad.cpp +2 -0
  158. package/nitrogen/generated/android/c++/JArtworkRequestConfig.hpp +3 -0
  159. package/nitrogen/generated/android/c++/JFindTrackParams.hpp +57 -0
  160. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_RequestConfig___MediaTransformParams.hpp +13 -1
  161. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_RequestConfig___RequestConfig_std__optional_std__unordered_map_std__string__std__string__.hpp +13 -1
  162. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_RequestConfig___Track.hpp +13 -1
  163. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__optional_FormattedNavigationError____FormatNavigationErrorParams.hpp +13 -1
  164. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__optional_NowPlayingUpdate____FormatNowPlayingParams.hpp +13 -1
  165. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__optional_std__string____Track.hpp +13 -1
  166. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_GateDecision_____NativeGateRequest.hpp +23 -2
  167. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_RequestConfig_____MediaTransformParams.hpp +23 -2
  168. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_RequestConfig_____RequestConfig_std__optional_std__unordered_map_std__string__std__string__.hpp +23 -2
  169. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_RequestConfig_____Track.hpp +23 -2
  170. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_TransformableRequestConfig____.hpp +23 -2
  171. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__optional_Track______FindTrackParams.hpp +171 -0
  172. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__vector_Track______SearchParams.hpp +23 -2
  173. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_void_____TrackLoadEvent.hpp +23 -2
  174. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__string__.hpp +13 -1
  175. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__variant_ResolvedTrack__BrowseError__std__shared_ptr_Promise_std__variant_ResolvedTrack__BrowseError_______BrowserSourceCallbackParam.hpp +13 -1
  176. package/nitrogen/generated/android/c++/JHybridAudioBrowserSpec.cpp +15 -3
  177. package/nitrogen/generated/android/c++/JHybridAudioBrowserSpec.hpp +1 -1
  178. package/nitrogen/generated/android/c++/JMediaRequestConfig.hpp +3 -0
  179. package/nitrogen/generated/android/c++/JNativeBrowserConfiguration.hpp +20 -2
  180. package/nitrogen/generated/android/c++/JNativeRouteEntry.hpp +3 -0
  181. package/nitrogen/generated/android/c++/JNativeSetupPlayerOptions.hpp +3 -0
  182. package/nitrogen/generated/android/c++/JOutputPickerAnchor.hpp +69 -0
  183. package/nitrogen/generated/android/c++/JPlayerCapabilities.hpp +5 -1
  184. package/nitrogen/generated/android/c++/JTransformableRequestConfig.hpp +3 -0
  185. package/nitrogen/generated/android/c++/JVariant_ResolvedTrack_BrowseError_Promise_BrowseResult_.hpp +13 -1
  186. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/FindTrackParams.kt +51 -0
  187. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__optional_Track______FindTrackParams.kt +78 -0
  188. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/HybridAudioBrowserSpec.kt +1 -1
  189. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/NativeBrowserConfiguration.kt +11 -6
  190. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/OutputPickerAnchor.kt +66 -0
  191. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/PlayerCapabilities.kt +7 -2
  192. package/nitrogen/generated/ios/AudioBrowser-Swift-Cxx-Bridge.cpp +35 -1
  193. package/nitrogen/generated/ios/AudioBrowser-Swift-Cxx-Bridge.hpp +144 -15
  194. package/nitrogen/generated/ios/AudioBrowser-Swift-Cxx-Umbrella.hpp +8 -0
  195. package/nitrogen/generated/ios/c++/HybridAudioBrowserSpecSwift.hpp +8 -2
  196. package/nitrogen/generated/ios/swift/FindTrackParams.swift +29 -0
  197. package/nitrogen/generated/ios/swift/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__optional_Track______FindTrackParams.swift +67 -0
  198. package/nitrogen/generated/ios/swift/Func_void_std__optional_Track_.swift +46 -0
  199. package/nitrogen/generated/ios/swift/Func_void_std__shared_ptr_Promise_std__optional_Track___.swift +66 -0
  200. package/nitrogen/generated/ios/swift/HybridAudioBrowserSpec.swift +1 -1
  201. package/nitrogen/generated/ios/swift/HybridAudioBrowserSpec_cxx.swift +2 -2
  202. package/nitrogen/generated/ios/swift/NativeBrowserConfiguration.swift +48 -1
  203. package/nitrogen/generated/ios/swift/OutputPickerAnchor.swift +44 -0
  204. package/nitrogen/generated/ios/swift/PlayerCapabilities.swift +19 -1
  205. package/nitrogen/generated/shared/c++/FindTrackParams.hpp +83 -0
  206. package/nitrogen/generated/shared/c++/HybridAudioBrowserSpec.hpp +4 -1
  207. package/nitrogen/generated/shared/c++/NativeBrowserConfiguration.hpp +10 -3
  208. package/nitrogen/generated/shared/c++/OutputPickerAnchor.hpp +95 -0
  209. package/nitrogen/generated/shared/c++/PlayerCapabilities.hpp +5 -1
  210. package/package.json +1 -1
  211. package/src/codegen-js-error-message.test.ts +78 -0
  212. package/src/features/browser-config.test.ts +7 -0
  213. package/src/features/browser-config.ts +3 -2
  214. package/src/features/browser.ts +7 -8
  215. package/src/features/output.ts +13 -5
  216. package/src/features/player/options.ts +19 -1
  217. package/src/specs/audio-browser.nitro.ts +16 -3
  218. package/src/types/browser-native.ts +4 -1
  219. package/src/types/browser.ts +60 -8
  220. package/src/web/NativeAudioBrowser.ts +43 -3
  221. package/src/web/__tests__/nowPlayingArtwork.test.ts +191 -0
  222. package/src/web/browser/BrowserManager.ts +50 -79
  223. package/src/web/browser/SearchManager.ts +1 -8
  224. package/src/web/browser/__tests__/artwork-resolution.test.ts +33 -0
  225. package/src/web/browser/__tests__/layer-resolver.test.ts +47 -1
  226. package/src/web/http/RequestConfigBuilder.test.ts +151 -1
  227. package/src/web/http/RequestConfigBuilder.ts +72 -57
  228. package/src/web/player/NowPlayingManager.test.ts +29 -0
  229. package/src/web/player/NowPlayingManager.ts +4 -27
  230. package/src/web/util/BrowserPathHelper.test.ts +23 -0
  231. package/src/web/util/BrowserPathHelper.ts +6 -7
  232. package/src/web/util/GenerationMemo.test.ts +148 -0
  233. package/src/web/util/GenerationMemo.ts +103 -0
  234. package/website/guide/audio-output.md +34 -7
  235. package/website/guide/browser.md +21 -0
  236. package/website/guide/carplay.md +1 -1
  237. package/website/guide/configuration.md +10 -9
  238. package/website/guide/gate.md +1 -1
  239. package/website/guide/remote-controls.md +35 -0
@@ -13,6 +13,7 @@ import com.audiobrowser.util.SearchParamsFactory
13
13
  import com.audiobrowser.util.TrackFactory
14
14
  import com.audiobrowser.util.artworkOf
15
15
  import com.audiobrowser.util.awaitCancellable
16
+ import com.audiobrowser.util.awaitJsPromise
16
17
  import com.audiobrowser.util.awaitNested
17
18
  import com.audiobrowser.util.awaitOrTimeout
18
19
  import com.margelo.nitro.audiobrowser.ArtworkRequestConfig
@@ -30,8 +31,14 @@ import com.margelo.nitro.audiobrowser.StyleDisplay
30
31
  import com.margelo.nitro.audiobrowser.Track
31
32
  import com.margelo.nitro.audiobrowser.TransformableRequestConfig
32
33
  import com.margelo.nitro.core.Promise
34
+ import java.io.IOException
35
+ import java.util.concurrent.ConcurrentHashMap
33
36
  import kotlinx.coroutines.CancellationException
37
+ import kotlinx.coroutines.CoroutineScope
38
+ import kotlinx.coroutines.CoroutineStart
39
+ import kotlinx.coroutines.Deferred
34
40
  import kotlinx.coroutines.Dispatchers
41
+ import kotlinx.coroutines.SupervisorJob
35
42
  import kotlinx.coroutines.async
36
43
  import kotlinx.coroutines.awaitAll
37
44
  import kotlinx.coroutines.coroutineScope
@@ -152,10 +159,19 @@ class BrowserManager {
152
159
  */
153
160
  val artworkResolutions = ArtworkResolutionRegistry()
154
161
 
155
- /** Sets the favorited track identities (id when non-blank, else src). */
156
- fun setFavorites(favorites: List<String>) {
157
- favoriteIds = favorites.toSet()
162
+ /**
163
+ * Sets the favorited track identities (id when non-blank, else src) and restamps the content on
164
+ * screen, the content cache and the track cache. Main thread only.
165
+ *
166
+ * @return the change, for the queue to follow; null when the set already held these identities
167
+ */
168
+ fun setFavorites(favorites: List<String>): FavoriteChange? {
169
+ val replaced = favorites.toSet()
170
+ val change = FavoriteChange.between(favoriteIds, replaced)
171
+ favoriteIds = replaced
158
172
  Timber.d("Set ${favoriteIds.size} favorite IDs")
173
+ change?.let(::restampFavorites)
174
+ return change
159
175
  }
160
176
 
161
177
  fun setFavoriteEnabled(enabled: Boolean) {
@@ -170,6 +186,21 @@ class BrowserManager {
170
186
  favoriteIds - identity
171
187
  }
172
188
  Timber.d("Updated favorite for '$identity' to $favorited (total: ${favoriteIds.size})")
189
+ restampFavorites(FavoriteChange.toggle(identity, favorited))
190
+ }
191
+
192
+ private fun restampFavorites(change: FavoriteChange) {
193
+ content?.let { change.restamp(it) }?.let { content = it }
194
+ // A cache hit re-keys the track cache from the cached page, so the page must follow too.
195
+ synchronized(cacheLock) {
196
+ contentCache.snapshot().forEach { (path, page) ->
197
+ change.restamp(page) { change.restampStamped(it) }?.let { contentCache.put(path, it) }
198
+ }
199
+ }
200
+ // Search results reach the track cache without a page in the content cache.
201
+ change.identities.forEach { identity ->
202
+ trackCache.get(identity)?.let { change.restampStamped(it) }?.let { cacheTrack(it) }
203
+ }
173
204
  }
174
205
 
175
206
  /**
@@ -269,59 +300,115 @@ class BrowserManager {
269
300
  return getCachedTrack(mediaId)?.path?.takeIf { BrowserPathHelper.isContextual(it) }
270
301
  }
271
302
 
303
+ /**
304
+ * The track for [id]: the cached one, else the one `findTrack` answers (see [findUncachedTrack]).
305
+ */
306
+ suspend fun trackFor(id: String): Track? = getCachedTrack(id) ?: findUncachedTrack(id)
307
+
308
+ /**
309
+ * Whether [id] is `findTrack`'s alone to answer: a bare id while `findTrack` is set. Such an id
310
+ * is never browsed as a path.
311
+ */
312
+ fun answersOnlyByFindTrack(id: String): Boolean =
313
+ config.findTrack != null && BrowserPathHelper.isBareId(id)
314
+
315
+ private val findScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
316
+ private val findsInFlight = ConcurrentHashMap<String, Deferred<Track?>>()
317
+
318
+ /**
319
+ * The playable track the consumer's `findTrack` answers for [id], carrying [id] as its own, and
320
+ * cached under [id] alone. Concurrent calls for one id share one `findTrack` call, which a
321
+ * caller's cancellation leaves running for the others. Null when [id] is a path or http(s) URL,
322
+ * or when `findTrack` is unset, answers nothing, answers a track without `src`, throws, or
323
+ * outruns [FALLBACK_TIMEOUT].
324
+ */
325
+ suspend fun findUncachedTrack(id: String): Track? {
326
+ if (!BrowserPathHelper.isBareId(id)) return null
327
+ val findTrack = config.findTrack ?: return null
328
+ val found =
329
+ findsInFlight
330
+ .computeIfAbsent(id) {
331
+ findScope
332
+ .async(start = CoroutineStart.LAZY) { find(findTrack, id) }
333
+ .also { lookup -> lookup.invokeOnCompletion { findsInFlight.remove(id, lookup) } }
334
+ }
335
+ .await()
336
+ return found?.let(::hydrateFavorite)
337
+ }
338
+
339
+ private suspend fun find(findTrack: suspend (String) -> Track?, id: String): Track? {
340
+ val track =
341
+ try {
342
+ findTrack(id)
343
+ } catch (e: CancellationException) {
344
+ throw e
345
+ } catch (e: Exception) {
346
+ Timber.e(e, "findTrack failed for id='$id'")
347
+ return null
348
+ }
349
+ if (track?.src == null) {
350
+ Timber.w("findTrack found no playable track for id='$id'")
351
+ return null
352
+ }
353
+ // A controller matches its now-playing row by the id it sent. Not under its path or src: a
354
+ // found track must not answer for a browse path it names.
355
+ return track.copy(id = id).also { trackCache.put(id, it) }
356
+ }
357
+
272
358
  /**
273
359
  * A cache miss is reachable: a controller can replay a mediaId this process never browsed (a
274
- * search result after process death). When the mediaId is a playable URL, or the item's
275
- * requestMetadata carries the playable uri (stamped by TrackFactory), it builds a minimal track
276
- * from the item's metadata.
360
+ * search result or the last track after process death). When the mediaId is a playable URL, or
361
+ * the item's requestMetadata carries the playable uri (stamped by TrackFactory), it builds a
362
+ * minimal track from the item's metadata on a cache miss; otherwise it asks [trackFor].
277
363
  *
278
- * @throws IllegalStateException when the mediaId is not cached and no playable URL is available
364
+ * @throws IllegalStateException when the mediaId is neither cached, a playable URL, nor found
279
365
  */
280
- private fun resolveMediaItemToTrack(mediaItem: MediaItem): Track {
366
+ private suspend fun resolveMediaItemToTrack(mediaItem: MediaItem): Track {
281
367
  val mediaId = mediaItem.mediaId
282
368
 
283
- getCachedTrack(mediaId)?.let { cachedTrack ->
284
- Timber.d("Resolved mediaId='$mediaId' from cache: '${cachedTrack.title}'")
285
- return cachedTrack
286
- }
287
-
288
369
  val fallbackSrc =
289
- if (mediaId.startsWith("http://") || mediaId.startsWith("https://")) {
370
+ if (BrowserPathHelper.isHttpUrl(mediaId)) {
290
371
  mediaId
291
372
  } else {
292
373
  mediaItem.requestMetadata.mediaUri?.toString()
293
374
  }
294
- if (fallbackSrc != null) {
295
- Timber.w("Cache MISS for mediaId='$mediaId' - building minimal track from media item")
296
- val metadata = mediaItem.mediaMetadata
297
- return hydrateFavorite(
298
- Track(
299
- // A mediaId distinct from the playable uri is the stable id; keeping it lets the car's
300
- // now-playing row match.
301
- id = mediaId.takeIf { it != fallbackSrc },
302
- path = null,
303
- src = fallbackSrc,
304
- artwork = artworkOf(metadata.artworkUri?.toString()),
305
- artworkSource = null,
306
- request = null,
307
- title = metadata.title?.toString() ?: mediaId,
308
- subtitle = metadata.artist?.toString(),
309
- artist = null,
310
- albumPath = null,
311
- album = metadata.albumTitle?.toString(),
312
- description = metadata.description?.toString(),
313
- genre = metadata.genre?.toString(),
314
- duration = null,
315
- style = null,
316
- disabled = null,
317
- favorited = null,
318
- live = null,
319
- icyCharset = null,
320
- )
321
- )
375
+ if (fallbackSrc == null) {
376
+ return trackFor(mediaId)
377
+ ?: throw IllegalStateException("MediaItem neither cached nor found: $mediaId")
322
378
  }
323
379
 
324
- throw IllegalStateException("MediaItem not found in cache: $mediaId")
380
+ getCachedTrack(mediaId)?.let { cachedTrack ->
381
+ Timber.d("Resolved mediaId='$mediaId' from cache: '${cachedTrack.title}'")
382
+ return cachedTrack
383
+ }
384
+
385
+ Timber.w("Cache MISS for mediaId='$mediaId' - building minimal track from media item")
386
+ val metadata = mediaItem.mediaMetadata
387
+ return hydrateFavorite(
388
+ Track(
389
+ // A mediaId distinct from the playable uri is the stable id; keeping it lets the car's
390
+ // now-playing row match.
391
+ id = mediaId.takeIf { it != fallbackSrc },
392
+ path = null,
393
+ src = fallbackSrc,
394
+ artwork = artworkOf(metadata.artworkUri?.toString()),
395
+ artworkSource = null,
396
+ request = null,
397
+ title = metadata.title?.toString() ?: mediaId,
398
+ subtitle = metadata.artist?.toString(),
399
+ artist = null,
400
+ albumPath = null,
401
+ album = metadata.albumTitle?.toString(),
402
+ description = metadata.description?.toString(),
403
+ genre = metadata.genre?.toString(),
404
+ duration = null,
405
+ style = null,
406
+ disabled = null,
407
+ favorited = null,
408
+ live = null,
409
+ icyCharset = null,
410
+ )
411
+ )
325
412
  }
326
413
 
327
414
  /**
@@ -331,7 +418,7 @@ class BrowserManager {
331
418
  * are dropped and the start index shifts to match.
332
419
  *
333
420
  * @throws IllegalStateException when the start track is disabled, every track is disabled, or a
334
- * mediaId is neither cached nor a playable URL
421
+ * mediaId is neither cached, a playable URL, nor found by `findTrack`
335
422
  */
336
423
  suspend fun resolveMediaItemsForPlayback(
337
424
  mediaItems: List<MediaItem>,
@@ -345,9 +432,10 @@ class BrowserManager {
345
432
  if (searchQuery != null) {
346
433
  Timber.d("Handling search playback request for query: $searchQuery")
347
434
 
348
- val searchResults = search(searchQuery)
349
435
  val searchTracks =
350
- searchResults.flattenedChildren?.filterNot { it.disabled == true }?.toTypedArray()
436
+ (getCachedSearchResults(searchQuery) ?: searchedOrNull(searchQuery))
437
+ ?.filterNot { it.disabled == true }
438
+ ?.toTypedArray()
351
439
 
352
440
  if (searchTracks != null && searchTracks.isNotEmpty()) {
353
441
  val mediaId = mediaItem.mediaId
@@ -402,7 +490,7 @@ class BrowserManager {
402
490
 
403
491
  val resolvedTracks = mediaItems.map { resolveMediaItemToTrack(it) }
404
492
 
405
- // Refusal fails the future: Media3 surfaces an error to the controller and current playback
493
+ // Refusal fails the future, which the session reports to the controller, and current playback
406
494
  // stays untouched, where an empty item list would clear the timeline. Android Auto and
407
495
  // Assistant request playback through Media3's legacy path, which passes C.INDEX_UNSET for
408
496
  // "the first item": normalize before the guard, or the refusal misses the cars.
@@ -740,6 +828,15 @@ class BrowserManager {
740
828
  }
741
829
  }
742
830
 
831
+ /** A fresh search's results, or null when it fails. */
832
+ private suspend fun searchedOrNull(query: String): Array<Track>? =
833
+ try {
834
+ search(query).flattenedChildren?.toTypedArray()
835
+ } catch (e: Exception) {
836
+ if (e is CancellationException) throw e
837
+ null
838
+ }
839
+
743
840
  /** Returns the results of the most recent search when [query] matches it, else null. */
744
841
  fun getCachedSearchResults(query: String): Array<Track>? {
745
842
  val (cachedQuery, cachedResults) = lastSearch ?: return null
@@ -755,7 +852,7 @@ class BrowserManager {
755
852
  * Returns the playable results, or null when there are none. A browsable first result plays its
756
853
  * children instead.
757
854
  *
758
- * @throws Exception when the search callback fails; a failed API search returns null
855
+ * @throws Exception when the search fails
759
856
  */
760
857
  suspend fun searchPlayable(params: SearchParams): Array<Track>? {
761
858
  val searchResults = search(params)
@@ -791,7 +888,7 @@ class BrowserManager {
791
888
  /**
792
889
  * Runs a fresh search and keeps its results for [getCachedSearchResults].
793
890
  *
794
- * @throws Exception when the search callback fails; a failed API search yields no results
891
+ * @throws Exception when the search fails
795
892
  */
796
893
  suspend fun search(params: SearchParams): ResolvedTrack {
797
894
  Timber.d("Executing fresh search for: ${params.query} (mode=${params.mode})")
@@ -965,7 +1062,7 @@ class BrowserManager {
965
1062
  second = { browseError -> throw CallbackException(browseError.error) },
966
1063
  third = { promise ->
967
1064
  promise
968
- .awaitCancellable()
1065
+ .awaitJsPromise()
969
1066
  .match(
970
1067
  first = { resolvedTrack -> resolvedTrack },
971
1068
  second = { browseError -> throw CallbackException(browseError.error) },
@@ -1130,39 +1227,14 @@ class BrowserManager {
1130
1227
  ensureLayersResolved()
1131
1228
  // apiConfig is null for the implicit default.
1132
1229
  val httpRequest = buildApiRequest(resolvedBrowseLayer, apiConfig, path, routeParams)
1133
- val response = httpClient.request(httpRequest)
1134
-
1135
- response.fold(
1136
- onSuccess = { httpResponse ->
1137
- if (httpResponse.isSuccessful) {
1138
- val jsonResolvedTrack =
1139
- try {
1140
- json.decodeFromString<JsonResolvedTrack>(httpResponse.body).also {
1141
- // A browse page needs its title (BrowserSource); the tabs page does not.
1142
- if (it.title == null && path != TABS_ROUTE_PATH) {
1143
- throw SerializationException("Field 'title' is required for a browse page")
1144
- }
1145
- }
1146
- } catch (e: Exception) {
1147
- throw HttpStatusException(
1148
- httpResponse.code,
1149
- "Server returned ${httpResponse.code} with a response that is not a page: ${e.message}",
1150
- e,
1151
- )
1152
- }
1153
- jsonResolvedTrack.toNitro(requestedPath = path)
1154
- } else {
1155
- Timber.w(
1156
- "HTTP request failed with status ${httpResponse.code} for ${httpRequest.url}: ${httpResponse.body}"
1157
- )
1158
- throw HttpStatusException(httpResponse.code, "Server returned ${httpResponse.code}")
1230
+ val jsonResolvedTrack =
1231
+ fetchJson<JsonResolvedTrack>(httpRequest, "a page") {
1232
+ // A browse page needs its title (BrowserSource); the tabs page does not.
1233
+ if (it.title == null && path != TABS_ROUTE_PATH) {
1234
+ throw SerializationException("Field 'title' is required for a browse page")
1159
1235
  }
1160
- },
1161
- onFailure = { exception ->
1162
- Timber.e(exception, "HTTP request failed")
1163
- throw NetworkException("Network request failed: ${exception.message}", exception)
1164
- },
1165
- )
1236
+ }
1237
+ jsonResolvedTrack.toNitro(requestedPath = path)
1166
1238
  }
1167
1239
  }
1168
1240
 
@@ -1171,52 +1243,64 @@ class BrowserManager {
1171
1243
  params: SearchParams,
1172
1244
  ): Array<Track> {
1173
1245
  return withContext(Dispatchers.IO) {
1174
- try {
1175
- val searchQueryParams = buildMap {
1176
- put("q", params.query)
1177
- params.mode?.let { put("mode", it.toString().lowercase()) }
1178
- if (params.reference == MediaReference.MY) put("reference", "my")
1179
- params.genre?.let { put("genre", it) }
1180
- params.artist?.let { put("artist", it) }
1181
- params.album?.let { put("album", it) }
1182
- params.title?.let { put("title", it) }
1183
- params.playlist?.let { put("playlist", it) }
1184
- }
1246
+ val searchQueryParams = buildMap {
1247
+ put("q", params.query)
1248
+ params.mode?.let { put("mode", it.toString().lowercase()) }
1249
+ if (params.reference == MediaReference.MY) put("reference", "my")
1250
+ params.genre?.let { put("genre", it) }
1251
+ params.artist?.let { put("artist", it) }
1252
+ params.album?.let { put("album", it) }
1253
+ params.title?.let { put("title", it) }
1254
+ params.playlist?.let { put("playlist", it) }
1255
+ }
1185
1256
 
1186
- // No browse layer and no route: search is its own kind.
1187
- val httpRequest =
1188
- buildApiRequest(
1189
- kindConfig = apiConfig,
1190
- routeConfig = null,
1191
- // A layer's static path never applies, so the search config's path seeds the base.
1192
- path = apiConfig.path,
1193
- params = emptyMap(),
1194
- initialQuery = searchQueryParams,
1195
- )
1196
- val response = httpClient.request(httpRequest)
1197
-
1198
- response.fold(
1199
- onSuccess = { httpResponse ->
1200
- if (httpResponse.isSuccessful) {
1201
- // A bare Track array, unlike browse's page object.
1202
- val jsonTracks = json.decodeFromString<List<JsonTrack>>(httpResponse.body)
1203
- jsonTracks.map { it.toNitro() }.toTypedArray()
1204
- } else {
1205
- Timber.w(
1206
- "Search HTTP request failed with status ${httpResponse.code}: ${httpResponse.body}"
1207
- )
1208
- emptyArray()
1209
- }
1210
- },
1211
- onFailure = { exception ->
1212
- Timber.e(exception, "Search HTTP request failed")
1213
- emptyArray()
1214
- },
1257
+ // No browse layer and no route: search is its own kind.
1258
+ val httpRequest =
1259
+ buildApiRequest(
1260
+ kindConfig = apiConfig,
1261
+ routeConfig = null,
1262
+ // A layer's static path never applies, so the search config's path seeds the base.
1263
+ path = apiConfig.path,
1264
+ params = emptyMap(),
1265
+ initialQuery = searchQueryParams,
1215
1266
  )
1216
- } catch (e: Exception) {
1217
- Timber.e(e, "Error executing search API request")
1218
- emptyArray()
1267
+ // A bare Track array, unlike browse's page object.
1268
+ fetchJson<List<JsonTrack>>(httpRequest, "a track list").map { it.toNitro() }.toTypedArray()
1269
+ }
1270
+ }
1271
+
1272
+ /**
1273
+ * The body of [httpRequest]'s response decoded as [T], which [validate] may still refuse by
1274
+ * throwing.
1275
+ *
1276
+ * @throws HttpStatusException for a non-2xx response, or a 2xx body that is not [expected]
1277
+ * @throws NetworkException when the request fails in transit; a request [HttpClient] refuses (an
1278
+ * invalid URL, an unsupported method) throws as it is
1279
+ */
1280
+ private suspend inline fun <reified T> fetchJson(
1281
+ httpRequest: HttpClient.HttpRequest,
1282
+ expected: String,
1283
+ validate: (T) -> Unit = {},
1284
+ ): T {
1285
+ val httpResponse =
1286
+ httpClient.request(httpRequest).getOrElse { exception ->
1287
+ if (exception !is IOException) throw exception
1288
+ throw NetworkException("Network request failed: ${exception.message}", exception)
1219
1289
  }
1290
+ if (!httpResponse.isSuccessful) {
1291
+ Timber.w(
1292
+ "HTTP request failed with status ${httpResponse.code} for ${httpRequest.url}: ${httpResponse.body}"
1293
+ )
1294
+ throw HttpStatusException(httpResponse.code, "Server returned ${httpResponse.code}")
1295
+ }
1296
+ return try {
1297
+ json.decodeFromString<T>(httpResponse.body).also(validate)
1298
+ } catch (e: Exception) {
1299
+ throw HttpStatusException(
1300
+ httpResponse.code,
1301
+ "Server returned ${httpResponse.code} with a response that is not $expected: ${e.message}",
1302
+ e,
1303
+ )
1220
1304
  }
1221
1305
  }
1222
1306
  }
@@ -1252,6 +1336,7 @@ data class BrowserConfig(
1252
1336
  val singleTrack: Boolean = false,
1253
1337
  val androidControllerOfflineError: Boolean = true,
1254
1338
  val viewMoreTitle: (() -> Promise<String>)? = null,
1339
+ val findTrack: (suspend (id: String) -> Track?)? = null,
1255
1340
  ) {
1256
1341
  val hasSearch: Boolean
1257
1342
  get() {
@@ -0,0 +1,61 @@
1
+ package com.audiobrowser.browser
2
+
3
+ import com.audiobrowser.extension.identity
4
+ import com.margelo.nitro.audiobrowser.ResolvedTrack
5
+ import com.margelo.nitro.audiobrowser.Track
6
+
7
+ /**
8
+ * A change to the favorite set: the [identities] whose state changed, and the set after it. Every
9
+ * copy of a track already stamped with `favorited` (on the page on screen, in the content and track
10
+ * caches, in the queue) follows it through [restamp].
11
+ */
12
+ class FavoriteChange(val identities: Set<String>, private val favorites: Set<String>) {
13
+ /**
14
+ * [track] with `favorited` as the set has it, for a track whose identity changed. Unlike
15
+ * hydration it overwrites the value the track carries and ignores whether favoriting is on, so a
16
+ * change made while it is off still reaches the copies stamped before. Null when the track
17
+ * stands.
18
+ */
19
+ fun restamp(track: Track): Track? {
20
+ val identity = track.identity?.takeIf { it in identities } ?: return null
21
+ val favorited = identity in favorites
22
+ return if (track.favorited == favorited) null else track.copy(favorited = favorited)
23
+ }
24
+
25
+ /**
26
+ * As [restamp], for a track that carries `favorited`. One without follows the set through
27
+ * hydration, and stamping it would keep a value after favoriting is turned off.
28
+ */
29
+ fun restampStamped(track: Track): Track? = if (track.favorited == null) null else restamp(track)
30
+
31
+ /** A copy of [page] with each track [transform] returns replaced; null when none is. */
32
+ fun restamp(page: ResolvedTrack, transform: (Track) -> Track? = { restamp(it) }): ResolvedTrack? {
33
+ val sections = page.sections ?: return null
34
+ var replaced = false
35
+ val updated =
36
+ sections.map { section ->
37
+ section.copy(
38
+ children =
39
+ section.children
40
+ .map { track -> transform(track)?.also { replaced = true } ?: track }
41
+ .toTypedArray()
42
+ )
43
+ }
44
+ return if (replaced) page.copy(sections = updated.toTypedArray()) else null
45
+ }
46
+
47
+ companion object {
48
+ /** The change from replacing [previous] with [favorites]; null when they hold the same. */
49
+ fun between(previous: Set<String>, favorites: Set<String>): FavoriteChange? {
50
+ val changed = (previous - favorites) + (favorites - previous)
51
+ return if (changed.isEmpty()) null else FavoriteChange(changed, favorites)
52
+ }
53
+
54
+ /**
55
+ * A toggle of [identity]. It restamps even when the set already agreed, since a copy may carry
56
+ * the opposite value from the API.
57
+ */
58
+ fun toggle(identity: String, favorited: Boolean) =
59
+ FavoriteChange(setOf(identity), if (favorited) setOf(identity) else emptySet())
60
+ }
61
+ }
@@ -5,8 +5,6 @@ import java.io.IOException
5
5
  import java.util.concurrent.TimeUnit
6
6
  import kotlinx.coroutines.Dispatchers
7
7
  import kotlinx.coroutines.withContext
8
- import kotlinx.serialization.json.Json
9
- import kotlinx.serialization.json.JsonElement
10
8
  import okhttp3.Headers
11
9
  import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
12
10
  import okhttp3.MediaType.Companion.toMediaType
@@ -23,11 +21,6 @@ class HttpClient {
23
21
  private const val TIMEOUT_SECONDS = 30L
24
22
  }
25
23
 
26
- val json = Json {
27
- ignoreUnknownKeys = true
28
- isLenient = true
29
- }
30
-
31
24
  /**
32
25
  * Debug builds only: Timber is an `api` dependency, so these lines reach the host app's trees
33
26
  * (crash-reporter breadcrumbs included), and `BODY` buffers every response whether or not
@@ -61,13 +54,7 @@ class HttpClient {
61
54
  val userAgent: String = DEFAULT_USER_AGENT,
62
55
  )
63
56
 
64
- data class HttpResponse(
65
- val code: Int,
66
- val body: String,
67
- val headers: Map<String, String>,
68
- /** HTTP reason phrase, e.g. "Not Found"; OkHttp leaves it empty over HTTP/2. */
69
- val message: String,
70
- ) {
57
+ data class HttpResponse(val code: Int, val body: String, val headers: Map<String, String>) {
71
58
  val isSuccessful: Boolean
72
59
  get() = code in 200..299
73
60
  }
@@ -123,12 +110,7 @@ class HttpClient {
123
110
  val responseHeaders = response.headers.toMap()
124
111
 
125
112
  Result.success(
126
- HttpResponse(
127
- code = response.code,
128
- body = responseBody,
129
- headers = responseHeaders,
130
- message = response.message,
131
- )
113
+ HttpResponse(code = response.code, body = responseBody, headers = responseHeaders)
132
114
  )
133
115
  } catch (e: IOException) {
134
116
  Timber.e(e, "HTTP request failed")
@@ -138,43 +120,4 @@ class HttpClient {
138
120
  Result.failure(e)
139
121
  }
140
122
  }
141
-
142
- /** Fails with [HttpException] on a non-2xx response. */
143
- suspend inline fun <reified T> requestJson(httpRequest: HttpRequest): Result<T> {
144
- return request(httpRequest).mapCatching { response ->
145
- if (!response.isSuccessful) {
146
- throw HttpException(response.code, response.body, response.message)
147
- }
148
- json.decodeFromString<T>(response.body)
149
- }
150
- }
151
-
152
- /** Fails with [HttpException] on a non-2xx response. */
153
- suspend fun requestJsonElement(httpRequest: HttpRequest): Result<JsonElement> {
154
- return request(httpRequest).mapCatching { response ->
155
- if (!response.isSuccessful) {
156
- throw HttpException(response.code, response.body, response.message)
157
- }
158
- json.parseToJsonElement(response.body)
159
- }
160
- }
161
-
162
- /** Its message is the JSON body's `error` field when there is one, else [reasonPhrase]. */
163
- class HttpException(val code: Int, val responseBody: String, val reasonPhrase: String) :
164
- Exception(formatMessage(code, responseBody, reasonPhrase)) {
165
- companion object {
166
- private fun formatMessage(code: Int, responseBody: String, reasonPhrase: String): String {
167
- try {
168
- val json = org.json.JSONObject(responseBody)
169
- val errorMessage = json.optString("error", null)
170
- if (!errorMessage.isNullOrBlank()) {
171
- return errorMessage
172
- }
173
- } catch (_: Exception) {
174
- // Not JSON: fall back to the reason phrase.
175
- }
176
- return reasonPhrase
177
- }
178
- }
179
- }
180
123
  }
@@ -113,8 +113,7 @@ object RequestConfigBuilder {
113
113
  } catch (e: CancellationException) {
114
114
  throw e
115
115
  } catch (e: Exception) {
116
- // A JS call that throws reaches here as JSError's `what()`, `message\n\nstack`.
117
- throw CallbackException(e.message?.substringBefore("\n\n") ?: e.toString(), e)
116
+ throw CallbackException(e.message ?: e.toString(), e)
118
117
  }
119
118
  }
120
119
 
@@ -240,6 +239,7 @@ object RequestConfigBuilder {
240
239
  }
241
240
  }
242
241
 
242
+ /** Base URL, path, then query; a `data:` URL takes no query, which would land in its payload. */
243
243
  internal fun buildUrl(config: RequestConfig): String {
244
244
  val path = config.path ?: ""
245
245
  val baseUrl = config.baseUrl
@@ -247,7 +247,7 @@ object RequestConfigBuilder {
247
247
  val url = BrowserPathHelper.buildUrl(baseUrl, path)
248
248
 
249
249
  val query = config.query
250
- if (query.isNullOrEmpty()) return url
250
+ if (query.isNullOrEmpty() || BrowserPathHelper.isDataUrl(url)) return url
251
251
 
252
252
  val queryString =
253
253
  query.entries.joinToString("&") { (key, value) ->
@@ -24,6 +24,7 @@ data class PlayerUpdateOptions(
24
24
  seekTo = null,
25
25
  skipToNext = null,
26
26
  skipToPrevious = null,
27
+ skipToQueueItem = null,
27
28
  jumpForward = false,
28
29
  jumpBackward = false,
29
30
  favorite = null,
@@ -98,6 +99,7 @@ data class PlayerUpdateOptions(
98
99
  seekTo = incoming.seekTo ?: existing.seekTo,
99
100
  skipToNext = incoming.skipToNext ?: existing.skipToNext,
100
101
  skipToPrevious = incoming.skipToPrevious ?: existing.skipToPrevious,
102
+ skipToQueueItem = incoming.skipToQueueItem ?: existing.skipToQueueItem,
101
103
  jumpForward = incoming.jumpForward ?: existing.jumpForward,
102
104
  jumpBackward = incoming.jumpBackward ?: existing.jumpBackward,
103
105
  favorite = incoming.favorite ?: existing.favorite,
@@ -19,6 +19,7 @@ enum class Capability {
19
19
  SEEK_TO,
20
20
  SKIP_TO_NEXT,
21
21
  SKIP_TO_PREVIOUS,
22
+ SKIP_TO_QUEUE_ITEM,
22
23
  JUMP_FORWARD,
23
24
  JUMP_BACKWARD,
24
25
  FAVORITE,
@@ -35,6 +36,7 @@ fun PlayerCapabilities.isEnabled(capability: Capability): Boolean =
35
36
  Capability.SEEK_TO -> seekTo != false
36
37
  Capability.SKIP_TO_NEXT -> skipToNext != false
37
38
  Capability.SKIP_TO_PREVIOUS -> skipToPrevious != false
39
+ Capability.SKIP_TO_QUEUE_ITEM -> skipToQueueItem != false
38
40
  Capability.JUMP_FORWARD -> jumpForward != false
39
41
  Capability.JUMP_BACKWARD -> jumpBackward != false
40
42
  Capability.FAVORITE -> favoriteEnabled