react-native-audio-browser 0.2.0-next.43 → 0.2.0-next.45
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.
- package/android/src/main/java/com/audiobrowser/player/NowPlayingUpdater.kt +68 -21
- package/android/src/main/java/com/audiobrowser/player/Player.kt +3 -0
- package/android/src/test/java/com/audiobrowser/player/NowPlayingUpdaterTest.kt +170 -0
- package/ios/Player/NowPlayingLines.swift +16 -0
- package/ios/Player/NowPlayingUpdater.swift +11 -9
- package/ios/Tests/ArtworkFreshnessTests.swift +67 -0
- package/ios/Tests/NowPlayingLinesTests.swift +23 -0
- package/ios/Util/ArtworkFreshness.swift +42 -0
- package/ios/Util/ArtworkImageFetcher.swift +92 -11
- package/package.json +1 -1
|
@@ -107,9 +107,16 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
|
|
|
107
107
|
private var lastPublished: Published? = null
|
|
108
108
|
|
|
109
109
|
/**
|
|
110
|
-
* The track
|
|
111
|
-
*
|
|
112
|
-
*
|
|
110
|
+
* The identity of the track whose formatter result the surface shows. While it is the rendering
|
|
111
|
+
* track's, [render] skips its interim default stamp, which would flash the track's own line over
|
|
112
|
+
* the formatter's until the async result lands.
|
|
113
|
+
*/
|
|
114
|
+
private var formattedTrackId: String? = null
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The track identity (id-or-src, falling back to path) whose now-playing artwork has been
|
|
118
|
+
* resolved (or is being resolved), so a `nowPlayingArtwork` resolve runs once per track — id-less
|
|
119
|
+
* tracks included — instead of on every render.
|
|
113
120
|
*/
|
|
114
121
|
private var artworkResolvedForTrack: String? = null
|
|
115
122
|
|
|
@@ -153,30 +160,62 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
|
|
|
153
160
|
flash = null
|
|
154
161
|
}
|
|
155
162
|
|
|
156
|
-
/**
|
|
163
|
+
/**
|
|
164
|
+
* The lines the now-playing surface shows for the current track, formatter output included; until
|
|
165
|
+
* the track's first render, and while [enabled] is false, the flash, override or track fields.
|
|
166
|
+
*/
|
|
157
167
|
fun getNowPlaying(): NowPlayingMetadata? {
|
|
158
168
|
val track = surface.currentTrack ?: return null
|
|
169
|
+
val published =
|
|
170
|
+
lastPublished?.takeIf { enabled && it.trackId == (track.identity ?: track.path) }
|
|
171
|
+
?: return layered(track)
|
|
172
|
+
return metadata(track, published.title, published.secondaryLine, published.album)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
private fun layered(track: Track): NowPlayingMetadata {
|
|
159
176
|
val flash = flash
|
|
160
177
|
val override = override
|
|
178
|
+
return metadata(
|
|
179
|
+
track,
|
|
180
|
+
flash?.title ?: override?.title ?: track.title,
|
|
181
|
+
flash?.artist ?: override?.artist ?: track.artist,
|
|
182
|
+
flash?.album ?: override?.album ?: track.album,
|
|
183
|
+
)
|
|
184
|
+
}
|
|
161
185
|
|
|
162
|
-
|
|
186
|
+
private fun metadata(track: Track, title: String?, artist: String?, album: String?) =
|
|
187
|
+
NowPlayingMetadata(
|
|
163
188
|
elapsedTime = null,
|
|
164
|
-
title =
|
|
165
|
-
album =
|
|
166
|
-
artist =
|
|
189
|
+
title = title,
|
|
190
|
+
album = album,
|
|
191
|
+
artist = artist,
|
|
167
192
|
duration = track.duration,
|
|
168
193
|
artwork = track.artwork?.url,
|
|
169
194
|
description = track.description,
|
|
170
195
|
mediaId = track.src ?: track.path,
|
|
171
196
|
genre = track.genre,
|
|
172
197
|
)
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Forgets what the surface shows, so the next [render] stamps the lines and artwork in full: a
|
|
201
|
+
* media item that becomes current, or is replaced in place, carries its own default lines and
|
|
202
|
+
* artwork.
|
|
203
|
+
*/
|
|
204
|
+
fun forgetPublished() {
|
|
205
|
+
lastPublished = null
|
|
206
|
+
formattedTrackId = null
|
|
207
|
+
artworkResolvedForTrack = null
|
|
173
208
|
}
|
|
174
209
|
|
|
175
|
-
/**
|
|
210
|
+
/**
|
|
211
|
+
* Clears override, flash, timed metadata and the published lines on track change (PlayerListener
|
|
212
|
+
* transition).
|
|
213
|
+
*/
|
|
176
214
|
fun clearOverride() {
|
|
177
215
|
override = null
|
|
178
216
|
cancelFlash()
|
|
179
217
|
latestTimedMetadata = null
|
|
218
|
+
forgetPublished()
|
|
180
219
|
}
|
|
181
220
|
|
|
182
221
|
/**
|
|
@@ -193,8 +232,9 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
|
|
|
193
232
|
/**
|
|
194
233
|
* Renders the current now playing metadata to the surface. Flash wins while active (formatter
|
|
195
234
|
* skipped entirely so its async result can't land on top); otherwise the override-or-track
|
|
196
|
-
* default is stamped immediately
|
|
197
|
-
* by track identity and
|
|
235
|
+
* default is stamped immediately, unless a formatter result for the track is already up, and a
|
|
236
|
+
* configured formatter customizes it asynchronously, guarded by track identity and
|
|
237
|
+
* [renderGeneration].
|
|
198
238
|
*/
|
|
199
239
|
fun render() {
|
|
200
240
|
val index = surface.currentIndex ?: return
|
|
@@ -220,15 +260,19 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
|
|
|
220
260
|
activeFlash.artist ?: defaultSecondary,
|
|
221
261
|
activeFlash.album ?: defaultAlbum,
|
|
222
262
|
)
|
|
263
|
+
formattedTrackId = null
|
|
223
264
|
return
|
|
224
265
|
}
|
|
225
266
|
|
|
226
|
-
// Apply the default immediately so the now-playing never lags a track/status change
|
|
227
|
-
|
|
267
|
+
// Apply the default immediately so the now-playing never lags a track/status change, unless
|
|
268
|
+
// a formatter result for this track is on the surface.
|
|
269
|
+
val activeFormatter = if (enabled) formatter else null
|
|
270
|
+
if (activeFormatter == null || formattedTrackId != (track.identity ?: track.path)) {
|
|
271
|
+
applyFields(index, track, defaultTitle, defaultSecondary, defaultAlbum)
|
|
272
|
+
}
|
|
228
273
|
|
|
229
274
|
// If a formatter is configured, let it customize the fields asynchronously. Falls back to the
|
|
230
275
|
// default on null/throw.
|
|
231
|
-
val activeFormatter = if (enabled) formatter else null
|
|
232
276
|
if (activeFormatter != null) {
|
|
233
277
|
val capturedId = track.src ?: track.path
|
|
234
278
|
// Gate the raw load-control signal to the buffering state so `stalled` is correct on its
|
|
@@ -266,8 +310,7 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
|
|
|
266
310
|
val current = surface.currentTrack
|
|
267
311
|
val currentIdx = surface.currentIndex
|
|
268
312
|
if (
|
|
269
|
-
|
|
270
|
-
current != null &&
|
|
313
|
+
current != null &&
|
|
271
314
|
currentIdx != null &&
|
|
272
315
|
(current.src ?: current.path) == capturedId &&
|
|
273
316
|
renderGeneration == generation
|
|
@@ -275,10 +318,11 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
|
|
|
275
318
|
applyFields(
|
|
276
319
|
currentIdx,
|
|
277
320
|
current,
|
|
278
|
-
formatted
|
|
279
|
-
formatted
|
|
280
|
-
formatted
|
|
321
|
+
formatted?.title ?: defaultTitle,
|
|
322
|
+
formatted?.artist ?: defaultSecondary,
|
|
323
|
+
formatted?.album ?: defaultAlbum,
|
|
281
324
|
)
|
|
325
|
+
formattedTrackId = if (formatted != null) current.identity ?: current.path else null
|
|
282
326
|
}
|
|
283
327
|
}
|
|
284
328
|
}
|
|
@@ -297,11 +341,14 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
|
|
|
297
341
|
// (and flicker Android Auto / now-playing) for no visible change. Keyed on the track identity
|
|
298
342
|
// so a new track with a coincidentally identical line still publishes.
|
|
299
343
|
val published = Published(index, track.identity ?: track.path, title, secondaryLine, album)
|
|
300
|
-
|
|
344
|
+
val unchanged = published == lastPublished
|
|
301
345
|
lastPublished = published
|
|
346
|
+
if (unchanged) return
|
|
302
347
|
|
|
303
348
|
surface.stampFields(index, track, title, secondaryLine, album)
|
|
304
|
-
|
|
349
|
+
surface.emitNowPlayingChanged(
|
|
350
|
+
if (enabled) metadata(track, title, secondaryLine, album) else layered(track)
|
|
351
|
+
)
|
|
305
352
|
|
|
306
353
|
// Resolve the now-playing-only artwork (lock screen / notification / Android Auto
|
|
307
354
|
// now-playing), keyed on track id so it runs once per track and not on every render.
|
|
@@ -704,7 +704,10 @@ class Player(internal val context: Context) {
|
|
|
704
704
|
*/
|
|
705
705
|
fun replaceTrack(index: Int, track: Track) {
|
|
706
706
|
validateIndex(index)
|
|
707
|
+
val isCurrent = index == currentIndex
|
|
708
|
+
if (isCurrent) nowPlaying.forgetPublished()
|
|
707
709
|
exoPlayer.replaceMediaItem(index, TrackFactory.toMedia3(track))
|
|
710
|
+
if (isCurrent) nowPlaying.render()
|
|
708
711
|
}
|
|
709
712
|
|
|
710
713
|
/**
|
|
@@ -87,6 +87,8 @@ class NowPlayingUpdaterTest {
|
|
|
87
87
|
|
|
88
88
|
assertEquals(listOf(FakeSurface.Stamp(0, "Station", "Station", "Place", null)), surface.stamps)
|
|
89
89
|
assertEquals(1, surface.emitted.size)
|
|
90
|
+
assertEquals("Place", surface.emitted.last().artist)
|
|
91
|
+
assertEquals(surface.emitted.last(), updater.getNowPlaying())
|
|
90
92
|
}
|
|
91
93
|
|
|
92
94
|
@Test
|
|
@@ -122,6 +124,16 @@ class NowPlayingUpdaterTest {
|
|
|
122
124
|
assertEquals("Station", surface.stamps.last().title)
|
|
123
125
|
}
|
|
124
126
|
|
|
127
|
+
@Test
|
|
128
|
+
fun `disabled updater still reports the override to JS`() = runTest {
|
|
129
|
+
val surface = FakeSurface().apply { currentTrack = track("Station") }
|
|
130
|
+
val updater = NowPlayingUpdater(surface, backgroundScope).apply { enabled = false }
|
|
131
|
+
updater.updateNowPlaying(update(title = "Song"))
|
|
132
|
+
|
|
133
|
+
assertEquals("Song", surface.emitted.last().title)
|
|
134
|
+
assertEquals("Song", updater.getNowPlaying()?.title)
|
|
135
|
+
}
|
|
136
|
+
|
|
125
137
|
// MARK: dedupe
|
|
126
138
|
|
|
127
139
|
@Test
|
|
@@ -192,6 +204,164 @@ class NowPlayingUpdaterTest {
|
|
|
192
204
|
assertEquals("Place", surface.stamps.last().secondary) // per-field fallback
|
|
193
205
|
}
|
|
194
206
|
|
|
207
|
+
@Test
|
|
208
|
+
fun `the formatter's lines reach the event and getNowPlaying`() = runTest {
|
|
209
|
+
val surface =
|
|
210
|
+
FakeSurface().apply {
|
|
211
|
+
currentTrack =
|
|
212
|
+
track("Station", artist = "Place", album = "Country", artwork = "https://s/a.png")
|
|
213
|
+
}
|
|
214
|
+
val updater = NowPlayingUpdater(surface, backgroundScope)
|
|
215
|
+
updater.formatter = { update(artist = "Song - Artist") }
|
|
216
|
+
|
|
217
|
+
updater.render()
|
|
218
|
+
runCurrent()
|
|
219
|
+
|
|
220
|
+
val emitted = surface.emitted.last()
|
|
221
|
+
assertEquals("Station", emitted.title)
|
|
222
|
+
assertEquals("Song - Artist", emitted.artist)
|
|
223
|
+
assertEquals("Country", emitted.album)
|
|
224
|
+
assertEquals(emitted, updater.getNowPlaying())
|
|
225
|
+
assertNull(emitted.elapsedTime)
|
|
226
|
+
assertEquals("https://s/a.png", emitted.artwork)
|
|
227
|
+
assertEquals("https://s/a.mp3", emitted.mediaId)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
@Test
|
|
231
|
+
fun `a re-render keeps the formatter's line up while the formatter runs`() = runTest {
|
|
232
|
+
val surface = FakeSurface().apply { currentTrack = track("Station", artist = "Place") }
|
|
233
|
+
val updater = NowPlayingUpdater(surface, backgroundScope)
|
|
234
|
+
val gate = CompletableDeferred<Unit>()
|
|
235
|
+
var calls = 0
|
|
236
|
+
updater.formatter = {
|
|
237
|
+
if (++calls > 1) gate.await()
|
|
238
|
+
update(artist = "Song - Artist")
|
|
239
|
+
}
|
|
240
|
+
updater.render()
|
|
241
|
+
runCurrent()
|
|
242
|
+
|
|
243
|
+
updater.render()
|
|
244
|
+
runCurrent()
|
|
245
|
+
assertEquals("Song - Artist", updater.getNowPlaying()?.artist)
|
|
246
|
+
gate.complete(Unit)
|
|
247
|
+
runCurrent()
|
|
248
|
+
|
|
249
|
+
assertEquals(listOf("Place", "Song - Artist"), surface.emitted.map { it.artist })
|
|
250
|
+
assertEquals(listOf("Place", "Song - Artist"), surface.stamps.map { it.secondary })
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
@Test
|
|
254
|
+
fun `a formatter that stops customizing restores the default`() = runTest {
|
|
255
|
+
val surface = FakeSurface().apply { currentTrack = track("Station", artist = "Place") }
|
|
256
|
+
val updater = NowPlayingUpdater(surface, backgroundScope)
|
|
257
|
+
var line: String? = "Song - Artist"
|
|
258
|
+
updater.formatter = { update(artist = line) }
|
|
259
|
+
updater.render()
|
|
260
|
+
runCurrent()
|
|
261
|
+
|
|
262
|
+
line = null
|
|
263
|
+
updater.render()
|
|
264
|
+
runCurrent()
|
|
265
|
+
|
|
266
|
+
assertEquals("Place", surface.stamps.last().secondary)
|
|
267
|
+
assertEquals("Place", surface.emitted.last().artist)
|
|
268
|
+
assertEquals("Place", updater.getNowPlaying()?.artist)
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
@Test
|
|
272
|
+
fun `a throwing formatter after a result restores the default`() = runTest {
|
|
273
|
+
val surface = FakeSurface().apply { currentTrack = track("Station", artist = "Place") }
|
|
274
|
+
val updater = NowPlayingUpdater(surface, backgroundScope)
|
|
275
|
+
var fail = false
|
|
276
|
+
updater.formatter = { if (fail) error("boom") else update(artist = "Song - Artist") }
|
|
277
|
+
updater.render()
|
|
278
|
+
runCurrent()
|
|
279
|
+
|
|
280
|
+
fail = true
|
|
281
|
+
updater.render()
|
|
282
|
+
runCurrent()
|
|
283
|
+
|
|
284
|
+
assertEquals("Place", surface.stamps.last().secondary)
|
|
285
|
+
assertEquals("Place", updater.getNowPlaying()?.artist)
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
@Test
|
|
289
|
+
fun `getNowPlaying keeps the formatter's line when the playing item moves in the queue`() =
|
|
290
|
+
runTest {
|
|
291
|
+
val surface = FakeSurface().apply { currentTrack = track("Station", artist = "Place") }
|
|
292
|
+
val updater = NowPlayingUpdater(surface, backgroundScope)
|
|
293
|
+
updater.formatter = { update(artist = "Song - Artist") }
|
|
294
|
+
updater.render()
|
|
295
|
+
runCurrent()
|
|
296
|
+
|
|
297
|
+
surface.currentIndex = 1
|
|
298
|
+
|
|
299
|
+
assertEquals("Song - Artist", updater.getNowPlaying()?.artist)
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
@Test
|
|
303
|
+
fun `a track replaced in place is stamped even with unchanged lines`() = runTest {
|
|
304
|
+
val surface = FakeSurface().apply { currentTrack = track("Station") }
|
|
305
|
+
val updater = NowPlayingUpdater(surface, backgroundScope)
|
|
306
|
+
updater.render()
|
|
307
|
+
|
|
308
|
+
updater.forgetPublished()
|
|
309
|
+
surface.currentTrack = track("Station")
|
|
310
|
+
updater.render()
|
|
311
|
+
|
|
312
|
+
assertEquals(listOf("Station", "Station"), surface.stamps.map { it.title })
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
@Test
|
|
316
|
+
fun `a new item of the same track gets the formatter's line stamped again`() = runTest {
|
|
317
|
+
val surface = FakeSurface().apply { currentTrack = track("Station", artist = "Place") }
|
|
318
|
+
val updater = NowPlayingUpdater(surface, backgroundScope)
|
|
319
|
+
updater.formatter = { update(artist = "Song - Artist") }
|
|
320
|
+
updater.render()
|
|
321
|
+
runCurrent()
|
|
322
|
+
|
|
323
|
+
surface.currentTrack = track("Station", artist = "Place")
|
|
324
|
+
updater.clearOverride()
|
|
325
|
+
updater.render()
|
|
326
|
+
runCurrent()
|
|
327
|
+
|
|
328
|
+
assertEquals(
|
|
329
|
+
listOf("Place", "Song - Artist", "Place", "Song - Artist"),
|
|
330
|
+
surface.stamps.map { it.secondary },
|
|
331
|
+
)
|
|
332
|
+
assertEquals("Song - Artist", updater.getNowPlaying()?.artist)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
@Test
|
|
336
|
+
fun `a copy of the playing track keeps the formatter's line`() = runTest {
|
|
337
|
+
val surface = FakeSurface().apply { currentTrack = track("Station", artist = "Place") }
|
|
338
|
+
val updater = NowPlayingUpdater(surface, backgroundScope)
|
|
339
|
+
updater.formatter = { update(artist = "Song - Artist") }
|
|
340
|
+
updater.render()
|
|
341
|
+
runCurrent()
|
|
342
|
+
|
|
343
|
+
surface.currentTrack = surface.currentTrack?.copy(favorited = true)
|
|
344
|
+
assertEquals("Song - Artist", updater.getNowPlaying()?.artist)
|
|
345
|
+
updater.render()
|
|
346
|
+
runCurrent()
|
|
347
|
+
|
|
348
|
+
assertEquals(listOf("Place", "Song - Artist"), surface.emitted.map { it.artist })
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
@Test
|
|
352
|
+
fun `getNowPlaying shows a new track before it renders`() = runTest {
|
|
353
|
+
val surface = FakeSurface().apply { currentTrack = track("A", src = "https://s/a.mp3") }
|
|
354
|
+
val updater = NowPlayingUpdater(surface, backgroundScope)
|
|
355
|
+
updater.formatter = { update(artist = "Song on A") }
|
|
356
|
+
updater.render()
|
|
357
|
+
runCurrent()
|
|
358
|
+
|
|
359
|
+
surface.currentTrack = track("B", src = "https://s/b.mp3", artist = "Place B")
|
|
360
|
+
|
|
361
|
+
assertEquals("B", updater.getNowPlaying()?.title)
|
|
362
|
+
assertEquals("Place B", updater.getNowPlaying()?.artist)
|
|
363
|
+
}
|
|
364
|
+
|
|
195
365
|
@Test
|
|
196
366
|
fun `formatter params carry surface state`() = runTest {
|
|
197
367
|
var seen: FormatNowPlayingParams? = null
|
|
@@ -25,6 +25,22 @@ struct NowPlayingLines: Equatable {
|
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
+
/// The lines last stamped on the now-playing surface, and the track they were stamped for.
|
|
29
|
+
struct PublishedNowPlayingLines {
|
|
30
|
+
let trackId: String?
|
|
31
|
+
let lines: NowPlayingLines
|
|
32
|
+
|
|
33
|
+
init(_ lines: NowPlayingLines, for track: Track) {
|
|
34
|
+
trackId = track.identity ?? track.path
|
|
35
|
+
self.lines = lines
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/// `lines` when they were stamped for `track`, else nil.
|
|
39
|
+
func lines(for track: Track) -> NowPlayingLines? {
|
|
40
|
+
trackId == (track.identity ?? track.path) ? lines : nil
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
28
44
|
/// What the now-playing surface renders from: the player's track and state.
|
|
29
45
|
@MainActor
|
|
30
46
|
protocol NowPlayingSource: AnyObject {
|
|
@@ -33,8 +33,9 @@ final class NowPlayingUpdater {
|
|
|
33
33
|
|
|
34
34
|
private var artworkLoadTask: Task<Void, Never>?
|
|
35
35
|
|
|
36
|
-
/// The
|
|
37
|
-
|
|
36
|
+
/// The lines `onChanged` last reported, and their track, so a new track with the same text
|
|
37
|
+
/// still reports.
|
|
38
|
+
private var published: PublishedNowPlayingLines?
|
|
38
39
|
|
|
39
40
|
func setOverride(_ update: NowPlayingUpdate?) {
|
|
40
41
|
override = update
|
|
@@ -73,11 +74,13 @@ final class NowPlayingUpdater {
|
|
|
73
74
|
render()
|
|
74
75
|
}
|
|
75
76
|
|
|
76
|
-
/// The
|
|
77
|
-
///
|
|
77
|
+
/// The lines the surface shows for the current track, formatter result included; until the
|
|
78
|
+
/// track's first render, and while `enabled` is false, the flash, override or track fields.
|
|
78
79
|
var nowPlaying: NowPlayingMetadata? {
|
|
79
80
|
guard let track = source?.currentTrack else { return nil }
|
|
80
|
-
|
|
81
|
+
let rendered = enabled ? published?.lines(for: track) : nil
|
|
82
|
+
let lines = rendered ?? .resolve(track: track, flash: flash, override: override)
|
|
83
|
+
return metadata(track: track, lines: lines)
|
|
81
84
|
}
|
|
82
85
|
|
|
83
86
|
/// Empties the now-playing surface and drops any artwork fetch or formatter result in flight.
|
|
@@ -86,7 +89,7 @@ final class NowPlayingUpdater {
|
|
|
86
89
|
artworkLoadTask?.cancel()
|
|
87
90
|
artworkLoadTask = nil
|
|
88
91
|
nowPlayingInfoController.clear()
|
|
89
|
-
|
|
92
|
+
published = nil
|
|
90
93
|
formattedTrackId = nil
|
|
91
94
|
}
|
|
92
95
|
|
|
@@ -212,9 +215,8 @@ final class NowPlayingUpdater {
|
|
|
212
215
|
MPMediaItemPropertyArtist: lines.artist,
|
|
213
216
|
MPMediaItemPropertyAlbumTitle: lines.album,
|
|
214
217
|
])
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
publishedTrackId = trackId
|
|
218
|
+
guard textChanged || published?.lines(for: track) == nil else { return }
|
|
219
|
+
published = PublishedNowPlayingLines(lines, for: track)
|
|
218
220
|
onChanged?(metadata(track: track, lines: lines))
|
|
219
221
|
}
|
|
220
222
|
|
|
@@ -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
|
+
}
|
|
@@ -41,3 +41,26 @@ struct NowPlayingLinesTests {
|
|
|
41
41
|
#expect(lines == NowPlayingLines(title: "Station", artist: nil, album: nil))
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
|
+
|
|
45
|
+
@Suite("PublishedNowPlayingLines")
|
|
46
|
+
struct PublishedNowPlayingLinesTests {
|
|
47
|
+
private let station = Track(src: "https://s/a.mp3", title: "Station", artist: "City")
|
|
48
|
+
private let liveSong = NowPlayingLines(title: "Station", artist: "Song - Artist", album: nil)
|
|
49
|
+
|
|
50
|
+
@Test func theStampedTrackGetsItsLines() {
|
|
51
|
+
let published = PublishedNowPlayingLines(liveSong, for: station)
|
|
52
|
+
#expect(published.lines(for: station) == liveSong)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
@Test func anotherTrackGetsNone() {
|
|
56
|
+
let published = PublishedNowPlayingLines(liveSong, for: station)
|
|
57
|
+
#expect(published.lines(for: Track(src: "https://s/b.mp3", title: "Station", artist: "City")) == nil)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
@Test func aTrackWithoutIdentityMatchesOnItsPath() {
|
|
61
|
+
let folder = Track(path: "/a", title: "Folder")
|
|
62
|
+
let published = PublishedNowPlayingLines(liveSong, for: folder)
|
|
63
|
+
#expect(published.lines(for: folder) == liveSong)
|
|
64
|
+
#expect(published.lines(for: Track(path: "/b", title: "Folder")) == nil)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
enum ArtworkFreshness {
|
|
4
|
+
/// The lifetime when no response states one: Kingfisher's own disk expiry.
|
|
5
|
+
static let defaultLifetime: TimeInterval = 7 * 24 * 60 * 60
|
|
6
|
+
|
|
7
|
+
/// The shortest lifetime any of `responses` (a fetch's redirects and its final response) states:
|
|
8
|
+
/// its `max-age` less its `Age`, or zero for `no-cache` or `no-store`. A response that states
|
|
9
|
+
/// none is skipped; `defaultLifetime` when none does.
|
|
10
|
+
static func lifetime(of responses: [HTTPURLResponse]) -> TimeInterval {
|
|
11
|
+
responses.compactMap(lifetime(of:)).min() ?? defaultLifetime
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
private static func lifetime(of response: HTTPURLResponse) -> TimeInterval? {
|
|
15
|
+
guard let cacheControl = response.value(forHTTPHeaderField: "Cache-Control") else { return nil }
|
|
16
|
+
var maxAge: TimeInterval?
|
|
17
|
+
for directive in cacheControl.split(separator: ",") {
|
|
18
|
+
let parts = directive.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
|
|
19
|
+
let name = parts[0].trimmingCharacters(in: .whitespaces).lowercased()
|
|
20
|
+
let value = parts.count == 2 ? parts[1].trimmingCharacters(in: .whitespaces).trimmingCharacters(in: ["\""]) : nil
|
|
21
|
+
switch name {
|
|
22
|
+
// `no-cache="field"` forbids reusing only that field, not the response.
|
|
23
|
+
case "no-cache" where value == nil, "no-store":
|
|
24
|
+
return 0
|
|
25
|
+
case "max-age":
|
|
26
|
+
maxAge = value.flatMap(deltaSeconds) ?? maxAge
|
|
27
|
+
default:
|
|
28
|
+
break
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
guard let maxAge else { return nil }
|
|
32
|
+
let age = response.value(forHTTPHeaderField: "Age").flatMap(deltaSeconds) ?? 0
|
|
33
|
+
return max(0, maxAge - age)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/// RFC 9111's delta-seconds: digits only, so `inf` or `1e999` state nothing, and capped at 2^31.
|
|
37
|
+
private static func deltaSeconds(_ value: String) -> TimeInterval? {
|
|
38
|
+
guard !value.isEmpty, value.allSatisfy({ ("0" ... "9").contains($0) }), let seconds = TimeInterval(value)
|
|
39
|
+
else { return nil }
|
|
40
|
+
return min(seconds, 2_147_483_648)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -30,8 +30,9 @@ enum ArtworkImageFetcher {
|
|
|
30
30
|
}
|
|
31
31
|
options.append(.requestModifier(modifier))
|
|
32
32
|
}
|
|
33
|
+
let processor: (any ImageProcessor)?
|
|
33
34
|
if let svgScale {
|
|
34
|
-
|
|
35
|
+
processor = SVGProcessor(size: nil, scale: svgScale)
|
|
35
36
|
} else if let downsampleTo {
|
|
36
37
|
// Downsample rasters at decode time. Any size hint passed upstream (the
|
|
37
38
|
// resolver's ImageContext) is advisory — a CDN can ignore it and return
|
|
@@ -40,22 +41,105 @@ enum ArtworkImageFetcher {
|
|
|
40
41
|
// cacheOriginalImage keeps the untouched original in the disk cache so
|
|
41
42
|
// the same URL at another target size re-processes instead of
|
|
42
43
|
// re-downloading.
|
|
43
|
-
|
|
44
|
+
processor = DownsamplingImageProcessor(size: downsampleTo.size)
|
|
44
45
|
options.append(.scaleFactor(downsampleTo.scale))
|
|
45
46
|
options.append(.cacheOriginalImage)
|
|
47
|
+
} else {
|
|
48
|
+
processor = nil
|
|
46
49
|
}
|
|
50
|
+
if let processor { options.append(.processor(processor)) }
|
|
51
|
+
let retry: KingfisherOptionsInfo = waitsForConnectivity ? [.retryStrategy(ConnectivityRetry())] : []
|
|
47
52
|
|
|
48
|
-
|
|
49
|
-
|
|
53
|
+
// Each processed variant is fresh on its own: a variant cached before the image changed
|
|
54
|
+
// would otherwise outlive the refetch of another.
|
|
55
|
+
let key = url.absoluteString + (processor?.identifier ?? "")
|
|
56
|
+
// Only an HTTP fetch records a lifetime: a file: or data: image would be refetched on every show.
|
|
57
|
+
let isFresh = if ["http", "https"].contains(url.scheme?.lowercased()) { await freshness.isFresh(key) } else { true }
|
|
58
|
+
let result: Result<UIImage, any Error> = if isFresh {
|
|
59
|
+
await retrieve(url, options: options + retry, freshnessKey: key)
|
|
60
|
+
} else {
|
|
61
|
+
await refetch(url, options: options, retry: retry, freshnessKey: key)
|
|
50
62
|
}
|
|
63
|
+
switch result {
|
|
64
|
+
case let .success(image):
|
|
65
|
+
return image
|
|
66
|
+
case let .failure(error):
|
|
67
|
+
logger.error("Failed to load artwork from \(source.uri): \(error.localizedDescription)")
|
|
68
|
+
return nil
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private static let freshness = FreshnessStore()
|
|
73
|
+
|
|
74
|
+
/// Fetches a stale or never-fetched image again. When that fails, the cached copy, if any, is
|
|
75
|
+
/// shown; with `retry`, a fetch that failed for want of a connection waits for one first.
|
|
76
|
+
@MainActor
|
|
77
|
+
private static func refetch(
|
|
78
|
+
_ url: URL,
|
|
79
|
+
options: KingfisherOptionsInfo,
|
|
80
|
+
retry: KingfisherOptionsInfo,
|
|
81
|
+
freshnessKey: String,
|
|
82
|
+
) async -> Result<UIImage, any Error> {
|
|
83
|
+
let fetched = await retrieve(url, options: options + [.forceRefresh], freshnessKey: freshnessKey)
|
|
84
|
+
guard case let .failure(error) = fetched else { return fetched }
|
|
85
|
+
if let cached = try? await KingfisherManager.shared.retrieveImage(with: url, options: options + [.onlyFromCache]) {
|
|
86
|
+
return .success(cached.image)
|
|
87
|
+
}
|
|
88
|
+
guard !retry.isEmpty, (error as? KingfisherError)?.isConnectivity == true else { return fetched }
|
|
89
|
+
return await retrieve(url, options: options + [.forceRefresh] + retry, freshnessKey: freshnessKey)
|
|
90
|
+
}
|
|
51
91
|
|
|
92
|
+
/// Fetches through Kingfisher, and records how long an image from the network stays fresh.
|
|
93
|
+
@MainActor
|
|
94
|
+
private static func retrieve(
|
|
95
|
+
_ url: URL,
|
|
96
|
+
options: KingfisherOptionsInfo,
|
|
97
|
+
freshnessKey: String,
|
|
98
|
+
) async -> Result<UIImage, any Error> {
|
|
52
99
|
do {
|
|
53
100
|
let result = try await KingfisherManager.shared.retrieveImage(with: url, options: options)
|
|
54
|
-
|
|
101
|
+
// Metrics mark a download: an image re-made from the cached original is `.none` too.
|
|
102
|
+
if result.cacheType == .none, let metrics = result.metrics {
|
|
103
|
+
let responses = metrics.rawMetrics.transactionMetrics.compactMap { $0.response as? HTTPURLResponse }
|
|
104
|
+
await freshness.record(freshnessKey, lifetime: ArtworkFreshness.lifetime(of: responses))
|
|
105
|
+
}
|
|
106
|
+
return .success(result.image)
|
|
55
107
|
} catch {
|
|
56
|
-
|
|
57
|
-
|
|
108
|
+
return .failure(error)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/// The cache keys whose image is still fresh, each kept on disk until its lifetime ends.
|
|
114
|
+
private actor FreshnessStore {
|
|
115
|
+
private let storage = try? DiskStorage.Backend<Data>(
|
|
116
|
+
config: DiskStorage.Config(name: "com.audiobrowser.artwork-freshness", sizeLimit: 0),
|
|
117
|
+
)
|
|
118
|
+
private var sweptExpired = false
|
|
119
|
+
|
|
120
|
+
func isFresh(_ key: String) -> Bool {
|
|
121
|
+
guard let storage else { return false }
|
|
122
|
+
if !sweptExpired {
|
|
123
|
+
sweptExpired = true
|
|
124
|
+
_ = try? storage.removeExpiredValues()
|
|
58
125
|
}
|
|
126
|
+
return storage.isCached(forKey: key)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
func record(_ key: String, lifetime: TimeInterval) {
|
|
130
|
+
guard let storage else { return }
|
|
131
|
+
if lifetime > 0 {
|
|
132
|
+
try? storage.store(value: Data(), forKey: key, expiration: .seconds(lifetime))
|
|
133
|
+
} else {
|
|
134
|
+
try? storage.remove(forKey: key)
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private extension KingfisherError {
|
|
140
|
+
var isConnectivity: Bool {
|
|
141
|
+
guard case let .responseError(reason: .URLSessionError(error)) = self else { return false }
|
|
142
|
+
return (error as? URLError)?.isConnectivity == true
|
|
59
143
|
}
|
|
60
144
|
}
|
|
61
145
|
|
|
@@ -65,10 +149,7 @@ private struct ConnectivityRetry: RetryStrategy {
|
|
|
65
149
|
private static let maxRetries = 3
|
|
66
150
|
|
|
67
151
|
func retry(context: RetryContext, retryHandler: @escaping @Sendable (RetryDecision) -> Void) {
|
|
68
|
-
guard context.retriedCount < Self.maxRetries,
|
|
69
|
-
case let .responseError(reason: .URLSessionError(error)) = context.error,
|
|
70
|
-
(error as? URLError)?.isConnectivity == true
|
|
71
|
-
else {
|
|
152
|
+
guard context.retriedCount < Self.maxRetries, context.error.isConnectivity else {
|
|
72
153
|
retryHandler(.stop)
|
|
73
154
|
return
|
|
74
155
|
}
|