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

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.
@@ -918,8 +918,8 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
918
918
 
919
919
  override fun load(track: Track) {
920
920
  // Throws without a player, as on iOS: a track asked for and silently dropped hides a mistake.
921
- val player = player
922
- launchInScope { player.load(track) }
921
+ // Blocks rather than launching, so a track the player refuses fails this call.
922
+ runBlockingOnMain { player.load(track) }
923
923
  }
924
924
 
925
925
  override fun reset() =
@@ -0,0 +1,67 @@
1
+ package com.audiobrowser.player
2
+
3
+ import com.audiobrowser.TestFixtures
4
+ import com.audiobrowser.model.PlayerSetupOptions
5
+ import org.junit.After
6
+ import org.junit.Assert.assertEquals
7
+ import org.junit.Assert.assertThrows
8
+ import org.junit.Before
9
+ import org.junit.Test
10
+ import org.junit.runner.RunWith
11
+ import org.robolectric.RobolectricTestRunner
12
+ import org.robolectric.RuntimeEnvironment
13
+
14
+ // Robolectric: Player builds a real ExoPlayer, which needs the framework and a main looper.
15
+ @RunWith(RobolectricTestRunner::class)
16
+ class PlayerInvalidTrackTest {
17
+
18
+ private val player = Player(RuntimeEnvironment.getApplication())
19
+ private val invalid = TestFixtures.track(title = "invalid", src = null)
20
+
21
+ @Before fun setup() = player.setup(PlayerSetupOptions())
22
+
23
+ @After fun release() = player.exoPlayer.release()
24
+
25
+ @Test
26
+ fun loadIntoAnEmptyQueueThrows() {
27
+ assertThrows(IllegalArgumentException::class.java) { player.load(invalid) }
28
+
29
+ assertEquals(emptyList<String>(), titles())
30
+ }
31
+
32
+ @Test
33
+ fun loadOverTheCurrentTrackThrows() {
34
+ player.setQueue(arrayOf(valid("a"), valid("b")), startIndex = 1)
35
+
36
+ assertThrows(IllegalArgumentException::class.java) { player.load(invalid) }
37
+
38
+ assertEquals(listOf("a", "b"), titles())
39
+ assertEquals(1, player.exoPlayer.currentMediaItemIndex)
40
+ }
41
+
42
+ @Test
43
+ fun addThrowsAndAddsNoneOfTheTracks() {
44
+ player.setQueue(arrayOf(valid("a")))
45
+
46
+ assertThrows(IllegalArgumentException::class.java) {
47
+ player.add(arrayOf(valid("b"), invalid), -1)
48
+ }
49
+
50
+ assertEquals(listOf("a"), titles())
51
+ }
52
+
53
+ @Test
54
+ fun setQueueThrowsAndKeepsTheQueue() {
55
+ player.setQueue(arrayOf(valid("a")))
56
+
57
+ assertThrows(IllegalArgumentException::class.java) {
58
+ player.setQueue(arrayOf(valid("b"), invalid))
59
+ }
60
+
61
+ assertEquals(listOf("a"), titles())
62
+ }
63
+
64
+ private fun valid(title: String) = TestFixtures.track(title = title, src = "https://s/$title.mp3")
65
+
66
+ private fun titles() = player.tracks.map { it.title }
67
+ }
@@ -56,7 +56,7 @@ enum MediaIntentPlayback {
56
56
  do {
57
57
  guard let tracks = try await browser.browserManager.searchPlayable(params),
58
58
  let player = livePlayer(of: browser) else { return false }
59
- player.setQueue(tracks, initialIndex: 0, playWhenReady: true)
59
+ try player.setQueue(tracks, initialIndex: 0, playWhenReady: true)
60
60
  browser.showNowPlayingRequestedEmitter.emit(())
61
61
  return true
62
62
  } catch {
@@ -13,7 +13,7 @@ public extension HybridAudioBrowser {
13
13
  guard let player else {
14
14
  throw NSError(domain: "AudioBrowser", code: 1, userInfo: [NSLocalizedDescriptionKey: "Player not initialized"])
15
15
  }
16
- player.load(track)
16
+ try player.load(track)
17
17
  }
18
18
  }
19
19
 
@@ -161,7 +161,7 @@ public extension HybridAudioBrowser {
161
161
  if let index = insertBeforeIndex {
162
162
  try player.add(tracks, at: Int(index))
163
163
  } else {
164
- player.add(tracks)
164
+ try player.add(tracks)
165
165
  }
166
166
  }
167
167
  }
@@ -248,9 +248,9 @@ public extension HybridAudioBrowser {
248
248
  }
249
249
 
250
250
  func setQueue(tracks: [Track], startIndex: Double?, startPosition: Double?) throws {
251
- onMainActor {
251
+ try onMainActor {
252
252
  guard let player else { return }
253
- player.setQueue(
253
+ try player.setQueue(
254
254
  tracks,
255
255
  initialIndex: startIndex.map { Int($0) } ?? 0,
256
256
  startPositionMs: startPosition.map { $0 * 1000 },
@@ -21,6 +21,8 @@ public enum TrackPlayerError: Error {
21
21
  case noCurrentItem
22
22
  case invalidIndex(index: Int, message: String)
23
23
  case empty
24
+ /// A track with neither `src` nor `path`, which no queue can hold.
25
+ case invalidTrack(title: String)
24
26
  }
25
27
  }
26
28
 
@@ -56,6 +58,8 @@ extension TrackPlayerError.QueueError: LocalizedError {
56
58
  "Invalid track index \(index): \(message)"
57
59
  case .empty:
58
60
  "Queue is empty"
61
+ case let .invalidTrack(title):
62
+ "Track must have either path or src defined. Track: title='\(title)'"
59
63
  }
60
64
  }
61
65
  }
@@ -431,7 +431,15 @@ final class Player {
431
431
 
432
432
  // MARK: - Queue Methods
433
433
 
434
- func load(_ track: Track, playWhenReady: Bool? = nil) {
434
+ /// Refuses a track with neither `src` nor `path`, before the queue changes.
435
+ private func throwIfInvalid(_ tracks: [Track]) throws {
436
+ if let track = tracks.first(where: { $0.src == nil && $0.path == nil }) {
437
+ throw TrackPlayerError.QueueError.invalidTrack(title: track.title)
438
+ }
439
+ }
440
+
441
+ func load(_ track: Track, playWhenReady: Bool? = nil) throws {
442
+ try throwIfInvalid([track])
435
443
  handlePlayWhenReady(playWhenReady) {
436
444
  if queue.currentIndex == -1 {
437
445
  afterQueueMutation(queue.add([track], initialIndex: 0))
@@ -457,7 +465,8 @@ final class Player {
457
465
  startPositionMs: Double? = nil,
458
466
  playWhenReady: Bool? = nil,
459
467
  sourcePath: String? = nil,
460
- ) {
468
+ ) throws {
469
+ try throwIfInvalid(newTracks)
461
470
  guard !newTracks.isEmpty else {
462
471
  clear()
463
472
  return
@@ -470,13 +479,15 @@ final class Player {
470
479
  }
471
480
  }
472
481
 
473
- func add(_ tracks: [Track], initialIndex: Int? = nil, playWhenReady: Bool? = nil) {
482
+ func add(_ tracks: [Track], initialIndex: Int? = nil, playWhenReady: Bool? = nil) throws {
483
+ try throwIfInvalid(tracks)
474
484
  handlePlayWhenReady(playWhenReady) {
475
485
  afterQueueMutation(queue.add(tracks, initialIndex: initialIndex ?? 0))
476
486
  }
477
487
  }
478
488
 
479
489
  func add(_ tracks: [Track], at index: Int) throws {
490
+ try throwIfInvalid(tracks)
480
491
  try afterQueueMutation(queue.addAt(tracks, at: index))
481
492
  }
482
493
 
@@ -904,26 +915,30 @@ final class Player {
904
915
  shuffleEnabled = snapshot.shuffleEnabled
905
916
  rate = snapshot.playbackSpeed
906
917
  let startMs = track.live == true ? nil : snapshot.positionMs
907
- if let expanded {
908
- setQueue(expanded.tracks, initialIndex: expanded.selectedIndex, startPositionMs: startMs, playWhenReady: true)
909
- } else {
910
- setQueue([track], initialIndex: 0, startPositionMs: startMs, playWhenReady: true)
918
+ do {
919
+ if let expanded {
920
+ try setQueue(expanded.tracks, initialIndex: expanded.selectedIndex, startPositionMs: startMs, playWhenReady: true)
921
+ } else {
922
+ try setQueue([track], initialIndex: 0, startPositionMs: startMs, playWhenReady: true)
923
+ }
924
+ } catch {
925
+ logger.error("resume: \(error)")
911
926
  }
912
927
  }
913
928
 
914
929
  /// Plays what `TrackSelector` resolved a picked track to.
915
930
  func execute(_ intent: TrackSelector.PlaybackIntent) {
916
- switch intent {
917
- case let .skipTo(index):
918
- do {
931
+ do {
932
+ switch intent {
933
+ case let .skipTo(index):
919
934
  try skipTo(index, playWhenReady: true)
920
- } catch {
921
- logger.error("Failed to skip to track at index \(index): \(error)")
935
+ case let .setQueue(tracks, startIndex, sourcePath):
936
+ try setQueue(tracks, initialIndex: startIndex, playWhenReady: true, sourcePath: sourcePath)
937
+ case let .loadTrack(track):
938
+ try load(track, playWhenReady: true)
922
939
  }
923
- case let .setQueue(tracks, startIndex, sourcePath):
924
- setQueue(tracks, initialIndex: startIndex, playWhenReady: true, sourcePath: sourcePath)
925
- case let .loadTrack(track):
926
- load(track, playWhenReady: true)
940
+ } catch {
941
+ logger.error("Failed to play the selected track: \(error)")
927
942
  }
928
943
  }
929
944
 
@@ -0,0 +1,67 @@
1
+ import Foundation
2
+ import Testing
3
+
4
+ @testable import AudioBrowserTestable
5
+
6
+ @Suite("ArtworkFreshness")
7
+ struct ArtworkFreshnessTests {
8
+ private func response(status: Int = 200, _ headers: [String: String] = [:]) -> HTTPURLResponse {
9
+ HTTPURLResponse(url: URL(string: "https://example.com/a")!, statusCode: status, httpVersion: nil, headerFields: headers)!
10
+ }
11
+
12
+ @Test func aResponseLivesForItsMaxAge() {
13
+ #expect(ArtworkFreshness.lifetime(of: [response(["Cache-Control": "public, max-age=60"])]) == 60)
14
+ }
15
+
16
+ @Test func theShortestHopOfARedirectChainWins() {
17
+ let redirect = response(status: 302, ["Cache-Control": "max-age=86400, stale-while-revalidate=604800"])
18
+ let image = response(["Cache-Control": "public, max-age=31536000, immutable"])
19
+ #expect(ArtworkFreshness.lifetime(of: [redirect, image]) == 86400)
20
+ }
21
+
22
+ @Test func aHopThatStatesNothingIsSkipped() {
23
+ let redirect = response(status: 302)
24
+ let image = response(["Cache-Control": "max-age=300"])
25
+ #expect(ArtworkFreshness.lifetime(of: [redirect, image]) == 300)
26
+ }
27
+
28
+ @Test func withoutAnyStatedLifetimeTheDefaultHolds() {
29
+ #expect(ArtworkFreshness.lifetime(of: [response(), response(["Cache-Control": "public"])]) == ArtworkFreshness.defaultLifetime)
30
+ #expect(ArtworkFreshness.lifetime(of: []) == ArtworkFreshness.defaultLifetime)
31
+ }
32
+
33
+ @Test(arguments: ["no-cache", "no-store", "max-age=600, no-cache", "No-Store"])
34
+ func noCacheOrNoStoreIsAlreadyStale(_ cacheControl: String) {
35
+ #expect(ArtworkFreshness.lifetime(of: [response(["Cache-Control": cacheControl])]) == 0)
36
+ }
37
+
38
+ @Test func ageIsSubtractedFromMaxAge() {
39
+ #expect(ArtworkFreshness.lifetime(of: [response(["Cache-Control": "max-age=600", "Age": "100"])]) == 500)
40
+ #expect(ArtworkFreshness.lifetime(of: [response(["Cache-Control": "max-age=60", "Age": "100"])]) == 0)
41
+ }
42
+
43
+ @Test func directivesAreReadLooselyAsServersSendThem() {
44
+ #expect(ArtworkFreshness.lifetime(of: [response(["cache-control": " MAX-AGE = \"120\" "])]) == 120)
45
+ }
46
+
47
+ @Test func anUnreadableMaxAgeStatesNothing() {
48
+ #expect(ArtworkFreshness.lifetime(of: [response(["Cache-Control": "max-age=soon"])]) == ArtworkFreshness.defaultLifetime)
49
+ }
50
+
51
+ @Test(arguments: ["max-age=inf", "max-age=1e999", "max-age=-5", "max-age="])
52
+ func onlyDigitsStateAMaxAge(_ cacheControl: String) {
53
+ #expect(ArtworkFreshness.lifetime(of: [response(["Cache-Control": cacheControl])]) == ArtworkFreshness.defaultLifetime)
54
+ }
55
+
56
+ @Test func aMaxAgeBeyond2To31IsCapped() {
57
+ #expect(ArtworkFreshness.lifetime(of: [response(["Cache-Control": "max-age=" + String(repeating: "9", count: 400)])]) == 2_147_483_648)
58
+ }
59
+
60
+ @Test func aBareEqualsSignIsSkipped() {
61
+ #expect(ArtworkFreshness.lifetime(of: [response(["Cache-Control": "max-age=60,="])]) == 60)
62
+ }
63
+
64
+ @Test func noCacheNamingAFieldStillLetsTheResponseBeReused() {
65
+ #expect(ArtworkFreshness.lifetime(of: [response(["Cache-Control": "max-age=600, no-cache=\"Set-Cookie\""])]) == 600)
66
+ }
67
+ }
@@ -0,0 +1,65 @@
1
+ @testable import AudioBrowserTestable
2
+ import Testing
3
+
4
+ @Suite("Player - invalid tracks")
5
+ @MainActor
6
+ struct PlayerInvalidTrackTests {
7
+ private let invalid = Track(title: "Invalid")
8
+
9
+ private func valid(_ title: String) -> Track {
10
+ Track(src: "https://example.com/\(title).mp3", title: title)
11
+ }
12
+
13
+ private func expectInvalidTrack(_ body: () throws -> Void) {
14
+ let error = #expect(throws: TrackPlayerError.QueueError.self, performing: body)
15
+ guard case .invalidTrack = error else {
16
+ Issue.record("Expected invalidTrack, got \(String(describing: error))")
17
+ return
18
+ }
19
+ }
20
+
21
+ @Test func loadIntoAnEmptyQueueThrows() {
22
+ let player = makePlayer()
23
+
24
+ expectInvalidTrack { try player.load(invalid) }
25
+
26
+ #expect(player.tracks.isEmpty)
27
+ }
28
+
29
+ @Test func loadOverTheCurrentTrackThrows() throws {
30
+ let player = makePlayer()
31
+ try player.setQueue([valid("a"), valid("b")], initialIndex: 1)
32
+
33
+ expectInvalidTrack { try player.load(invalid) }
34
+
35
+ #expect(player.tracks.map(\.title) == ["a", "b"])
36
+ #expect(player.currentTrack?.title == "b")
37
+ }
38
+
39
+ @Test func addThrowsAndAddsNoneOfTheTracks() throws {
40
+ let player = makePlayer()
41
+ try player.setQueue([valid("a")])
42
+
43
+ expectInvalidTrack { try player.add([valid("b"), invalid]) }
44
+ expectInvalidTrack { try player.add([valid("b"), invalid], at: 0) }
45
+
46
+ #expect(player.tracks.map(\.title) == ["a"])
47
+ }
48
+
49
+ @Test func setQueueThrowsAndKeepsTheQueue() throws {
50
+ let player = makePlayer()
51
+ try player.setQueue([valid("a")])
52
+
53
+ expectInvalidTrack { try player.setQueue([valid("b"), invalid]) }
54
+
55
+ #expect(player.tracks.map(\.title) == ["a"])
56
+ }
57
+
58
+ @Test func aTrackWithOnlyAPathIsQueued() throws {
59
+ let player = makePlayer()
60
+
61
+ try player.setQueue([Track(path: "/browse/only", title: "Path")])
62
+
63
+ #expect(player.tracks.map(\.title) == ["Path"])
64
+ }
65
+ }