92 lines
2.9 KiB
Swift
92 lines
2.9 KiB
Swift
import Combine
|
|
import Foundation
|
|
|
|
struct HomeGenreSection: Identifiable, Sendable {
|
|
let genre: Genre
|
|
let albums: [Album]
|
|
|
|
var id: String { genre.id }
|
|
}
|
|
|
|
@MainActor
|
|
final class HomeViewModel: ObservableObject {
|
|
@Published private(set) var sections: [HomeGenreSection]
|
|
@Published private(set) var isLoading = false
|
|
@Published private(set) var errorMessage: String?
|
|
|
|
private let api: MusicAPI
|
|
private var hasLoaded: Bool
|
|
|
|
init(api: MusicAPI? = nil, previewSections: [HomeGenreSection]? = nil) {
|
|
self.api = api ?? MusicAPI()
|
|
sections = previewSections ?? []
|
|
hasLoaded = previewSections != nil
|
|
}
|
|
|
|
static var preview: HomeViewModel {
|
|
let genre = Genre(id: "genre-preview", name: "Alternative")
|
|
let artist = Artist(id: "artist-preview", name: "Example Artist", file: nil)
|
|
let albums = [
|
|
Album(
|
|
id: "album-preview-1",
|
|
name: "First Light",
|
|
artists: [.value(artist)],
|
|
file: nil,
|
|
genre: .value(genre)
|
|
),
|
|
Album(
|
|
id: "album-preview-2",
|
|
name: "After the Rain",
|
|
artists: [.value(artist)],
|
|
file: nil,
|
|
genre: .value(genre)
|
|
),
|
|
]
|
|
return HomeViewModel(previewSections: [HomeGenreSection(genre: genre, albums: albums)])
|
|
}
|
|
|
|
func load(forceRefresh: Bool = false) async {
|
|
guard !isLoading, forceRefresh || !hasLoaded else { return }
|
|
isLoading = true
|
|
errorMessage = nil
|
|
defer { isLoading = false }
|
|
|
|
do {
|
|
let genres = try await api.randomGenres()
|
|
let api = self.api
|
|
let loadedSections = await withTaskGroup(
|
|
of: (Int, HomeGenreSection?).self,
|
|
returning: [HomeGenreSection].self
|
|
) { group in
|
|
for (index, genre) in genres.enumerated() {
|
|
group.addTask {
|
|
do {
|
|
let albums = try await api.genreAlbums(id: genre.id)
|
|
guard !albums.isEmpty else { return (index, nil) }
|
|
return (index, HomeGenreSection(genre: genre, albums: albums))
|
|
} catch {
|
|
return (index, nil)
|
|
}
|
|
}
|
|
}
|
|
|
|
var results: [(Int, HomeGenreSection?)] = []
|
|
for await result in group {
|
|
results.append(result)
|
|
}
|
|
return results.sorted { $0.0 < $1.0 }.compactMap(\.1)
|
|
}
|
|
|
|
sections = loadedSections
|
|
hasLoaded = true
|
|
} catch {
|
|
errorMessage = error.localizedDescription
|
|
}
|
|
}
|
|
|
|
func artworkURL(for album: Album) -> URL? {
|
|
guard let file = album.file else { return nil }
|
|
return api.client.configuration.mediaURL(for: file)
|
|
}
|
|
}
|