Add playback handoff support
This commit is contained in:
1 parent
c72596ef44
commit
77c00cc47e
5 files changed
+440
-1
No files matched your search
@@ -14,6 +14,7 @@ The iOS client is closed source for now. It targets iOS only and uses SwiftUI fo
|
||||
- **Catalog pages:** album pages show artwork, title, artists, Play and Shuffle actions, and the album’s tracks. Artist pages show artist artwork/name, Play and Shuffle actions, the artist’s tracks, and albums. A separate artist Songs page lists that artist’s tracks. Tracks link to their album and artist pages.
|
||||
- **Personal library:** tracks can be saved to and removed from the signed-in user’s Library. Library navigation has Songs, Albums, and Artists views. Songs can be played in order or shuffled and removed from the Library. The Albums and Artists lists are derived from the user’s saved tracks; they are not separately saved collections.
|
||||
- **Playback:** provide persistent playback controls for current track/artwork and artist, play/pause, previous/next, shuffle, repeat, seek with elapsed/remaining time, volume, queue access, and fullscreen player access. Track actions include playing only that track, playing next, adding to queue, saving/removing from Library, and navigating to the track’s artist or album. The queue can be reordered and tracks in it can be selected for playback. Preserve appropriate iOS background/audio-session and system media-control behavior when implementing the equivalent native experience.
|
||||
- **Playback handoff:** after authentication, restore the unexpired playback handoff only if the player is empty. Save current track, position, queue, history, repeat mode, and playing state through `/api/user/playback-handoff`; refresh position every 15 seconds while playing and save on meaningful state changes or app backgrounding. Consume the handoff only after a successful playing or paused restore, and clear it when the player is cleared. Handoff failures must not interrupt local playback.
|
||||
- **Fullscreen player and lyrics:** show artwork, track and artist, playback controls, seek and volume controls over an animated, artwork-derived color wash. Display plain lyrics when available. For synced lyrics, highlight and follow the current line and allow tapping a line to seek to its timestamp. Lyrics may be absent or unsynced.
|
||||
- **Admin catalog tools:** the web app exposes an admin-only panel with tables for genres, artists, albums, and songs, plus create/edit forms. Forms support artist artwork, album artwork/artists/genre, and song audio/artists/album plus lyrics and synced-lyrics metadata. Song creation can create a single album as part of the flow. The backend has delete APIs, but the current web table delete buttons are unimplemented; do not present deletion as an existing user-facing flow unless the web UI implements it. Keep administration restricted to admin accounts.
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import SwiftUI
|
||||
|
||||
struct ContentView: View {
|
||||
@EnvironmentObject private var player: PlayerManager
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
@StateObject private var session: AuthSessionStore
|
||||
private let restoresSession: Bool
|
||||
|
||||
@@ -28,6 +30,7 @@ struct ContentView: View {
|
||||
}
|
||||
}
|
||||
.task {
|
||||
player.setAuthenticated(session.state == .signedIn)
|
||||
guard restoresSession else { return }
|
||||
#if DEBUG
|
||||
print("[ContentView] session restore task started")
|
||||
@@ -36,6 +39,13 @@ struct ContentView: View {
|
||||
}
|
||||
#endif
|
||||
await session.restoreSession()
|
||||
player.setAuthenticated(session.state == .signedIn)
|
||||
}
|
||||
.onChange(of: session.state) { _, state in
|
||||
player.setAuthenticated(state == .signedIn)
|
||||
}
|
||||
.onChange(of: scenePhase) { _, phase in
|
||||
if phase == .background { player.saveHandoffForBackground() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,4 +100,66 @@ nonisolated public struct SearchResults: Decodable, Sendable {
|
||||
}
|
||||
nonisolated public struct TrackMembership: Decodable, Sendable { public let contains: Bool }
|
||||
|
||||
nonisolated public struct PlaybackHandoff: Decodable, Sendable {
|
||||
public let currentTrackId: String
|
||||
public let position: Double
|
||||
public let queueTrackIds: [String]
|
||||
public let remainingTrackIds: [String]
|
||||
public let historyTrackIds: [String]
|
||||
public let repeatEnabled: Bool
|
||||
public let repeatOnce: Bool
|
||||
public let wasPlaying: Bool
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case currentTrackId, position, queueTrackIds, remainingTrackIds, historyTrackIds
|
||||
case repeatEnabled = "repeat"
|
||||
case repeatOnce, wasPlaying
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated public struct PlaybackHandoffBody: Encodable, Sendable {
|
||||
public let currentTrackId: String
|
||||
public let position: Double
|
||||
public let queueTrackIds: [String]
|
||||
public let remainingTrackIds: [String]
|
||||
public let historyTrackIds: [String]
|
||||
public let repeatEnabled: Bool
|
||||
public let repeatOnce: Bool
|
||||
public let wasPlaying: Bool
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case currentTrackId, position, queueTrackIds, remainingTrackIds, historyTrackIds
|
||||
case repeatEnabled = "repeat"
|
||||
case repeatOnce, wasPlaying
|
||||
}
|
||||
|
||||
public init(
|
||||
currentTrackId: String,
|
||||
position: Double,
|
||||
queueTrackIds: [String],
|
||||
remainingTrackIds: [String],
|
||||
historyTrackIds: [String],
|
||||
repeatEnabled: Bool,
|
||||
repeatOnce: Bool,
|
||||
wasPlaying: Bool
|
||||
) {
|
||||
self.currentTrackId = currentTrackId
|
||||
self.position = position
|
||||
self.queueTrackIds = queueTrackIds
|
||||
self.remainingTrackIds = remainingTrackIds
|
||||
self.historyTrackIds = historyTrackIds
|
||||
self.repeatEnabled = repeatEnabled
|
||||
self.repeatOnce = repeatOnce
|
||||
self.wasPlaying = wasPlaying
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated public struct PlaybackHandoffSaveResponse: Decodable, Sendable {
|
||||
public let saved: Bool
|
||||
public let expiresAt: String
|
||||
}
|
||||
|
||||
nonisolated public struct PlaybackHandoffDeleteResponse: Decodable, Sendable {
|
||||
public let deleted: Bool
|
||||
}
|
||||
|
||||
nonisolated public enum SearchType: String, Sendable { case track, album, artist, `default` }
|
||||
@@ -109,6 +109,18 @@ public struct MusicAPI: Sendable {
|
||||
let _: APIClient.EmptyResponse = try await client.request(
|
||||
"DELETE", path: "user/tracks", query: ids.map { URLQueryItem(name: "ids", value: $0) })
|
||||
}
|
||||
public func playbackHandoff() async throws -> PlaybackHandoff? {
|
||||
try await client.request("GET", path: "user/playback-handoff")
|
||||
}
|
||||
@discardableResult
|
||||
public func savePlaybackHandoff(_ body: PlaybackHandoffBody) async throws
|
||||
-> PlaybackHandoffSaveResponse
|
||||
{
|
||||
try await client.request("PUT", path: "user/playback-handoff", body: body)
|
||||
}
|
||||
public func deletePlaybackHandoff() async throws -> PlaybackHandoffDeleteResponse {
|
||||
try await client.request("DELETE", path: "user/playback-handoff")
|
||||
}
|
||||
public func tracks(ids: [String]) async throws -> [Track] {
|
||||
try await client.request(
|
||||
"GET", path: "tracks", query: ids.map { URLQueryItem(name: "ids", value: $0) })
|
||||
|
||||
@@ -21,7 +21,10 @@ final class PlayerManager: ObservableObject {
|
||||
@Published private(set) var duration: TimeInterval = 0
|
||||
@Published private(set) var errorMessage: String?
|
||||
@Published var repeatMode: PlayerRepeatMode = .off {
|
||||
didSet { applyRepeatMode() }
|
||||
didSet {
|
||||
applyRepeatMode()
|
||||
scheduleHandoffSave()
|
||||
}
|
||||
}
|
||||
@Published var volume: Double {
|
||||
didSet {
|
||||
@@ -38,8 +41,20 @@ final class PlayerManager: ObservableObject {
|
||||
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()
|
||||
@@ -64,12 +79,18 @@ final class PlayerManager: ObservableObject {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
refreshState()
|
||||
updateHandoffPositionTimer()
|
||||
scheduleHandoffSave()
|
||||
}
|
||||
|
||||
func pause() {
|
||||
handoffSeekSaveTask?.cancel()
|
||||
handoffSeekSaveTask = nil
|
||||
playbackIntent = false
|
||||
isPlaying = false
|
||||
player.pause()
|
||||
updateHandoffPositionTimer()
|
||||
scheduleHandoffSave()
|
||||
}
|
||||
|
||||
func play(_ track: Track) {
|
||||
@@ -77,6 +98,9 @@ final class PlayerManager: ObservableObject {
|
||||
}
|
||||
|
||||
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]
|
||||
@@ -101,12 +125,14 @@ final class PlayerManager: ObservableObject {
|
||||
player.add(items: items, playWhenReady: true)
|
||||
refreshState()
|
||||
loadArtwork(for: player.currentItem)
|
||||
scheduleHandoffSave()
|
||||
}
|
||||
|
||||
func next() {
|
||||
player.next()
|
||||
refreshState()
|
||||
loadArtwork(for: player.currentItem)
|
||||
scheduleHandoffSave()
|
||||
}
|
||||
|
||||
func previous() {
|
||||
@@ -116,15 +142,24 @@ final class PlayerManager: ObservableObject {
|
||||
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)
|
||||
@@ -132,13 +167,16 @@ final class PlayerManager: ObservableObject {
|
||||
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 {
|
||||
@@ -147,44 +185,58 @@ final class PlayerManager: ObservableObject {
|
||||
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()
|
||||
@@ -195,6 +247,13 @@ final class PlayerManager: ObservableObject {
|
||||
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? {
|
||||
@@ -203,6 +262,7 @@ final class PlayerManager: ObservableObject {
|
||||
}
|
||||
|
||||
func shuffleUpcoming() {
|
||||
invalidatePendingHandoffRestore()
|
||||
let currentIndex = player.currentIndex
|
||||
guard currentIndex >= 0, player.items.count - currentIndex > 2 else { return }
|
||||
|
||||
@@ -218,6 +278,7 @@ final class PlayerManager: ObservableObject {
|
||||
}
|
||||
}
|
||||
refreshState()
|
||||
scheduleHandoffSave()
|
||||
}
|
||||
|
||||
func cycleRepeat() {
|
||||
@@ -236,6 +297,286 @@ final class PlayerManager: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
@@ -263,6 +604,8 @@ final class PlayerManager: ObservableObject {
|
||||
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 {
|
||||
@@ -281,12 +624,19 @@ final class PlayerManager: ObservableObject {
|
||||
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
|
||||
@@ -300,8 +650,11 @@ final class PlayerManager: ObservableObject {
|
||||
}
|
||||
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() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -313,6 +666,7 @@ final class PlayerManager: ObservableObject {
|
||||
elapsedTime = player.currentTime
|
||||
duration = player.duration
|
||||
isPlaying = playbackIntent ?? (player.playerState == .playing || player.playerState == .buffering)
|
||||
updateHandoffPositionTimer()
|
||||
}
|
||||
|
||||
private func track(for item: AudioItem?) -> Track? {
|
||||
|
||||
Reference in new issue
Block a user