diff --git a/Music/API/APIClient.swift b/Music/API/APIClient.swift index 0f40739..805eee8 100644 --- a/Music/API/APIClient.swift +++ b/Music/API/APIClient.swift @@ -10,14 +10,19 @@ public struct APIConfiguration: Sendable { mediaBaseURL: URL? = nil ) { self.apiBaseURL = apiBaseURL - self.mediaBaseURL = mediaBaseURL ?? URL(string: "/", relativeTo: apiBaseURL)!.absoluteURL + self.mediaBaseURL = mediaBaseURL ?? URL(string: "https://s3-seaweedfs.lucasskt.dk/music/")! } public func mediaURL(for path: String) -> URL? { if let url = URL(string: path), url.scheme != nil { return url } + let directoryURL = + mediaBaseURL.absoluteString.hasSuffix("/") + ? mediaBaseURL + : URL(string: mediaBaseURL.absoluteString + "/")! return URL( string: path.trimmingCharacters(in: CharacterSet(charactersIn: "/")), - relativeTo: mediaBaseURL)?.absoluteURL + relativeTo: directoryURL + )?.absoluteURL } public func audioURL(for track: Track) -> URL? { diff --git a/Music/Auth/AuthSessionStore.swift b/Music/Auth/AuthSessionStore.swift index 7354f4e..3e54bee 100644 --- a/Music/Auth/AuthSessionStore.swift +++ b/Music/Auth/AuthSessionStore.swift @@ -13,6 +13,10 @@ final class AuthSessionStore: ObservableObject { private let api = MusicAPI() + init(initialState: State = .checking) { + state = initialState + } + func restoreSession() async { guard state == .checking else { return } diff --git a/Music/ContentView.swift b/Music/ContentView.swift index c74c743..d6e62a8 100644 --- a/Music/ContentView.swift +++ b/Music/ContentView.swift @@ -2,6 +2,12 @@ import SwiftUI struct ContentView: View { @StateObject private var session = AuthSessionStore() + private let restoresSession: Bool + + @MainActor init(session: AuthSessionStore? = nil, restoresSession: Bool = true) { + _session = StateObject(wrappedValue: session ?? AuthSessionStore()) + self.restoresSession = restoresSession + } var body: some View { Group { @@ -15,16 +21,11 @@ struct ContentView: View { case .signedOut: SignInView(session: session) case .signedIn: - VStack(spacing: 12) { - Image(systemName: "music.note.list") - .imageScale(.large) - .foregroundStyle(.tint) - Text("Hello, world!") - } - .padding() + MainTabView() } } .task { + guard restoresSession else { return } await session.restoreSession() } } @@ -32,6 +33,9 @@ struct ContentView: View { struct ContentView_Previews: PreviewProvider { static var previews: some View { - ContentView() + ContentView( + session: AuthSessionStore(initialState: .signedOut), + restoresSession: false + ) } } diff --git a/Music/Home/HomeView.swift b/Music/Home/HomeView.swift new file mode 100644 index 0000000..5de54e1 --- /dev/null +++ b/Music/Home/HomeView.swift @@ -0,0 +1,172 @@ +import SwiftUI + +struct HomeView: View { + @StateObject private var viewModel: HomeViewModel + + init(viewModel: HomeViewModel? = nil) { + _viewModel = StateObject(wrappedValue: viewModel ?? HomeViewModel()) + } + + var body: some View { + NavigationStack { + ScrollView { + Group { + if viewModel.sections.isEmpty, viewModel.isLoading { + ProgressView() + .tint(.red) + .frame(maxWidth: .infinity) + .padding(.top, 72) + } else if viewModel.sections.isEmpty, let errorMessage = viewModel.errorMessage + { + ContentUnavailableView { + Label("Couldn't Load Home", systemImage: "wifi.exclamationmark") + } description: { + Text(errorMessage) + } actions: { + Button("Try Again") { + Task { await viewModel.load(forceRefresh: true) } + } + .tint(.red) + } + .padding(.top, 48) + } else if viewModel.sections.isEmpty { + ContentUnavailableView( + "No Albums Yet", + systemImage: "square.stack", + description: Text("There are no albums to show right now.") + ) + .padding(.top, 48) + } else { + LazyVStack(alignment: .leading, spacing: 26) { + ForEach(viewModel.sections) { section in + HomeAlbumCarousel(section: section) { album in + viewModel.artworkURL(for: album) + } + } + } + .padding(.vertical, 20) + } + } + } + .scrollIndicators(.hidden) + .refreshable { + await viewModel.load(forceRefresh: true) + } + .navigationTitle("Home") + .navigationBarTitleDisplayMode(.large) + .tint(.red) + } + .task { + await viewModel.load() + } + } +} + +private struct HomeAlbumCarousel: View { + let section: HomeGenreSection + let artworkURL: (Album) -> URL? + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + Text(section.genre.name) + .font(.title3.weight(.semibold)) + .padding(.horizontal, 20) + + ScrollView(.horizontal) { + LazyHStack(alignment: .top, spacing: 14) { + ForEach(section.albums) { album in + HomeAlbumCard(album: album, artworkURL: artworkURL(album)) + .containerRelativeFrame(.horizontal) { length, _ in + (length - 40 - 28) / 2.2 + } + } + } + .scrollTargetLayout() + .padding(.horizontal, 20) + } + .scrollIndicators(.hidden) + .scrollTargetBehavior(.viewAligned) + } + } +} + +private struct HomeAlbumCarousel_Previews: PreviewProvider { + static var previews: some View { + HomeAlbumCarousel(section: HomeViewModel.preview.sections[0]) { _ in nil } + .padding(.vertical, 24) + } +} + +private struct HomeAlbumCard: View { + let album: Album + let artworkURL: URL? + + private var artistNames: String { + album.artists.compactMap { reference in + guard case .value(let artist) = reference else { return nil } + return artist.name + } + .joined(separator: ", ") + } + + var body: some View { + VStack(alignment: .leading, spacing: 5) { + AsyncImage(url: artworkURL) { phase in + switch phase { + case .success(let image): + image + .resizable() + .scaledToFill() + case .empty: + ProgressView() + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(.quaternary) + case .failure: + artworkPlaceholder + @unknown default: + artworkPlaceholder + } + } + .aspectRatio(1, contentMode: .fit) + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + + Text(album.name) + .font(.subheadline.weight(.medium)) + .lineLimit(2) + .foregroundStyle(.primary) + + if !artistNames.isEmpty { + Text(artistNames) + .font(.footnote) + .lineLimit(1) + .foregroundStyle(.secondary) + } + } + .accessibilityElement(children: .combine) + } + + private var artworkPlaceholder: some View { + Image(systemName: "music.note") + .font(.largeTitle) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(.quaternary) + } +} + +private struct HomeAlbumCard_Previews: PreviewProvider { + static var previews: some View { + HomeAlbumCard( + album: HomeViewModel.preview.sections[0].albums[0], + artworkURL: nil + ) + .padding() + .frame(maxWidth: 240) + } +} + +struct HomeView_Previews: PreviewProvider { + static var previews: some View { + HomeView(viewModel: .preview) + } +} diff --git a/Music/Home/HomeViewModel.swift b/Music/Home/HomeViewModel.swift new file mode 100644 index 0000000..71e77d5 --- /dev/null +++ b/Music/Home/HomeViewModel.swift @@ -0,0 +1,91 @@ +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) + } +} diff --git a/Music/MainTabView.swift b/Music/MainTabView.swift new file mode 100644 index 0000000..10b6efc --- /dev/null +++ b/Music/MainTabView.swift @@ -0,0 +1,66 @@ +import SwiftUI + +struct MainTabView: View { + var body: some View { + TabView { + Tab("Home", systemImage: "house") { + HomeView() + } + + Tab("Library", systemImage: "books.vertical") { + LibraryTabView() + } + + Tab("Search", systemImage: "magnifyingglass", role: .search) { + SearchTabView() + } + } + .tint(.red) + } +} + +private struct LibraryTabView: View { + var body: some View { + NavigationStack { + ContentUnavailableView( + "Your Library", + systemImage: "books.vertical", + description: Text("Your saved songs will appear here.") + ) + .navigationTitle("Library") + .navigationBarTitleDisplayMode(.large) + } + } +} + +private struct SearchTabView: View { + var body: some View { + NavigationStack { + ContentUnavailableView( + "Search Music", + systemImage: "magnifyingglass", + description: Text("Search for songs, albums, and artists.") + ) + .navigationTitle("Search") + .navigationBarTitleDisplayMode(.large) + } + } +} + +struct MainTabView_Previews: PreviewProvider { + static var previews: some View { + MainTabView() + } +} + +private struct LibraryTabView_Previews: PreviewProvider { + static var previews: some View { + LibraryTabView() + } +} + +private struct SearchTabView_Previews: PreviewProvider { + static var previews: some View { + SearchTabView() + } +}