85 lines
2.4 KiB
Swift
85 lines
2.4 KiB
Swift
import Foundation
|
|
|
|
public struct PlaybackSessionSnapshot: Codable, Hashable, Sendable {
|
|
public var queueTrackIDs: [String]
|
|
public var currentTrackID: String?
|
|
public var currentTime: Double
|
|
public var isShuffleEnabled: Bool
|
|
public var repeatMode: PlaybackRepeatMode
|
|
|
|
public init(
|
|
queueTrackIDs: [String] = [],
|
|
currentTrackID: String? = nil,
|
|
currentTime: Double = 0,
|
|
isShuffleEnabled: Bool = false,
|
|
repeatMode: PlaybackRepeatMode = .off
|
|
) {
|
|
self.queueTrackIDs = queueTrackIDs
|
|
self.currentTrackID = currentTrackID
|
|
self.currentTime = currentTime
|
|
self.isShuffleEnabled = isShuffleEnabled
|
|
self.repeatMode = repeatMode
|
|
}
|
|
}
|
|
|
|
public protocol PlaybackSessionStore: Sendable {
|
|
func loadSession() -> PlaybackSessionSnapshot?
|
|
func saveSession(_ session: PlaybackSessionSnapshot)
|
|
func clearSession()
|
|
}
|
|
|
|
public struct UserDefaultsPlaybackSessionStore: PlaybackSessionStore, @unchecked Sendable {
|
|
private let userDefaults: UserDefaults
|
|
private let storageKey: String
|
|
private let encoder = JSONEncoder()
|
|
private let decoder = JSONDecoder()
|
|
|
|
public init(
|
|
userDefaults: UserDefaults = .standard,
|
|
storageKey: String = "velody.playback.session"
|
|
) {
|
|
self.userDefaults = userDefaults
|
|
self.storageKey = storageKey
|
|
}
|
|
|
|
public func loadSession() -> PlaybackSessionSnapshot? {
|
|
guard let data = userDefaults.data(forKey: storageKey) else {
|
|
return nil
|
|
}
|
|
|
|
return try? decoder.decode(PlaybackSessionSnapshot.self, from: data)
|
|
}
|
|
|
|
public func saveSession(_ session: PlaybackSessionSnapshot) {
|
|
guard let data = try? encoder.encode(session) else {
|
|
return
|
|
}
|
|
|
|
userDefaults.set(data, forKey: storageKey)
|
|
}
|
|
|
|
public func clearSession() {
|
|
userDefaults.removeObject(forKey: storageKey)
|
|
}
|
|
}
|
|
|
|
public final class InMemoryPlaybackSessionStore: PlaybackSessionStore, @unchecked Sendable {
|
|
private var session: PlaybackSessionSnapshot?
|
|
|
|
public init(session: PlaybackSessionSnapshot? = nil) {
|
|
self.session = session
|
|
}
|
|
|
|
public func loadSession() -> PlaybackSessionSnapshot? {
|
|
session
|
|
}
|
|
|
|
public func saveSession(_ session: PlaybackSessionSnapshot) {
|
|
self.session = session
|
|
}
|
|
|
|
public func clearSession() {
|
|
session = nil
|
|
}
|
|
}
|