Add iPhone local favorites

This commit is contained in:
diyaa
2026-05-31 13:20:07 +02:00
parent cb556ccf0a
commit 3d7252ce6d
8 changed files with 1103 additions and 14 deletions
@@ -28,10 +28,20 @@ struct iPhoneLibraryView: View {
Spacer()
if let trackID = viewModel.nowPlaying.trackID {
Button(viewModel.nowPlaying.isPlaying ? "Pause" : "Play") {
viewModel.togglePlayback(trackID: trackID)
HStack(spacing: 12) {
if viewModel.nowPlayingFavoriteTrackID == trackID {
favoriteButton(isFavorite: viewModel.isNowPlayingTrackFavorite) {
Task {
await viewModel.toggleFavorite(trackID: trackID)
}
}
}
Button(viewModel.nowPlaying.isPlaying ? "Pause" : "Play") {
viewModel.togglePlayback(trackID: trackID)
}
.buttonStyle(.borderedProminent)
}
.buttonStyle(.borderedProminent)
}
}
}
@@ -61,6 +71,12 @@ struct iPhoneLibraryView: View {
Spacer()
favoriteButton(isFavorite: track.isFavorite) {
Task {
await viewModel.toggleFavorite(trackID: track.id)
}
}
Text(track.statusText)
.font(.caption.weight(.semibold))
.padding(.horizontal, 10)
@@ -139,6 +155,12 @@ struct iPhoneLibraryView: View {
Spacer()
favoriteButton(isFavorite: track.isFavorite) {
Task {
await viewModel.toggleFavorite(trackID: track.id)
}
}
Button(track.playButtonTitle) {
viewModel.togglePlayback(trackID: track.id)
}
@@ -255,6 +277,19 @@ struct iPhoneLibraryView: View {
return .red
}
}
private func favoriteButton(
isFavorite: Bool,
action: @escaping () -> Void
) -> some View {
Button(action: action) {
Image(systemName: isFavorite ? "heart.fill" : "heart")
.font(.title3.weight(.semibold))
.foregroundStyle(isFavorite ? .red : .secondary)
}
.buttonStyle(.borderless)
.accessibilityLabel(isFavorite ? "Remove Favorite" : "Add Favorite")
}
}
private struct ArtworkThumbnailView: View {
@@ -194,16 +194,20 @@ final class iPhoneLibraryViewModel {
isPlaying: false,
errorMessage: nil
)
var nowPlayingFavoriteTrackID: String?
var isNowPlayingTrackFavorite = false
private let environment: ServerEnvironment
private let apiClient: any VelodyAPIClient
private let syncService: RemoteLibrarySyncService
private let offlineLibraryService: OfflineLibraryService
private let favoriteTrackStore: any FavoriteTrackStore
private let keychainService: any KeychainService
private let player: any iPhoneLocalAudioPlaying
private var cachedRemoteTracksByID: [String: RemoteTrack] = [:]
private var cachedRemoteLibraryTracks: [OfflineLibraryRemoteTrack] = []
private var cachedAvailableOfflineTracks: [OfflineLibraryTrack] = []
private var cachedFavoriteTrackRecordsByID: [String: FavoriteTrackRecord] = [:]
private var hasLoaded = false
var hasActiveSearch: Bool {
@@ -214,7 +218,7 @@ final class iPhoneLibraryViewModel {
!cachedRemoteLibraryTracks.isEmpty
}
init(
convenience init(
player: (any iPhoneLocalAudioPlaying)? = nil,
keychainService: any KeychainService = SystemKeychainService(
service: "de.diyaa.velody.iphone"
@@ -229,6 +233,7 @@ final class iPhoneLibraryViewModel {
let downloadStateStore = Self.makeRemoteTrackDownloadStateStore()
let audioFileStore = Self.makeOfflineAudioFileStore()
let artworkStore = Self.makeArtworkStore()
let favoriteTrackStore = Self.makeFavoriteTrackStore()
let repository = DefaultRemoteLibraryRepository(
apiClient: apiClient,
store: store
@@ -240,16 +245,38 @@ final class iPhoneLibraryViewModel {
artworkStore: artworkStore
)
self.environment = environment
self.apiClient = apiClient
self.keychainService = keychainService
self.player = player ?? iPhoneLocalAudioPlayer()
self.syncService = syncService
self.offlineLibraryService = OfflineLibraryService(
let offlineLibraryService = OfflineLibraryService(
syncService: syncService,
audioFileStore: audioFileStore,
artworkStore: artworkStore
)
self.init(
environment: environment,
apiClient: apiClient,
syncService: syncService,
offlineLibraryService: offlineLibraryService,
favoriteTrackStore: favoriteTrackStore,
player: player ?? iPhoneLocalAudioPlayer(),
keychainService: keychainService
)
}
init(
environment: ServerEnvironment,
apiClient: any VelodyAPIClient,
syncService: RemoteLibrarySyncService,
offlineLibraryService: OfflineLibraryService,
favoriteTrackStore: any FavoriteTrackStore,
player: any iPhoneLocalAudioPlaying,
keychainService: any KeychainService
) {
self.environment = environment
self.apiClient = apiClient
self.syncService = syncService
self.offlineLibraryService = offlineLibraryService
self.favoriteTrackStore = favoriteTrackStore
self.keychainService = keychainService
self.player = player
self.player.onStateChange = { [weak self] state in
self?.handleNowPlayingStateChange(state)
}
@@ -259,9 +286,20 @@ final class iPhoneLibraryViewModel {
guard !hasLoaded else { return }
hasLoaded = true
var favoriteRestoreError: Error?
do {
try await reloadFavoriteTracks()
} catch {
favoriteRestoreError = error
}
do {
let snapshot = try await reloadOfflineLibrary()
applyRestoredTracks(snapshot)
if let favoriteRestoreError {
syncStatus += " Favorites could not be restored: \(favoriteRestoreError.localizedDescription)"
}
} catch {
state = .idle
syncStatus = "Failed to load cached remote library: \(error.localizedDescription)"
@@ -354,6 +392,32 @@ final class iPhoneLibraryViewModel {
}
}
func toggleFavorite(trackID: String) async {
guard hasTrackInLibrarySnapshot(trackID) else {
return
}
let previousFavorites = cachedFavoriteTrackRecordsByID
if cachedFavoriteTrackRecordsByID[trackID] != nil {
cachedFavoriteTrackRecordsByID.removeValue(forKey: trackID)
} else {
cachedFavoriteTrackRecordsByID[trackID] = FavoriteTrackRecord(
remoteTrackId: trackID,
favoritedAt: Date()
)
}
rebuildRows()
do {
try await favoriteTrackStore.saveFavoriteTracks(Array(cachedFavoriteTrackRecordsByID.values))
} catch {
cachedFavoriteTrackRecordsByID = previousFavorites
rebuildRows()
syncStatus = "Favorite update failed: \(error.localizedDescription)"
}
}
private func currentOrRegisterDeviceID() async throws -> String {
if let existingDeviceID = try await keychainService.loadValue(
forKey: Self.deviceIDKey
@@ -430,6 +494,25 @@ final class iPhoneLibraryViewModel {
return InMemoryArtworkStore()
}
private static func makeFavoriteTrackStore() -> any FavoriteTrackStore {
if let store = try? FileFavoriteTrackStore() {
return store
}
return InMemoryFavoriteTrackStore()
}
private func reloadFavoriteTracks() async throws {
let favoriteTracks = try await favoriteTrackStore.loadFavoriteTracks()
var favoritesByTrackID: [String: FavoriteTrackRecord] = [:]
for favoriteTrack in favoriteTracks {
favoritesByTrackID[favoriteTrack.remoteTrackId] = favoriteTrack
}
cachedFavoriteTrackRecordsByID = favoritesByTrackID
}
private func reloadOfflineLibrary() async throws -> OfflineLibrarySnapshot {
let snapshot = try await offlineLibraryService.loadSnapshot()
@@ -444,6 +527,7 @@ final class iPhoneLibraryViewModel {
}
private func rebuildRows() {
let favoriteTrackIDs = Set(cachedFavoriteTrackRecordsByID.keys)
let filteredSnapshot = OfflineLibrarySnapshot(
remoteTracks: cachedRemoteLibraryTracks,
availableTracks: cachedAvailableOfflineTracks
@@ -452,15 +536,24 @@ final class iPhoneLibraryViewModel {
remoteTracks = filteredSnapshot.remoteTracks.map { track in
RemoteTrackRowViewData(
track: track,
nowPlaying: nowPlaying
nowPlaying: nowPlaying,
isFavorite: favoriteTrackIDs.contains(track.remoteTrack.trackId)
)
}
availableOfflineTracks = filteredSnapshot.availableTracks.map { track in
AvailableOfflineTrackRowViewData(
track: track,
nowPlaying: nowPlaying
nowPlaying: nowPlaying,
isFavorite: favoriteTrackIDs.contains(track.remoteTrackId)
)
}
if let trackID = nowPlaying.trackID, hasTrackInLibrarySnapshot(trackID) {
nowPlayingFavoriteTrackID = trackID
isNowPlayingTrackFavorite = favoriteTrackIDs.contains(trackID)
} else {
nowPlayingFavoriteTrackID = nil
isNowPlayingTrackFavorite = false
}
}
private func handleNowPlayingStateChange(_ state: iPhoneNowPlayingState) {
@@ -481,6 +574,10 @@ final class iPhoneLibraryViewModel {
cachedRemoteLibraryTracks[index] = transform(cachedRemoteLibraryTracks[index])
}
private func hasTrackInLibrarySnapshot(_ trackID: String) -> Bool {
cachedRemoteTracksByID[trackID] != nil
}
private func refreshOfflineLibraryInBackground() {
Task { @MainActor [weak self] in
guard let self else {
@@ -508,6 +605,7 @@ struct RemoteTrackRowViewData: Identifiable, Equatable {
let title: String
let artist: String
let durationText: String
let isFavorite: Bool
let remoteTrackID: String
let assetID: String
let status: OfflineLibraryRemoteTrackStatus
@@ -521,12 +619,14 @@ struct RemoteTrackRowViewData: Identifiable, Equatable {
init(
track: OfflineLibraryRemoteTrack,
nowPlaying: iPhoneNowPlayingState
nowPlaying: iPhoneNowPlayingState,
isFavorite: Bool
) {
id = track.remoteTrack.trackId
title = track.remoteTrack.title
artist = track.remoteTrack.artist
durationText = Self.formatDuration(seconds: track.remoteTrack.durationSeconds)
self.isFavorite = isFavorite
remoteTrackID = track.remoteTrack.trackId
assetID = track.remoteTrack.assetId
status = track.status
@@ -581,6 +681,7 @@ struct AvailableOfflineTrackRowViewData: Identifiable, Equatable {
let title: String
let artist: String
let durationText: String
let isFavorite: Bool
let remoteTrackID: String
let assetID: String
let playButtonTitle: String
@@ -588,12 +689,14 @@ struct AvailableOfflineTrackRowViewData: Identifiable, Equatable {
init(
track: OfflineLibraryTrack,
nowPlaying: iPhoneNowPlayingState
nowPlaying: iPhoneNowPlayingState,
isFavorite: Bool
) {
id = track.remoteTrackId
title = track.title
artist = track.artist
durationText = RemoteTrackRowViewData.formatDuration(seconds: track.durationSeconds)
self.isFavorite = isFavorite
remoteTrackID = track.remoteTrackId
assetID = track.assetId
playButtonTitle = nowPlaying.trackID == track.remoteTrackId && nowPlaying.isPlaying