react-native-audio-browser 1.0.0-next.2 → 1.0.0-next.3

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 (147) hide show
  1. package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +19 -2
  2. package/android/src/main/java/com/audiobrowser/browser/BrowserManager.kt +29 -8
  3. package/android/src/main/java/com/audiobrowser/http/RequestConfigBuilder.kt +8 -10
  4. package/android/src/main/java/com/audiobrowser/model/PlayerSetupOptions.kt +2 -2
  5. package/android/src/main/java/com/audiobrowser/player/AutomaticBufferManager.kt +17 -16
  6. package/android/src/main/java/com/audiobrowser/player/InterceptingPlayer.kt +11 -0
  7. package/android/src/main/java/com/audiobrowser/player/Player.kt +8 -4
  8. package/android/src/test/java/com/audiobrowser/ContentRefreshNavigationErrorTest.kt +236 -0
  9. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerUnparsableResponseTest.kt +82 -0
  10. package/android/src/test/java/com/audiobrowser/browser/BrowserUrlResolutionTest.kt +15 -0
  11. package/android/src/test/java/com/audiobrowser/http/RequestConfigBuilderTest.kt +26 -0
  12. package/android/src/test/java/com/audiobrowser/model/PlayerSetupOptionsTest.kt +19 -2
  13. package/android/src/test/java/com/audiobrowser/player/AutomaticBufferManagerTest.kt +17 -0
  14. package/android/src/test/java/com/audiobrowser/player/SessionQueueShuffleOrderTest.kt +38 -0
  15. package/ios/Browser/BrowserError.swift +8 -0
  16. package/ios/Browser/BrowserManager.swift +29 -28
  17. package/ios/Browser/BrowserPathHelper.swift +26 -24
  18. package/ios/Browser/FavoriteSet.swift +16 -8
  19. package/ios/Browser/Favorites.swift +66 -0
  20. package/ios/Browser/JsonModels.swift +27 -7
  21. package/ios/Browser/NavigationErrorState.swift +18 -1
  22. package/ios/Browser/PageResolver.swift +2 -2
  23. package/ios/Browser/RequestLayer.swift +11 -4
  24. package/ios/Browser/RequestPipeline.swift +8 -4
  25. package/ios/Browser/TabBarEntries.swift +7 -0
  26. package/ios/CarPlay/CarPlayImageLoader.swift +3 -7
  27. package/ios/CarPlay/CarPlaySession+Navigator.swift +3 -1
  28. package/ios/CarPlay/IntentHandlers.swift +1 -7
  29. package/ios/CarPlay/MediaIntentCriteria.swift +4 -4
  30. package/ios/Extension/CGSize+AspectFit.swift +11 -0
  31. package/ios/Extension/Dictionary+Headers.swift +8 -0
  32. package/ios/Extension/NavigationError+Conversion.swift +4 -3
  33. package/ios/Extension/ResolvedTrack+Copying.swift +15 -0
  34. package/ios/Http/HttpClient.swift +37 -11
  35. package/ios/HybridAudioBrowser+Browser.swift +9 -16
  36. package/ios/HybridAudioBrowser+Options.swift +1 -0
  37. package/ios/HybridAudioBrowser+Player.swift +24 -23
  38. package/ios/HybridAudioBrowser+PlayerCallbacks.swift +1 -2
  39. package/ios/Model/NitroTypeStubs.swift +39 -0
  40. package/ios/Model/TrackPlayerError.swift +21 -2
  41. package/ios/Player/AudioSessionController.swift +2 -2
  42. package/ios/Player/MediaLoader.swift +1 -1
  43. package/ios/Player/PlaybackStateMachine.swift +1 -2
  44. package/ios/Player/Player.swift +59 -20
  45. package/ios/Player/PlayerEngine.swift +5 -0
  46. package/ios/Player/QueueManager.swift +21 -4
  47. package/ios/Tests/BrowserErrorTests.swift +21 -0
  48. package/ios/Tests/BrowserPathHelperTests.swift +18 -0
  49. package/ios/Tests/CGSizeAspectFitTests.swift +36 -0
  50. package/ios/Tests/ClampedVolumeTests.swift +26 -0
  51. package/ios/Tests/FavoriteSetTests.swift +68 -3
  52. package/ios/Tests/FavoritesTests.swift +102 -0
  53. package/ios/Tests/HttpClientUserAgentTests.swift +45 -0
  54. package/ios/Tests/JsonModelsTests.swift +74 -6
  55. package/ios/Tests/MediaIntentCriteriaTests.swift +11 -1
  56. package/ios/Tests/MediaLoaderAssetOptionsTests.swift +7 -0
  57. package/ios/Tests/NavigationErrorStateTests.swift +73 -0
  58. package/ios/Tests/PlaybackStateMachineTests.swift +6 -4
  59. package/ios/Tests/PlayerPolicyTests.swift +38 -0
  60. package/ios/Tests/PlayerProgressTests.swift +109 -0
  61. package/ios/Tests/PlayerTests.swift +106 -0
  62. package/ios/Tests/QueueIndexTests.swift +43 -0
  63. package/ios/Tests/QueueManagerTests.swift +79 -15
  64. package/ios/Tests/RequestLayerTests.swift +22 -3
  65. package/ios/Tests/TabBarEntriesTests.swift +19 -0
  66. package/ios/Tests/TrackSelectorTests.swift +154 -0
  67. package/ios/Tests/UnparsableResponseTests.swift +91 -0
  68. package/ios/TrackSelector.swift +28 -8
  69. package/ios/Util/ArtworkImageFetcher.swift +9 -8
  70. package/ios/Util/SVGProcessor.swift +6 -17
  71. package/lib/commonjs/features/browser-config.js +6 -3
  72. package/lib/commonjs/features/browser-config.js.map +1 -1
  73. package/lib/commonjs/features/errors.js +12 -7
  74. package/lib/commonjs/features/errors.js.map +1 -1
  75. package/lib/commonjs/features/nowPlaying.js +9 -3
  76. package/lib/commonjs/features/nowPlaying.js.map +1 -1
  77. package/lib/commonjs/features/playback/trackPlaybackTime.js +2 -1
  78. package/lib/commonjs/features/playback/trackPlaybackTime.js.map +1 -1
  79. package/lib/commonjs/features/player/setup.js +2 -2
  80. package/lib/commonjs/features/queue/activeTrack.js +4 -2
  81. package/lib/commonjs/features/queue/activeTrack.js.map +1 -1
  82. package/lib/commonjs/features/sleepTimer.js +6 -5
  83. package/lib/commonjs/features/sleepTimer.js.map +1 -1
  84. package/lib/commonjs/utils/LazyNativeEmitter.js +2 -1
  85. package/lib/commonjs/utils/LazyNativeEmitter.js.map +1 -1
  86. package/lib/commonjs/utils/NativeUpdatedValue.js +2 -1
  87. package/lib/commonjs/utils/NativeUpdatedValue.js.map +1 -1
  88. package/lib/commonjs/utils/callListener.js +23 -0
  89. package/lib/commonjs/utils/callListener.js.map +1 -0
  90. package/lib/module/features/browser-config.js +6 -3
  91. package/lib/module/features/browser-config.js.map +1 -1
  92. package/lib/module/features/errors.js +12 -7
  93. package/lib/module/features/errors.js.map +1 -1
  94. package/lib/module/features/nowPlaying.js +9 -3
  95. package/lib/module/features/nowPlaying.js.map +1 -1
  96. package/lib/module/features/playback/trackPlaybackTime.js +2 -1
  97. package/lib/module/features/playback/trackPlaybackTime.js.map +1 -1
  98. package/lib/module/features/player/setup.js +2 -2
  99. package/lib/module/features/queue/activeTrack.js +4 -2
  100. package/lib/module/features/queue/activeTrack.js.map +1 -1
  101. package/lib/module/features/sleepTimer.js +6 -5
  102. package/lib/module/features/sleepTimer.js.map +1 -1
  103. package/lib/module/utils/LazyNativeEmitter.js +2 -1
  104. package/lib/module/utils/LazyNativeEmitter.js.map +1 -1
  105. package/lib/module/utils/NativeUpdatedValue.js +2 -1
  106. package/lib/module/utils/NativeUpdatedValue.js.map +1 -1
  107. package/lib/module/utils/callListener.js +19 -0
  108. package/lib/module/utils/callListener.js.map +1 -0
  109. package/lib/typescript/src/features/browser-config.d.ts.map +1 -1
  110. package/lib/typescript/src/features/errors.d.ts +8 -6
  111. package/lib/typescript/src/features/errors.d.ts.map +1 -1
  112. package/lib/typescript/src/features/nowPlaying.d.ts +2 -1
  113. package/lib/typescript/src/features/nowPlaying.d.ts.map +1 -1
  114. package/lib/typescript/src/features/playback/trackPlaybackTime.d.ts.map +1 -1
  115. package/lib/typescript/src/features/player/setup.d.ts +2 -2
  116. package/lib/typescript/src/features/queue/activeTrack.d.ts +2 -1
  117. package/lib/typescript/src/features/queue/activeTrack.d.ts.map +1 -1
  118. package/lib/typescript/src/features/sleepTimer.d.ts +2 -1
  119. package/lib/typescript/src/features/sleepTimer.d.ts.map +1 -1
  120. package/lib/typescript/src/types/browser.d.ts +3 -2
  121. package/lib/typescript/src/types/browser.d.ts.map +1 -1
  122. package/lib/typescript/src/utils/LazyNativeEmitter.d.ts.map +1 -1
  123. package/lib/typescript/src/utils/NativeUpdatedValue.d.ts.map +1 -1
  124. package/lib/typescript/src/utils/callListener.d.ts +7 -0
  125. package/lib/typescript/src/utils/callListener.d.ts.map +1 -0
  126. package/package.json +1 -1
  127. package/src/features/browser-config.test.ts +15 -0
  128. package/src/features/browser-config.ts +6 -3
  129. package/src/features/errors.test.ts +83 -0
  130. package/src/features/errors.ts +12 -7
  131. package/src/features/hook-wiring.test.ts +11 -10
  132. package/src/features/nowPlaying.ts +9 -3
  133. package/src/features/playback/trackPlaybackTime.test.ts +24 -1
  134. package/src/features/playback/trackPlaybackTime.ts +2 -1
  135. package/src/features/player/setup.ts +2 -2
  136. package/src/features/queue/activeTrack.test.ts +32 -0
  137. package/src/features/queue/activeTrack.ts +8 -2
  138. package/src/features/sleepTimer.test.ts +24 -0
  139. package/src/features/sleepTimer.ts +6 -5
  140. package/src/types/browser.ts +3 -2
  141. package/src/utils/LazyNativeEmitter.test.ts +32 -0
  142. package/src/utils/LazyNativeEmitter.ts +3 -1
  143. package/src/utils/NativeUpdatedValue.test.ts +32 -0
  144. package/src/utils/NativeUpdatedValue.ts +3 -1
  145. package/src/utils/callListener.ts +17 -0
  146. package/website/guide/configuration.md +3 -3
  147. package/website/guide/errors.md +3 -1
@@ -74,6 +74,23 @@ class AutomaticBufferManagerTest {
74
74
  assertEquals(6_000, threshold)
75
75
  }
76
76
 
77
+ @Test
78
+ fun `an underrun keeps a threshold set above the automatic maximum`() {
79
+ val slowStart =
80
+ BufferConfig(bufferForPlaybackMs = 10_000, bufferForPlaybackAfterRebufferMs = 10_000)
81
+ val loadControl = DynamicLoadControl(slowStart)
82
+ val manager =
83
+ AutomaticBufferManager(loadControl, slowStart, clock = { nowMs }).also { it.attach(engine) }
84
+
85
+ manager.onPlaybackStateChanged(MediaPlayer.STATE_BUFFERING)
86
+ `when`(engine.totalBufferedDuration).thenReturn(10_000)
87
+ manager.onPlaybackStateChanged(MediaPlayer.STATE_READY)
88
+ nowMs += 20_000
89
+ manager.onPlaybackStateChanged(MediaPlayer.STATE_BUFFERING)
90
+
91
+ assertEquals(10_000, loadControl.getBufferConfig().bufferForPlaybackAfterRebufferMs)
92
+ }
93
+
77
94
  @Test
78
95
  fun `a reconnect's first buffering is not a rebuffer`() {
79
96
  play()
@@ -0,0 +1,38 @@
1
+ package com.audiobrowser.player
2
+
3
+ import com.audiobrowser.TestFixtures
4
+ import com.audiobrowser.model.PlayerSetupOptions
5
+ import com.audiobrowser.util.TrackFactory
6
+ import org.junit.After
7
+ import org.junit.Assert.assertEquals
8
+ import org.junit.Test
9
+ import org.junit.runner.RunWith
10
+ import org.robolectric.RobolectricTestRunner
11
+ import org.robolectric.RuntimeEnvironment
12
+
13
+ /** A queue the session sets, as for an Android Auto pick or playback resumption, shuffle on. */
14
+ @RunWith(RobolectricTestRunner::class)
15
+ class SessionQueueShuffleOrderTest {
16
+
17
+ private val player = Player(RuntimeEnvironment.getApplication())
18
+ private val items =
19
+ (0 until 20).map {
20
+ TrackFactory.toMedia3(TestFixtures.track(title = "$it", src = "https://s/$it.mp3"))
21
+ }
22
+
23
+ @After fun release() = player.exoPlayer.release()
24
+
25
+ @Test
26
+ fun `the start index leads the shuffle order`() {
27
+ player.setup(PlayerSetupOptions())
28
+ player.shuffleMode = true
29
+
30
+ // A random order leads with the start index once in 20: ten in a row is no accident.
31
+ repeat(10) {
32
+ player.forwardingPlayer.setMediaItems(items, 3, 0)
33
+
34
+ assertEquals(3, player.exoPlayer.currentMediaItemIndex)
35
+ assertEquals(3, player.exoPlayer.currentTimeline.getFirstWindowIndex(true))
36
+ }
37
+ }
38
+ }
@@ -13,3 +13,11 @@ enum BrowserError: LocalizedError {
13
13
  }
14
14
  }
15
15
  }
16
+
17
+ extension BrowserError {
18
+ /// The error for a request that no layer gives a base URL. A path no route matches has
19
+ /// nowhere to be fetched from; a route that names a request is misconfigured.
20
+ static func missingBaseUrl(path: String, routed: Bool) -> BrowserError {
21
+ routed ? .invalidConfiguration("No URL configured for route") : .contentNotFound(path: path)
22
+ }
23
+ }
@@ -28,7 +28,8 @@ final class BrowserManager {
28
28
  private var lastSearchKey: String?
29
29
  private var lastSearchResults: [Track]?
30
30
 
31
- private var favorites = FavoriteSet()
31
+ /// The favorite set; set its `queue` to the player.
32
+ private(set) lazy var favorites = Favorites(content: self)
32
33
 
33
34
  private var currentNavigationId: Int = 0
34
35
 
@@ -53,8 +54,8 @@ final class BrowserManager {
53
54
  didSet {
54
55
  // An unchanged result must not churn the CarPlay tab bar or reset its selection;
55
56
  // `invalidateAll` re-queries the tabs every time.
56
- if let tabs, !TabBarEntries.same(oldValue, tabs) {
57
- tabsChanged.emit(tabs)
57
+ if let emitted = TabBarEntries.change(from: oldValue, to: tabs) {
58
+ tabsChanged.emit(emitted)
58
59
  }
59
60
  }
60
61
  }
@@ -78,8 +79,7 @@ final class BrowserManager {
78
79
  let contentChanged = Emitter<ResolvedTrack?>()
79
80
  let tabsChanged = Emitter<[Track]>()
80
81
  let configChanged = Emitter<BrowserConfig>()
81
- /// Emitted on any change to the favorites, however it came about.
82
- let favoritesChanged = Emitter<Void>()
82
+ var favoritesChanged: Emitter<Void> { favorites.changed }
83
83
 
84
84
  /// Runs the app's `handleTrackLoad` and awaits both promise layers (a JS callback returning
85
85
  /// `Promise<void>` arrives as `Promise<Promise<Void>>`); a failure is logged, not thrown. False
@@ -96,10 +96,8 @@ final class BrowserManager {
96
96
 
97
97
  // MARK: - Favorites
98
98
 
99
- func setFavorites(_ favorites: [String]) {
100
- if self.favorites.replace(with: favorites) {
101
- favoritesChanged.emit(())
102
- }
99
+ func setFavorites(_ identities: [String]) {
100
+ favorites.replace(with: identities)
103
101
  }
104
102
 
105
103
  func setFavoriteEnabled(_ enabled: Bool) {
@@ -116,10 +114,11 @@ final class BrowserManager {
116
114
 
117
115
  // MARK: - Navigation
118
116
 
119
- /// Loads `path` as the current page. `bypassCache` refetches it and keeps the current content
120
- /// on screen meanwhile. A newer load supersedes this one: its result or error is dropped, so a
121
- /// slow failing /a cannot show its error over a fast /b's content.
122
- func load(_ path: String, bypassCache: Bool = false) async throws {
117
+ /// Loads `path` as the current page and returns whether it published the content.
118
+ /// `bypassCache` refetches it and keeps the current content on screen meanwhile. A newer load
119
+ /// supersedes this one: its result or error is dropped, so a slow failing /a cannot show its
120
+ /// error over a fast /b's content.
121
+ func load(_ path: String, bypassCache: Bool = false) async throws -> Bool {
123
122
  currentNavigationId += 1
124
123
  let navigationId = currentNavigationId
125
124
  self.path = path
@@ -131,10 +130,11 @@ final class BrowserManager {
131
130
  }
132
131
  do {
133
132
  let resolved = try await resolve(path, useCache: !bypassCache)
134
- guard navigationId == currentNavigationId else { return }
133
+ guard navigationId == currentNavigationId else { return false }
135
134
  content = resolved
135
+ return true
136
136
  } catch {
137
- guard navigationId == currentNavigationId else { return }
137
+ guard navigationId == currentNavigationId else { return false }
138
138
  throw error
139
139
  }
140
140
  }
@@ -172,20 +172,12 @@ final class BrowserManager {
172
172
  (contentGeneration, pageGenerations[path])
173
173
  }
174
174
 
175
- /// Clears every cache and the resolved request layers, then re-queries the tabs and reloads
176
- /// the current path, independently: a failed reload goes to `reloadFailed` with its path, and
177
- /// a failed tabs query keeps the current tabs.
178
- func invalidateAll(reloadFailed: @escaping @MainActor (Error, String) async -> Void) {
175
+ /// Clears every cache and the resolved request layers, then re-queries the tabs; a failed
176
+ /// query keeps the current tabs. Reloading the current path is the caller's.
177
+ func invalidateAll() {
179
178
  clearContent()
180
179
  requests.invalidateLayers()
181
180
  Task { _ = try? await queryTabs() }
182
- Task {
183
- do {
184
- try await load(path, bypassCache: true)
185
- } catch {
186
- await reloadFailed(error, path)
187
- }
188
- }
189
181
  }
190
182
 
191
183
  /// Clears the cached pages and the last search; a fetch in flight caches nothing.
@@ -279,9 +271,9 @@ final class BrowserManager {
279
271
 
280
272
  func queryTabs() async throws -> [Track] {
281
273
  let generation = contentGeneration
282
- guard let tabs = try await pages.tabs() else { return [] }
274
+ let tabs = try await pages.tabs()
283
275
  if generation == contentGeneration { self.tabs = tabs }
284
- return tabs
276
+ return tabs ?? []
285
277
  }
286
278
 
287
279
  // MARK: - Queue Expansion (for CarPlay/external controllers)
@@ -299,3 +291,12 @@ final class BrowserManager {
299
291
  // MARK: - TrackSelectionBrowser
300
292
 
301
293
  extension BrowserManager: TrackSelectionBrowser {}
294
+
295
+ // MARK: - FavoriteStamped
296
+
297
+ extension BrowserManager: FavoriteStamped {
298
+ func restampFavorites(_ restamp: (Track) -> Track?) {
299
+ guard let restamped = content?.replacingEachTrack(restamp) else { return }
300
+ content = restamped
301
+ }
302
+ }
@@ -35,25 +35,18 @@ enum BrowserPathHelper {
35
35
  || path.contains("&\(contextualTrackParam)=")
36
36
  }
37
37
 
38
- /// Strips both `__trackId` and `__index`; `url` unchanged when it is not contextual.
38
+ /// Strips both `__trackId` and `__index` and leaves every other character as it is, so the
39
+ /// result equals the parent path the contextual path was built on; `url` unchanged when it is
40
+ /// not contextual.
39
41
  static func stripTrackId(_ url: String) -> String {
40
- guard isContextual(url) else {
42
+ guard isContextual(url), let query = splitQuery(url) else {
41
43
  return url
42
44
  }
43
45
 
44
- guard var components = URLComponents(string: url) else {
45
- return url
46
- }
47
-
48
- components.queryItems = components.queryItems?.filter {
49
- $0.name != contextualTrackParam && $0.name != contextualIndexParam
50
- }
51
-
52
- if components.queryItems?.isEmpty == true {
53
- components.queryItems = nil
46
+ let kept = query.pairs.filter {
47
+ !$0.hasPrefix("\(contextualTrackParam)=") && !$0.hasPrefix("\(contextualIndexParam)=")
54
48
  }
55
-
56
- return components.string ?? url
49
+ return kept.isEmpty ? String(query.head) : "\(query.head)?\(kept.joined(separator: "&"))"
57
50
  }
58
51
 
59
52
  /// `parentPath` with `trackId` (the track's identity) and, when given, its page position
@@ -67,27 +60,36 @@ enum BrowserPathHelper {
67
60
  }
68
61
 
69
62
  static func extractTrackId(_ path: String) -> String? {
70
- guard isContextual(path) else {
63
+ contextualValue(contextualTrackParam, in: path)
64
+ }
65
+
66
+ /// Nil when the path is not contextual or its index is missing or negative.
67
+ static func extractIndex(_ path: String) -> Int? {
68
+ guard let raw = contextualValue(contextualIndexParam, in: path), let index = Int(raw), index >= 0 else {
71
69
  return nil
72
70
  }
71
+ return index
72
+ }
73
73
 
74
- guard let components = URLComponents(string: path) else {
74
+ /// `path` cut at its first `?`: what precedes it, and the `name=value` pairs after it as written.
75
+ private static func splitQuery(_ path: String) -> (head: Substring, pairs: [Substring])? {
76
+ guard let mark = path.firstIndex(of: "?") else {
75
77
  return nil
76
78
  }
77
-
78
- return components.queryItems?.first { $0.name == contextualTrackParam }?.value
79
+ let pairs = path[path.index(after: mark)...].split(separator: "&", omittingEmptySubsequences: false)
80
+ return (path[..<mark], pairs)
79
81
  }
80
82
 
81
- /// Nil when the path is not contextual or its index is missing or negative.
82
- static func extractIndex(_ path: String) -> Int? {
83
+ /// The percent-decoded value of `name` in a contextual path; nil when `path` is not contextual.
84
+ private static func contextualValue(_ name: String, in path: String) -> String? {
85
+ let prefix = "\(name)="
83
86
  guard isContextual(path),
84
- let components = URLComponents(string: path),
85
- let raw = components.queryItems?.first(where: { $0.name == contextualIndexParam })?.value,
86
- let index = Int(raw), index >= 0
87
+ let pair = splitQuery(path)?.pairs.first(where: { $0.hasPrefix(prefix) })
87
88
  else {
88
89
  return nil
89
90
  }
90
- return index
91
+ let raw = pair.dropFirst(prefix.count)
92
+ return raw.removingPercentEncoding ?? String(raw)
91
93
  }
92
94
 
93
95
  /// Percent-encodes keys and values, so pass them unencoded.
@@ -8,12 +8,13 @@ struct FavoriteSet {
8
8
  private var identities: Set<String> = []
9
9
  var enabled = false
10
10
 
11
- /// False when `favorites` holds the identities already there.
12
- mutating func replace(with favorites: [String]) -> Bool {
11
+ /// The identities whose favorite state changed; empty when `favorites` holds those already
12
+ /// there.
13
+ mutating func replace(with favorites: [String]) -> Set<String> {
13
14
  let replaced = Set(favorites)
14
- guard replaced != identities else { return false }
15
+ let changed = replaced.symmetricDifference(identities)
15
16
  identities = replaced
16
- return true
17
+ return changed
17
18
  }
18
19
 
19
20
  /// A local toggle; the consumer's next `replace(with:)` overrides it.
@@ -35,9 +36,16 @@ struct FavoriteSet {
35
36
  }
36
37
 
37
38
  func hydrate(_ page: ResolvedTrack) -> ResolvedTrack {
38
- guard let sections = page.sections else { return page }
39
- return page.copying(sections: sections.map { section in
40
- section.copying(children: section.children.map(hydrate))
41
- })
39
+ page.replacingEachTrack(hydrate) ?? page
40
+ }
41
+
42
+ /// `track` with `favorited` as the set has it, for a track whose identity is in `changed`
43
+ /// (what `replace(with:)` returned, or the identity just `set`). Unlike `hydrate`, this
44
+ /// overwrites the value the track carries, and ignores `enabled`: a change made while
45
+ /// favoriting is off must still reach the copies stamped before. Nil when the track stands.
46
+ func restamp(_ track: Track, changed: Set<String>) -> Track? {
47
+ guard let identity = track.identity, changed.contains(identity) else { return nil }
48
+ let favorited = identities.contains(identity)
49
+ return track.favorited == favorited ? nil : track.copying(favorited: favorited)
42
50
  }
43
51
  }
@@ -0,0 +1,66 @@
1
+ #if canImport(NitroModules)
2
+ import NitroModules
3
+ #endif
4
+
5
+ /// A holder of tracks stamped with `favorited`: the page on screen, the queue.
6
+ @MainActor
7
+ protocol FavoriteStamped: AnyObject {
8
+ /// Replaces, in place, each track `restamp` returns a track for.
9
+ func restampFavorites(_ restamp: (Track) -> Track?)
10
+ }
11
+
12
+ /// The favorite set, with every stamped copy of a track kept in line with it. A change, from
13
+ /// `setFavorites` or a heart toggle, restamps `content`, then `queue`, then emits `changed`,
14
+ /// whose listeners read both.
15
+ @MainActor
16
+ final class Favorites {
17
+ private var favorites = FavoriteSet()
18
+ private weak var content: (any FavoriteStamped)?
19
+ weak var queue: (any FavoriteStamped)?
20
+ /// Emitted on any change to the favorites, however it came about.
21
+ let changed = Emitter<Void>()
22
+
23
+ init(content: any FavoriteStamped) {
24
+ self.content = content
25
+ }
26
+
27
+ /// Whether favoriting is on (the player's `favorite` capability).
28
+ var enabled: Bool {
29
+ get { favorites.enabled }
30
+ set { favorites.enabled = newValue }
31
+ }
32
+
33
+ func replace(with identities: [String]) {
34
+ apply(favorites.replace(with: identities))
35
+ }
36
+
37
+ /// A local toggle; the next `replace(with:)` overrides it. Restamps `identity` even when the
38
+ /// set already agreed, since a copy may carry the opposite value from the API.
39
+ func set(_ identity: String, favorited: Bool) {
40
+ favorites.set(identity, favorited: favorited)
41
+ apply([identity])
42
+ }
43
+
44
+ func hydrate(_ track: Track) -> Track {
45
+ favorites.hydrate(track)
46
+ }
47
+
48
+ func hydrate(_ page: ResolvedTrack) -> ResolvedTrack {
49
+ favorites.hydrate(page)
50
+ }
51
+
52
+ private func apply(_ changed: Set<String>) {
53
+ guard !changed.isEmpty else { return }
54
+ let set = favorites
55
+ let restamp = { (track: Track) in set.restamp(track, changed: changed) }
56
+ content?.restampFavorites(restamp)
57
+ queue?.restampFavorites(restamp)
58
+ self.changed.emit(())
59
+ }
60
+ }
61
+
62
+ extension Player: FavoriteStamped {
63
+ func restampFavorites(_ restamp: (Track) -> Track?) {
64
+ replaceEach(restamp)
65
+ }
66
+ }
@@ -189,10 +189,12 @@ struct JsonTrackRequest: Codable {
189
189
  }
190
190
  }
191
191
 
192
+ /// A page as an endpoint answers it. `path` and `title` may be absent: a browse page needs its
193
+ /// `title` (`JsonBrowsePage`), a tabs page does not.
192
194
  struct JsonResolvedTrack: Codable {
193
195
  var id: String? = nil
194
- var path: String
195
- var title: String
196
+ var path: String? = nil
197
+ var title: String? = nil
196
198
  var subtitle: String? = nil
197
199
  var artwork: JsonArtwork? = nil
198
200
  var artist: String? = nil
@@ -206,11 +208,26 @@ struct JsonResolvedTrack: Codable {
206
208
  var src: String? = nil
207
209
  var style: JsonStyle? = nil
208
210
  var disabled: Bool? = nil
211
+ var favorited: Bool? = nil
209
212
  var live: Bool? = nil
210
213
  var icyCharset: String? = nil
211
214
  var carPlaySiriListButton: String? = nil
212
215
  }
213
216
 
217
+ /// A browse endpoint's page: a `JsonResolvedTrack` that must carry a `title`.
218
+ struct JsonBrowsePage: Decodable {
219
+ let page: JsonResolvedTrack
220
+
221
+ private enum RequiredKeys: String, CodingKey {
222
+ case title
223
+ }
224
+
225
+ init(from decoder: Decoder) throws {
226
+ _ = try decoder.container(keyedBy: RequiredKeys.self).decode(String.self, forKey: .title)
227
+ page = try JsonResolvedTrack(from: decoder)
228
+ }
229
+ }
230
+
214
231
  struct JsonTrack: Codable {
215
232
  var id: String? = nil
216
233
  var path: String? = nil
@@ -227,6 +244,7 @@ struct JsonTrack: Codable {
227
244
  var request: JsonTrackRequest? = nil
228
245
  var style: JsonStyle? = nil
229
246
  var disabled: Bool? = nil
247
+ var favorited: Bool? = nil
230
248
  var live: Bool? = nil
231
249
  var icyCharset: String? = nil
232
250
  }
@@ -278,9 +296,11 @@ extension JsonSection {
278
296
  }
279
297
 
280
298
  extension JsonResolvedTrack {
281
- func toNitro() -> ResolvedTrack {
299
+ /// The page, with `requestedPath` as its path when the body gave none and an empty title
300
+ /// when it gave none.
301
+ func toNitro(requestedPath: String) -> ResolvedTrack {
282
302
  ResolvedTrack(
283
- path: path,
303
+ path: path ?? requestedPath,
284
304
  style: style?.toSectionStyle(),
285
305
  sections: sections?.map { $0.toNitro() },
286
306
  children: children?.map { $0.toNitro() },
@@ -289,7 +309,7 @@ extension JsonResolvedTrack {
289
309
  src: src,
290
310
  artwork: artwork?.toNitro(),
291
311
  artworkSource: nil, request: nil,
292
- title: title,
312
+ title: title ?? "",
293
313
  subtitle: subtitle,
294
314
  artist: artist,
295
315
  albumPath: albumPath,
@@ -298,7 +318,7 @@ extension JsonResolvedTrack {
298
318
  genre: genre,
299
319
  duration: duration,
300
320
  disabled: disabled,
301
- favorited: nil,
321
+ favorited: favorited,
302
322
  live: live,
303
323
  icyCharset: icyCharset,
304
324
  )
@@ -324,7 +344,7 @@ extension JsonTrack {
324
344
  duration: duration,
325
345
  style: style?.toTrackStyle(),
326
346
  disabled: disabled,
327
- favorited: nil,
347
+ favorited: favorited,
328
348
  live: live,
329
349
  icyCharset: icyCharset,
330
350
  )
@@ -1,4 +1,6 @@
1
- import NitroModules
1
+ #if canImport(NitroModules)
2
+ import NitroModules
3
+ #endif
2
4
 
3
5
  /// The browser's last navigation error and its formatted display, as JS sees them.
4
6
  @MainActor
@@ -39,4 +41,19 @@ final class NavigationErrorState {
39
41
  guard reported == generation else { return }
40
42
  formatted = display
41
43
  }
44
+
45
+ /// Follows one load of the current page, which returns whether it published its content:
46
+ /// published content clears the error, a throw is reported, and a load that a newer one
47
+ /// superseded changes nothing.
48
+ func follow(
49
+ _ load: () async throws -> Bool,
50
+ describe: (Error) -> NavigationError,
51
+ format: (NavigationError) async -> FormattedNavigationError,
52
+ ) async {
53
+ do {
54
+ if try await load() { clear() }
55
+ } catch {
56
+ await report(describe(error), format: format)
57
+ }
58
+ }
42
59
  }
@@ -18,8 +18,8 @@ final class PageResolver {
18
18
  }
19
19
 
20
20
  /// The page at `path`, uncached and without favorites hydrated. A path no route matches is
21
- /// fetched through the request and browse layers. The result carries `sections`, never
22
- /// `children` (ADR 0010).
21
+ /// fetched through the request and browse layers, and throws `contentNotFound` when they set
22
+ /// no base URL. The result carries `sections`, never `children` (ADR 0010).
23
23
  func resolve(_ path: String) async throws -> ResolvedTrack {
24
24
  let routeEntry = config.routes.flatMap { SimpleRouter.browseRoute(for: path, in: $0) }
25
25
 
@@ -76,7 +76,8 @@ enum RequestLayer {
76
76
  }
77
77
 
78
78
  /// Applies one layer. With transforms, they replace its static fields entirely, each handed
79
- /// the one before's result; without, its static fields apply over `base`.
79
+ /// the one before's result; without, its static fields apply over `base`. A transform that
80
+ /// throws anything but a cancellation throws `BrowserError.callbackError`.
80
81
  nonisolated(nonsending) static func apply<C: RequestFields>(
81
82
  _ layer: C,
82
83
  transforms: [nonisolated(nonsending)(C) async throws -> C],
@@ -85,7 +86,13 @@ enum RequestLayer {
85
86
  guard !transforms.isEmpty else { return applyStatic(layer, to: base) }
86
87
  var result = base
87
88
  for transform in transforms {
88
- result = try await transform(result)
89
+ do {
90
+ result = try await transform(result)
91
+ } catch let error as CancellationError {
92
+ throw error
93
+ } catch {
94
+ throw BrowserError.callbackError(error.localizedDescription)
95
+ }
89
96
  }
90
97
  return result
91
98
  }
@@ -174,10 +181,10 @@ enum RequestLayer {
174
181
  /// sets them. Nil when there are none.
175
182
  static func imageHeaders(_ request: some RequestFieldValues) -> [String: String]? {
176
183
  var headers = request.headers ?? [:]
177
- if let userAgent = request.userAgent, headers["User-Agent"] == nil {
184
+ if let userAgent = request.userAgent, !headers.hasHeader("User-Agent") {
178
185
  headers["User-Agent"] = userAgent
179
186
  }
180
- if let contentType = request.contentType, headers["Content-Type"] == nil {
187
+ if let contentType = request.contentType, !headers.hasHeader("Content-Type") {
181
188
  headers["Content-Type"] = contentType
182
189
  }
183
190
  return headers.isEmpty ? nil : headers
@@ -65,7 +65,7 @@ final class RequestPipeline {
65
65
  /// for kinds with none), then `routeConfig` (nil for the implicit browse default).
66
66
  /// `initialQuery` goes onto the request after the request layer, so it reaches the URL even
67
67
  /// when a later layer's transforms replace that layer's static query. Throws
68
- /// `invalidConfiguration` when no layer sets a base URL.
68
+ /// `BrowserError.missingBaseUrl` when no layer sets a base URL.
69
69
  func buildApiRequest(
70
70
  kind: KeyPath<ResolvedLayers, TransformableRequestConfig?>?,
71
71
  _ routeConfig: TransformableRequestConfig?,
@@ -83,7 +83,7 @@ final class RequestPipeline {
83
83
  merged = try await applyLayer(routeConfig, to: merged, params: params)
84
84
 
85
85
  guard merged.baseUrl != nil else {
86
- throw BrowserError.invalidConfiguration("No URL configured for route")
86
+ throw BrowserError.missingBaseUrl(path: path, routed: routeConfig != nil)
87
87
  }
88
88
  return HttpClient.HttpRequest(
89
89
  url: RequestLayer.buildUrl(merged, defaultPath: path),
@@ -108,8 +108,12 @@ final class RequestPipeline {
108
108
  logger.debug(" path: \(path)")
109
109
  logger.debug(" url: \(request.url)")
110
110
 
111
- let result: JsonResolvedTrack = try await httpClient.requestJson(request, as: JsonResolvedTrack.self)
112
- let nitroResult = result.toNitro()
111
+ let result = if path == SimpleRouter.tabsRoutePath {
112
+ try await httpClient.requestJson(request, as: JsonResolvedTrack.self)
113
+ } else {
114
+ try await httpClient.requestJson(request, as: JsonBrowsePage.self).page
115
+ }
116
+ let nitroResult = result.toNitro(requestedPath: path)
113
117
 
114
118
  logger.debug("Resolved: \(nitroResult.title)")
115
119
  if let sections = nitroResult.normalizedSections {
@@ -13,4 +13,11 @@ enum TabBarEntries {
13
13
  && $0.disabled == $1.disabled
14
14
  }
15
15
  }
16
+
17
+ /// What `tabsChanged` emits when the tabs go from `old` to `new`, nil for no event. Tabs that
18
+ /// go away emit an empty list, as on Android: the event cannot carry nil.
19
+ static func change(from old: [Track]?, to new: [Track]?) -> [Track]? {
20
+ guard let new else { return old == nil ? nil : [] }
21
+ return same(old, new) ? nil : new
22
+ }
16
23
  }
@@ -108,15 +108,11 @@ final class CarPlayImageLoader {
108
108
  return .adaptive(light: lightImage, dark: darkImage, for: carTraitCollection)
109
109
  }
110
110
 
111
- /// Rasters downsample to `size` points at the car's display scale (CPListItem.h: "size them
112
- /// to the display scale of the car screen"); SVGs already rasterize at car scale.
111
+ /// The image fitted to `size` points at the car's display scale (CPListItem.h: "size them
112
+ /// to the display scale of the car screen").
113
113
  private func fetchImage(uri: String, headers: [String: String]?, isSvg: Bool, size: CGSize) async -> UIImage? {
114
114
  let source = ImageSource(uri: uri, method: nil, headers: headers, body: nil)
115
- let scale = carTraitCollection.displayScale
116
- if isSvg {
117
- return await ArtworkImageFetcher.fetchImage(from: source, svgScale: scale)
118
- }
119
- return await ArtworkImageFetcher.fetchImage(from: source, downsampleTo: (size, scale))
115
+ return await ArtworkImageFetcher.fetchImage(from: source, fitting: (size, carTraitCollection.displayScale, isSvg))
120
116
  }
121
117
 
122
118
  private nonisolated func renderImageToBitmap(_ image: UIImage, tintColor: UIColor) -> UIImage {
@@ -43,7 +43,9 @@ extension CarPlaySession {
43
43
  session.nowPlaying.showNowPlaying(popToFront: false)
44
44
  case let .browse(path):
45
45
  await session.navigate(to: path, title: track.title)
46
- case .none:
46
+ case .superseded, .none:
47
+ // No `endNowPlayingPreview()` when superseded: Now Playing already previews the later
48
+ // selection's track.
47
49
  break
48
50
  }
49
51
  }
@@ -83,12 +83,6 @@ final class FavoriteIntentHandler: NSObject, INAddMediaIntentHandling, INUpdateM
83
83
 
84
84
  @MainActor
85
85
  private static func favoriteCurrentTrack(_ favorited: Bool) -> Bool {
86
- guard let browser = HybridAudioBrowser.shared else { return false }
87
- do {
88
- return try browser.favoriteActiveTrack(favorited)
89
- } catch {
90
- logger.error("favoriteCurrentTrack(\(favorited)) failed: \(error.localizedDescription)")
91
- return false
92
- }
86
+ HybridAudioBrowser.shared?.favoriteActiveTrack(favorited) ?? false
93
87
  }
94
88
  }