697 lines
25 KiB
Swift
697 lines
25 KiB
Swift
import Combine
|
|
import AVFAudio
|
|
import Foundation
|
|
import SwiftAudioEx
|
|
import UIKit
|
|
|
|
enum PlayerRepeatMode: CaseIterable {
|
|
case off
|
|
case one
|
|
case all
|
|
}
|
|
|
|
/// App-owned playback state and actions backed by SwiftAudioEx.
|
|
@MainActor
|
|
final class PlayerManager: ObservableObject {
|
|
@Published private(set) var currentTrack: Track?
|
|
@Published private(set) var upcomingTracks: [Track] = []
|
|
@Published private(set) var previousTracks: [Track] = []
|
|
@Published private(set) var isPlaying = false
|
|
@Published private(set) var elapsedTime: TimeInterval = 0
|
|
@Published private(set) var duration: TimeInterval = 0
|
|
@Published private(set) var errorMessage: String?
|
|
@Published var repeatMode: PlayerRepeatMode = .off {
|
|
didSet {
|
|
applyRepeatMode()
|
|
scheduleHandoffSave()
|
|
}
|
|
}
|
|
@Published var volume: Double {
|
|
didSet {
|
|
let clamped = min(1, max(0, volume))
|
|
if clamped != volume {
|
|
volume = clamped
|
|
return
|
|
}
|
|
player.volume = Float(clamped)
|
|
UserDefaults.standard.set(clamped, forKey: Self.volumeStorageKey)
|
|
}
|
|
}
|
|
|
|
private static let volumeStorageKey = "music-v2-player-volume"
|
|
private let player = QueuedAudioPlayer()
|
|
private let apiConfiguration: APIConfiguration
|
|
private let api = MusicAPI()
|
|
private var tracksByItemID: [ObjectIdentifier: Track] = [:]
|
|
private var playbackIntent: Bool?
|
|
private var isAuthenticated = false
|
|
private var handoffRestoreAttempted = false
|
|
private var handoffRestoreInProgress = false
|
|
private var handoffGeneration = 0
|
|
private var handoffSaveInFlight = false
|
|
private var handoffSavePending = false
|
|
private var handoffSaveTask: Task<Void, Never>?
|
|
private var handoffPositionTask: Task<Void, Never>?
|
|
private var handoffSeekSaveTask: Task<Void, Never>?
|
|
private var handoffLastSavedAt = Date.distantPast
|
|
private static let handoffSyncInterval: TimeInterval = 15
|
|
|
|
init() {
|
|
self.apiConfiguration = APIConfiguration()
|
|
let storedVolume = UserDefaults.standard.object(forKey: Self.volumeStorageKey) as? Double
|
|
volume = min(1, max(0, storedVolume ?? 0.5))
|
|
player.volume = Float(volume)
|
|
player.automaticallyUpdateNowPlayingInfo = true
|
|
player.remoteCommands = [.play, .pause, .togglePlayPause, .next, .previous, .changePlaybackPosition]
|
|
installEventListeners()
|
|
}
|
|
|
|
func play() {
|
|
do {
|
|
try AudioSessionController.shared.set(category: .playback)
|
|
try AudioSessionController.shared.activateSession()
|
|
playbackIntent = true
|
|
player.play()
|
|
isPlaying = true
|
|
errorMessage = nil
|
|
} catch {
|
|
playbackIntent = nil
|
|
errorMessage = error.localizedDescription
|
|
}
|
|
refreshState()
|
|
updateHandoffPositionTimer()
|
|
scheduleHandoffSave()
|
|
}
|
|
|
|
func pause() {
|
|
handoffSeekSaveTask?.cancel()
|
|
handoffSeekSaveTask = nil
|
|
playbackIntent = false
|
|
isPlaying = false
|
|
player.pause()
|
|
updateHandoffPositionTimer()
|
|
scheduleHandoffSave()
|
|
}
|
|
|
|
func play(_ track: Track) {
|
|
play([track], startingAt: 0, shuffled: false)
|
|
}
|
|
|
|
func play(_ tracks: [Track], startingAt index: Int = 0, shuffled: Bool = false) {
|
|
invalidatePendingHandoffRestore()
|
|
handoffSeekSaveTask?.cancel()
|
|
handoffSeekSaveTask = nil
|
|
guard !tracks.isEmpty else { clear(); return }
|
|
guard tracks.indices.contains(index) else { return }
|
|
let orderedTracks: [Track]
|
|
if shuffled {
|
|
let selected = tracks[index]
|
|
orderedTracks = [selected] + tracks.enumerated()
|
|
.filter { $0.offset != index }
|
|
.map(\.element)
|
|
.shuffled()
|
|
} else {
|
|
orderedTracks = Array(tracks[index...])
|
|
}
|
|
|
|
player.clear()
|
|
tracksByItemID.removeAll()
|
|
let items = orderedTracks.compactMap(makeAudioItem(for:))
|
|
guard !items.isEmpty else {
|
|
errorMessage = "Could not create an audio URL for this track."
|
|
return
|
|
}
|
|
playbackIntent = true
|
|
player.add(items: items, playWhenReady: true)
|
|
refreshState()
|
|
loadArtwork(for: player.currentItem)
|
|
scheduleHandoffSave()
|
|
}
|
|
|
|
func next() {
|
|
player.next()
|
|
refreshState()
|
|
loadArtwork(for: player.currentItem)
|
|
scheduleHandoffSave()
|
|
}
|
|
|
|
func previous() {
|
|
if player.currentTime > 5 {
|
|
seek(to: 0)
|
|
} else {
|
|
player.previous()
|
|
refreshState()
|
|
loadArtwork(for: player.currentItem)
|
|
scheduleHandoffSave()
|
|
}
|
|
}
|
|
|
|
func seek(to seconds: TimeInterval) {
|
|
player.seek(to: min(max(0, seconds), max(duration, 0)))
|
|
elapsedTime = min(max(0, seconds), max(duration, 0))
|
|
handoffSeekSaveTask?.cancel()
|
|
handoffSeekSaveTask = Task { [weak self] in
|
|
try? await Task.sleep(for: .milliseconds(500))
|
|
guard let self, !Task.isCancelled else { return }
|
|
self.handoffSeekSaveTask = nil
|
|
self.scheduleHandoffSave()
|
|
}
|
|
}
|
|
|
|
func addToQueue(_ track: Track) {
|
|
if currentTrack == nil { invalidatePendingHandoffRestore() }
|
|
guard let item = makeAudioItem(for: track) else { return }
|
|
if player.currentItem == nil {
|
|
player.add(item: item, playWhenReady: false)
|
|
} else {
|
|
player.add(item: item)
|
|
}
|
|
refreshState()
|
|
scheduleHandoffSave()
|
|
}
|
|
|
|
func playNext(_ track: Track) {
|
|
if currentTrack == nil { invalidatePendingHandoffRestore() }
|
|
guard let item = makeAudioItem(for: track) else { return }
|
|
guard player.currentItem != nil else {
|
|
player.add(item: item, playWhenReady: true)
|
|
refreshState()
|
|
scheduleHandoffSave()
|
|
return
|
|
}
|
|
do {
|
|
try player.add(items: [item], at: player.currentIndex + 1)
|
|
} catch {
|
|
errorMessage = error.localizedDescription
|
|
}
|
|
refreshState()
|
|
scheduleHandoffSave()
|
|
}
|
|
|
|
func playQueuedTrack(at index: Int) {
|
|
invalidatePendingHandoffRestore()
|
|
guard player.items.indices.contains(index) else { return }
|
|
do {
|
|
try player.jumpToItem(atIndex: index, playWhenReady: true)
|
|
refreshState()
|
|
loadArtwork(for: player.currentItem)
|
|
scheduleHandoffSave()
|
|
} catch {
|
|
errorMessage = error.localizedDescription
|
|
}
|
|
}
|
|
|
|
func moveQueuedTrack(from sourceIndex: Int, to destinationIndex: Int) {
|
|
invalidatePendingHandoffRestore()
|
|
guard player.items.indices.contains(sourceIndex),
|
|
player.items.indices.contains(destinationIndex)
|
|
else { return }
|
|
do {
|
|
try player.moveItem(fromIndex: sourceIndex, toIndex: destinationIndex)
|
|
refreshState()
|
|
scheduleHandoffSave()
|
|
} catch {
|
|
errorMessage = error.localizedDescription
|
|
}
|
|
}
|
|
|
|
func removeQueuedTrack(at index: Int) {
|
|
invalidatePendingHandoffRestore()
|
|
guard player.items.indices.contains(index) else { return }
|
|
let item = player.items[index]
|
|
do {
|
|
_ = try player.removeItem(at: index)
|
|
tracksByItemID.removeValue(forKey: ObjectIdentifier(item as AnyObject))
|
|
refreshState()
|
|
scheduleHandoffSave()
|
|
} catch {
|
|
errorMessage = error.localizedDescription
|
|
}
|
|
}
|
|
|
|
func clear() {
|
|
invalidatePendingHandoffRestore()
|
|
handoffSeekSaveTask?.cancel()
|
|
handoffSeekSaveTask = nil
|
|
let pendingSave = handoffSaveTask
|
|
pendingSave?.cancel()
|
|
handoffSaveTask = nil
|
|
handoffSavePending = false
|
|
playbackIntent = nil
|
|
player.clear()
|
|
tracksByItemID.removeAll()
|
|
isPlaying = false
|
|
currentTrack = nil
|
|
upcomingTracks = []
|
|
previousTracks = []
|
|
elapsedTime = 0
|
|
duration = 0
|
|
errorMessage = nil
|
|
if isAuthenticated {
|
|
Task {
|
|
await pendingSave?.value
|
|
guard isAuthenticated else { return }
|
|
_ = try? await api.deletePlaybackHandoff()
|
|
}
|
|
}
|
|
}
|
|
|
|
func artworkURL(for track: Track) -> URL? {
|
|
guard case .value(let album) = track.album else { return nil }
|
|
return apiConfiguration.mediaURL(for: album.file)
|
|
}
|
|
|
|
func shuffleUpcoming() {
|
|
invalidatePendingHandoffRestore()
|
|
let currentIndex = player.currentIndex
|
|
guard currentIndex >= 0, player.items.count - currentIndex > 2 else { return }
|
|
|
|
let targetOrder = Array(player.items.dropFirst(currentIndex + 1)).shuffled()
|
|
for (offset, target) in targetOrder.enumerated() {
|
|
let targetID = ObjectIdentifier(target as AnyObject)
|
|
guard let existingIndex = player.items.firstIndex(where: {
|
|
ObjectIdentifier($0 as AnyObject) == targetID
|
|
}) else { continue }
|
|
let targetIndex = currentIndex + 1 + offset
|
|
if existingIndex != targetIndex {
|
|
try? player.moveItem(fromIndex: existingIndex, toIndex: targetIndex)
|
|
}
|
|
}
|
|
refreshState()
|
|
scheduleHandoffSave()
|
|
}
|
|
|
|
func cycleRepeat() {
|
|
switch repeatMode {
|
|
case .off: repeatMode = .one
|
|
case .one: repeatMode = .all
|
|
case .all: repeatMode = .off
|
|
}
|
|
}
|
|
|
|
private func applyRepeatMode() {
|
|
switch repeatMode {
|
|
case .off: player.repeatMode = .off
|
|
case .one: player.repeatMode = .track
|
|
case .all: player.repeatMode = .queue
|
|
}
|
|
}
|
|
|
|
func setAuthenticated(_ authenticated: Bool) {
|
|
guard isAuthenticated != authenticated else { return }
|
|
isAuthenticated = authenticated
|
|
logHandoff("authentication changed; signedIn=\(authenticated)")
|
|
if authenticated {
|
|
handoffRestoreAttempted = false
|
|
restorePlaybackHandoffIfNeeded()
|
|
updateHandoffPositionTimer()
|
|
scheduleHandoffSave()
|
|
} else {
|
|
handoffGeneration &+= 1
|
|
handoffRestoreTask?.cancel()
|
|
handoffRestoreTask = nil
|
|
if handoffRestoreInProgress { discardUnsuccessfulHandoffRestore() }
|
|
handoffRestoreAttempted = false
|
|
handoffSaveTask?.cancel()
|
|
handoffSaveTask = nil
|
|
handoffSavePending = false
|
|
handoffPositionTask?.cancel()
|
|
handoffPositionTask = nil
|
|
handoffSeekSaveTask?.cancel()
|
|
handoffSeekSaveTask = nil
|
|
}
|
|
}
|
|
|
|
func saveHandoffForBackground() {
|
|
handoffSeekSaveTask?.cancel()
|
|
handoffSeekSaveTask = nil
|
|
scheduleHandoffSave()
|
|
}
|
|
|
|
private var handoffRestoreTask: Task<Void, Never>?
|
|
|
|
private func invalidatePendingHandoffRestore() {
|
|
guard handoffRestoreTask != nil || handoffRestoreInProgress else { return }
|
|
handoffGeneration &+= 1
|
|
handoffRestoreTask?.cancel()
|
|
handoffRestoreTask = nil
|
|
handoffRestoreInProgress = false
|
|
}
|
|
|
|
private func restorePlaybackHandoffIfNeeded() {
|
|
guard isAuthenticated, !handoffRestoreAttempted, currentTrack == nil else { return }
|
|
handoffRestoreAttempted = true
|
|
handoffGeneration &+= 1
|
|
let generation = handoffGeneration
|
|
handoffRestoreTask = Task { [weak self] in
|
|
await self?.restorePlaybackHandoff(generation: generation)
|
|
}
|
|
}
|
|
|
|
private func restorePlaybackHandoff(generation: Int) async {
|
|
do {
|
|
guard let handoff = try await api.playbackHandoff(),
|
|
generation == handoffGeneration,
|
|
isAuthenticated,
|
|
currentTrack == nil
|
|
else { return }
|
|
|
|
let ids = Array(Set(
|
|
[handoff.currentTrackId] + handoff.queueTrackIds
|
|
+ handoff.remainingTrackIds + handoff.historyTrackIds
|
|
))
|
|
let hydratedTracks = try await api.tracks(ids: ids)
|
|
guard generation == handoffGeneration,
|
|
isAuthenticated,
|
|
currentTrack == nil
|
|
else { return }
|
|
|
|
let tracksByID = Dictionary(hydratedTracks.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
|
|
guard let restoredCurrent = tracksByID[handoff.currentTrackId] else { return }
|
|
func restoredTracks(_ ids: [String]) -> [Track] {
|
|
ids.compactMap { tracksByID[$0] }
|
|
}
|
|
// The web client stores history newest-first; SwiftAudioEx expects it in queue order.
|
|
let orderedHistory = Array(restoredTracks(handoff.historyTrackIds).reversed())
|
|
let restoredIndex = orderedHistory.count
|
|
let orderedQueue = orderedHistory + [restoredCurrent]
|
|
+ restoredTracks(handoff.remainingTrackIds)
|
|
guard !orderedQueue.isEmpty, orderedQueue.indices.contains(restoredIndex) else { return }
|
|
|
|
handoffRestoreInProgress = true
|
|
isApplyingHandoff = true
|
|
player.clear()
|
|
tracksByItemID.removeAll()
|
|
let restoredItems = orderedQueue.compactMap(makeAudioItem(for:))
|
|
guard restoredItems.count == orderedQueue.count,
|
|
restoredItems.indices.contains(restoredIndex)
|
|
else {
|
|
isApplyingHandoff = false
|
|
handoffRestoreInProgress = false
|
|
return
|
|
}
|
|
player.add(items: restoredItems, playWhenReady: false)
|
|
try player.jumpToItem(atIndex: restoredIndex, playWhenReady: false)
|
|
repeatMode = handoff.repeatEnabled ? .all : (handoff.repeatOnce ? .one : .off)
|
|
applyRepeatMode()
|
|
|
|
let ready = await waitForRestoredItem(generation: generation)
|
|
guard ready, generation == handoffGeneration, isAuthenticated else {
|
|
if generation == handoffGeneration {
|
|
discardUnsuccessfulHandoffRestore()
|
|
} else {
|
|
isApplyingHandoff = false
|
|
handoffRestoreInProgress = false
|
|
}
|
|
return
|
|
}
|
|
let requestedPosition = max(0, handoff.position)
|
|
let seekPosition = duration > 0 ? min(requestedPosition, duration) : requestedPosition
|
|
player.seek(to: seekPosition)
|
|
refreshState()
|
|
loadArtwork(for: player.currentItem)
|
|
if handoff.wasPlaying {
|
|
do {
|
|
try AudioSessionController.shared.set(category: .playback)
|
|
try AudioSessionController.shared.activateSession()
|
|
playbackIntent = true
|
|
player.play()
|
|
} catch {
|
|
errorMessage = error.localizedDescription
|
|
isApplyingHandoff = false
|
|
handoffRestoreInProgress = false
|
|
return
|
|
}
|
|
let started = await waitForRestoredPlayback(generation: generation)
|
|
guard started, generation == handoffGeneration else {
|
|
if generation == handoffGeneration {
|
|
discardUnsuccessfulHandoffRestore()
|
|
} else {
|
|
isApplyingHandoff = false
|
|
handoffRestoreInProgress = false
|
|
}
|
|
return
|
|
}
|
|
}
|
|
isApplyingHandoff = false
|
|
handoffRestoreInProgress = false
|
|
handoffRestoreTask = nil
|
|
updateHandoffPositionTimer()
|
|
_ = try? await api.deletePlaybackHandoff()
|
|
} catch is CancellationError {
|
|
if generation == handoffGeneration {
|
|
isApplyingHandoff = false
|
|
handoffRestoreInProgress = false
|
|
handoffRestoreTask = nil
|
|
}
|
|
} catch {
|
|
if generation == handoffGeneration {
|
|
isApplyingHandoff = false
|
|
handoffRestoreInProgress = false
|
|
handoffRestoreTask = nil
|
|
}
|
|
}
|
|
}
|
|
|
|
private var isApplyingHandoff = false
|
|
|
|
private func discardUnsuccessfulHandoffRestore() {
|
|
isApplyingHandoff = true
|
|
playbackIntent = nil
|
|
player.clear()
|
|
tracksByItemID.removeAll()
|
|
currentTrack = nil
|
|
upcomingTracks = []
|
|
previousTracks = []
|
|
isPlaying = false
|
|
elapsedTime = 0
|
|
duration = 0
|
|
isApplyingHandoff = false
|
|
handoffRestoreInProgress = false
|
|
handoffRestoreTask = nil
|
|
}
|
|
|
|
private func waitForRestoredItem(generation: Int) async -> Bool {
|
|
for _ in 0..<150 {
|
|
guard !Task.isCancelled, generation == handoffGeneration else { return false }
|
|
switch player.playerState {
|
|
case .ready, .paused, .playing:
|
|
return true
|
|
case .failed, .stopped, .ended:
|
|
return false
|
|
default:
|
|
try? await Task.sleep(for: .milliseconds(100))
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
private func waitForRestoredPlayback(generation: Int) async -> Bool {
|
|
for _ in 0..<100 {
|
|
guard !Task.isCancelled, generation == handoffGeneration else { return false }
|
|
if player.playerState == .playing || player.playerState == .buffering { return true }
|
|
if player.playerState == .failed || player.playerState == .ended { return false }
|
|
try? await Task.sleep(for: .milliseconds(100))
|
|
}
|
|
return false
|
|
}
|
|
|
|
private func scheduleHandoffSave() {
|
|
guard isAuthenticated, !isApplyingHandoff, !handoffRestoreInProgress,
|
|
let currentTrack
|
|
else {
|
|
logHandoff(
|
|
"save skipped; signedIn=\(isAuthenticated), hasTrack=\(currentTrack != nil), "
|
|
+ "applyingRestore=\(isApplyingHandoff), restoring=\(handoffRestoreInProgress)"
|
|
)
|
|
return
|
|
}
|
|
if !handoffSavePending {
|
|
logHandoff("save queued; track=\(currentTrack.id), playing=\(isPlaying)")
|
|
}
|
|
handoffSavePending = true
|
|
guard !handoffSaveInFlight, handoffSaveTask == nil else { return }
|
|
handoffSaveTask = Task { [weak self] in
|
|
guard let self else { return }
|
|
await self.drainHandoffSaves()
|
|
self.handoffSaveTask = nil
|
|
if self.handoffSavePending { self.scheduleHandoffSave() }
|
|
}
|
|
}
|
|
|
|
private func drainHandoffSaves() async {
|
|
guard !handoffSaveInFlight else { return }
|
|
handoffSaveInFlight = true
|
|
defer { handoffSaveInFlight = false }
|
|
while !Task.isCancelled, handoffSavePending, isAuthenticated, !isApplyingHandoff,
|
|
!handoffRestoreInProgress, let currentTrack
|
|
{
|
|
handoffSavePending = false
|
|
logHandoff("PUT starting; track=\(currentTrack.id)")
|
|
let body = PlaybackHandoffBody(
|
|
currentTrackId: currentTrack.id,
|
|
position: max(0, elapsedTime),
|
|
queueTrackIds: player.items.compactMap { track(for: $0)?.id },
|
|
remainingTrackIds: upcomingTracks.map(\.id),
|
|
historyTrackIds: previousTracks.reversed().map(\.id),
|
|
repeatEnabled: repeatMode == .all,
|
|
repeatOnce: repeatMode == .one,
|
|
wasPlaying: isPlaying
|
|
)
|
|
do {
|
|
try Task.checkCancellation()
|
|
let response = try await api.savePlaybackHandoff(body)
|
|
handoffLastSavedAt = Date()
|
|
#if DEBUG
|
|
print("[PlayerManager] playback handoff PUT completed; saved=\(response.saved)")
|
|
#endif
|
|
} catch {
|
|
// Handoff synchronization must never interrupt playback.
|
|
logHandoff("PUT failed; \(error.localizedDescription)")
|
|
}
|
|
}
|
|
}
|
|
|
|
private func logHandoff(_ message: String) {
|
|
#if DEBUG
|
|
print("[PlayerManager] playback handoff: \(message)")
|
|
#endif
|
|
}
|
|
|
|
private func updateHandoffPositionTimer() {
|
|
guard isAuthenticated, isPlaying else {
|
|
handoffPositionTask?.cancel()
|
|
handoffPositionTask = nil
|
|
return
|
|
}
|
|
guard handoffPositionTask == nil else { return }
|
|
handoffPositionTask = Task { [weak self] in
|
|
while !Task.isCancelled {
|
|
try? await Task.sleep(for: .seconds(15))
|
|
guard let self, !Task.isCancelled else { return }
|
|
guard self.isAuthenticated, self.isPlaying else { return }
|
|
if Date().timeIntervalSince(self.handoffLastSavedAt) >= Self.handoffSyncInterval {
|
|
self.scheduleHandoffSave()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private func makeAudioItem(for track: Track) -> DefaultAudioItem? {
|
|
guard let url = apiConfiguration.audioURL(for: track) else { return nil }
|
|
let artistNames = track.artists.compactMap { reference -> String? in
|
|
guard case .value(let artist) = reference else { return nil }
|
|
return artist.name
|
|
}
|
|
let albumName: String?
|
|
if case .value(let album) = track.album {
|
|
albumName = album.name
|
|
} else {
|
|
albumName = nil
|
|
}
|
|
let item = DefaultAudioItem(
|
|
audioUrl: url.absoluteString,
|
|
artist: artistNames.joined(separator: ", "),
|
|
title: track.name,
|
|
albumTitle: albumName,
|
|
sourceType: .stream
|
|
)
|
|
tracksByItemID[ObjectIdentifier(item)] = track
|
|
return item
|
|
}
|
|
|
|
private func installEventListeners() {
|
|
player.event.stateChange.addListener(self) { [weak self] state in
|
|
Task { @MainActor [weak self] in
|
|
guard let self else { return }
|
|
let previousTrackID = self.currentTrack?.id
|
|
let wasPlaying = self.isPlaying
|
|
switch state {
|
|
case .playing:
|
|
if self.playbackIntent != false {
|
|
self.playbackIntent = nil
|
|
self.isPlaying = true
|
|
}
|
|
case .paused:
|
|
self.playbackIntent = nil
|
|
self.isPlaying = false
|
|
case .buffering:
|
|
if self.playbackIntent != false { self.isPlaying = true }
|
|
case .stopped, .idle, .failed, .ended:
|
|
self.playbackIntent = nil
|
|
self.isPlaying = false
|
|
case .loading, .ready:
|
|
break
|
|
}
|
|
self.refreshState()
|
|
if previousTrackID != self.currentTrack?.id || wasPlaying != self.isPlaying {
|
|
self.scheduleHandoffSave()
|
|
}
|
|
}
|
|
}
|
|
player.event.currentItem.addListener(self) { [weak self] _ in
|
|
Task { @MainActor [weak self] in
|
|
let previousTrackID = self?.currentTrack?.id
|
|
self?.refreshState()
|
|
self?.loadArtwork(for: self?.player.currentItem)
|
|
if previousTrackID != self?.currentTrack?.id {
|
|
self?.scheduleHandoffSave()
|
|
}
|
|
}
|
|
}
|
|
player.event.secondElapse.addListener(self) { [weak self] elapsed in
|
|
Task { @MainActor [weak self] in
|
|
self?.elapsedTime = elapsed
|
|
self?.duration = self?.player.duration ?? 0
|
|
}
|
|
}
|
|
player.event.updateDuration.addListener(self) { [weak self] duration in
|
|
Task { @MainActor [weak self] in self?.duration = duration }
|
|
}
|
|
player.event.fail.addListener(self) { [weak self] error in
|
|
Task { @MainActor [weak self] in
|
|
let wasPlaying = self?.isPlaying ?? false
|
|
self?.errorMessage = error?.localizedDescription ?? "Playback failed."
|
|
self?.isPlaying = false
|
|
self?.updateHandoffPositionTimer()
|
|
if wasPlaying { self?.scheduleHandoffSave() }
|
|
}
|
|
}
|
|
}
|
|
|
|
private func refreshState() {
|
|
currentTrack = track(for: player.currentItem)
|
|
upcomingTracks = player.nextItems.compactMap { track(for: $0) }
|
|
previousTracks = player.previousItems.compactMap { track(for: $0) }
|
|
elapsedTime = player.currentTime
|
|
duration = player.duration
|
|
isPlaying = playbackIntent ?? (player.playerState == .playing || player.playerState == .buffering)
|
|
updateHandoffPositionTimer()
|
|
}
|
|
|
|
private func track(for item: AudioItem?) -> Track? {
|
|
guard let item else { return nil }
|
|
return tracksByItemID[ObjectIdentifier(item as AnyObject)]
|
|
}
|
|
|
|
private func loadArtwork(for item: AudioItem?) {
|
|
guard let item,
|
|
let track = track(for: item),
|
|
let audioItem = item as? DefaultAudioItem,
|
|
case .value(let album) = track.album,
|
|
let url = apiConfiguration.mediaURL(for: album.file)
|
|
else { return }
|
|
|
|
Task {
|
|
guard let (data, _) = try? await URLSession.shared.data(from: url),
|
|
let image = UIImage(data: data)
|
|
else { return }
|
|
audioItem.artwork = image
|
|
guard let currentItem = player.currentItem,
|
|
ObjectIdentifier(currentItem as AnyObject) == ObjectIdentifier(item as AnyObject)
|
|
else { return }
|
|
player.loadNowPlayingMetaValues()
|
|
}
|
|
}
|
|
}
|