diff --git a/.swift-format b/.swift-format new file mode 100644 index 0000000..93eda1a --- /dev/null +++ b/.swift-format @@ -0,0 +1,75 @@ +{ + "fileScopedDeclarationPrivacy": { + "accessLevel": "private" + }, + "indentConditionalCompilationBlocks": true, + "indentSwitchCaseLabels": false, + "indentation": { + "spaces": 4 + }, + "lineBreakAroundMultilineExpressionChainComponents": false, + "lineBreakBeforeControlFlowKeywords": false, + "lineBreakBeforeEachArgument": false, + "lineBreakBeforeEachGenericRequirement": false, + "lineBreakBetweenDeclarationAttributes": false, + "lineLength": 100, + "maximumBlankLines": 1, + "multiElementCollectionTrailingCommas": true, + "noAssignmentInExpressions": { + "allowedFunctions": [ + "XCTAssertNoThrow" + ] + }, + "prioritizeKeepingFunctionOutputTogether": false, + "reflowMultilineStringLiterals": "never", + "respectsExistingLineBreaks": true, + "rules": { + "AllPublicDeclarationsHaveDocumentation": false, + "AlwaysUseLiteralForEmptyCollectionInit": false, + "AlwaysUseLowerCamelCase": true, + "AmbiguousTrailingClosureOverload": true, + "AvoidRetroactiveConformances": true, + "BeginDocumentationCommentWithOneLineSummary": false, + "DoNotUseSemicolons": true, + "DontRepeatTypeInStaticProperties": true, + "FileScopedDeclarationPrivacy": true, + "FullyIndirectEnum": true, + "GroupNumericLiterals": true, + "IdentifiersMustBeASCII": true, + "NeverForceUnwrap": false, + "NeverUseForceTry": false, + "NeverUseImplicitlyUnwrappedOptionals": false, + "NoAccessLevelOnExtensionDeclaration": true, + "NoAssignmentInExpressions": true, + "NoBlockComments": true, + "NoCasesWithOnlyFallthrough": true, + "NoEmptyLinesOpeningClosingBraces": false, + "NoEmptyTrailingClosureParentheses": true, + "NoLabelsInCasePatterns": true, + "NoLeadingUnderscores": false, + "NoParensAroundConditions": true, + "NoPlaygroundLiterals": true, + "NoVoidReturnOnFunctionSignature": true, + "OmitExplicitReturns": false, + "OneCasePerLine": true, + "OneVariableDeclarationPerLine": true, + "OnlyOneTrailingClosureArgument": true, + "OrderedImports": true, + "ReplaceForEachWithForLoop": true, + "ReturnVoidInsteadOfEmptyTuple": true, + "TypeNamesShouldBeCapitalized": true, + "UseEarlyExits": false, + "UseExplicitNilCheckInConditions": true, + "UseLetInEveryBoundCaseVariable": true, + "UseShorthandTypeNames": true, + "UseSingleLinePropertyGetter": true, + "UseSynthesizedInitializer": true, + "UseTripleSlashForDocumentationComments": true, + "UseWhereClausesInForLoops": false, + "ValidateDocumentationComments": false + }, + "spacesAroundRangeFormationOperators": false, + "spacesBeforeEndOfLineComments": 2, + "tabWidth": 4, + "version": 1 +} diff --git a/Music/AGENTS.md b/Music/AGENTS.md index 137cb1d..cac4acf 100644 --- a/Music/AGENTS.md +++ b/Music/AGENTS.md @@ -37,6 +37,7 @@ The iOS app should feel native to iOS and use an Apple Music-inspired **liquid g ## Working principles - The user directs product decisions; keep implementation clear and maintainable, with comments where they clarify non-obvious behavior. +- Before completing code changes, run available linting and type checking or a build for the affected code. Fix errors introduced by the change, and clearly report any unrelated baseline or environment failures that prevent a clean check. - Reuse the web app’s backend API and data model. Inspect `~/music-v2` when route behavior, authentication, content fields, or feature scope is unclear. - Match the web version’s structure and scope, while making the experience idiomatic to SwiftUI and iOS. - Update this document when the web app’s features, flows, design direction, or technical scope changes. Flag uncertainty for review instead of silently adding new product behavior. diff --git a/Music/API/APIClient.swift b/Music/API/APIClient.swift index 3691e0b..0f40739 100644 --- a/Music/API/APIClient.swift +++ b/Music/API/APIClient.swift @@ -15,11 +15,15 @@ public struct APIConfiguration: Sendable { public func mediaURL(for path: String) -> URL? { if let url = URL(string: path), url.scheme != nil { return url } - return URL(string: path.trimmingCharacters(in: CharacterSet(charactersIn: "/")), relativeTo: mediaBaseURL)?.absoluteURL + return URL( + string: path.trimmingCharacters(in: CharacterSet(charactersIn: "/")), + relativeTo: mediaBaseURL)?.absoluteURL } public func audioURL(for track: Track) -> URL? { - mediaURL(for: "\(track.fileDir.trimmingCharacters(in: CharacterSet(charactersIn: "/")))/high.m4a") + mediaURL( + for: "\(track.fileDir.trimmingCharacters(in: CharacterSet(charactersIn: "/")))/high.m4a" + ) } } @@ -34,9 +38,9 @@ public enum APIError: Error, LocalizedError, Sendable { switch self { case .invalidURL: "The API URL is invalid." case .nonHTTPResponse: "The server returned an invalid response." - case let .http(status, message): message ?? "The server returned HTTP \(status)." - case let .decoding(message): "Could not read the server response: \(message)" - case let .transport(message): message + case .http(let status, let message): message ?? "The server returned HTTP \(status)." + case .decoding(let message): "Could not read the server response: \(message)" + case .transport(let message): message } } } @@ -70,7 +74,9 @@ public final class APIClient: @unchecked Sendable { body: Body? = nil, response: Response.Type = Response.self ) async throws -> Response { - try await perform(method, path: path, query: query, body: body, response: response, refreshAfterUnauthorized: true) + try await perform( + method, path: path, query: query, body: body, response: response, + refreshAfterUnauthorized: true) } private func perform( @@ -81,7 +87,10 @@ public final class APIClient: @unchecked Sendable { response: Response.Type, refreshAfterUnauthorized: Bool ) async throws -> Response { - guard var components = URLComponents(url: configuration.apiBaseURL.appending(path: path), resolvingAgainstBaseURL: false) else { + guard + var components = URLComponents( + url: configuration.apiBaseURL.appending(path: path), resolvingAgainstBaseURL: false) + else { throw APIError.invalidURL } if !query.isEmpty { components.queryItems = query } @@ -89,7 +98,9 @@ public final class APIClient: @unchecked Sendable { var request = URLRequest(url: url) request.httpMethod = method request.setValue("application/json", forHTTPHeaderField: "Accept") - if let origin = URLComponents(url: configuration.apiBaseURL, resolvingAgainstBaseURL: false)?.url?.origin { + if let origin = URLComponents( + url: configuration.apiBaseURL, resolvingAgainstBaseURL: false)?.url?.origin + { request.setValue(origin, forHTTPHeaderField: "Origin") } if let body { @@ -100,7 +111,9 @@ public final class APIClient: @unchecked Sendable { let (data, rawResponse) = try await session.data(for: request) guard let http = rawResponse as? HTTPURLResponse else { throw APIError.nonHTTPResponse } guard (200..<300).contains(http.statusCode) else { - let message = (try? JSONSerialization.jsonObject(with: data) as? [String: Any])?["message"] as? String + let message = + (try? JSONSerialization.jsonObject(with: data) as? [String: Any])?["message"] + as? String if http.statusCode == 401, refreshAfterUnauthorized, !path.hasPrefix("auth/") { let status: SessionStatus = try await perform( "GET", @@ -123,28 +136,42 @@ public final class APIClient: @unchecked Sendable { } throw APIError.http(status: http.statusCode, message: message) } - if Response.self == EmptyResponse.self, let empty = EmptyResponse() as? Response { return empty } + if Response.self == EmptyResponse.self, let empty = EmptyResponse() as? Response { + return empty + } do { // The lyrics handler intentionally sends no body when lyrics are absent. - let isOptionalResponse = String(reflecting: Response.self).hasPrefix("Swift.Optional<") - if isOptionalResponse, data.isEmpty || (try? JSONSerialization.jsonObject(with: data) as? [String: Any])?.isEmpty == true { + let isOptionalResponse = String(reflecting: Response.self).hasPrefix( + "Swift.Optional<") + if isOptionalResponse, + data.isEmpty + || (try? JSONSerialization.jsonObject(with: data) as? [String: Any])? + .isEmpty == true + { return try decoder.decode(Response.self, from: Data("null".utf8)) } return try decoder.decode(Response.self, from: data) - } - catch { throw APIError.decoding(error.localizedDescription) } - } catch let error as APIError { throw error } - catch { throw APIError.transport(error.localizedDescription) } + } catch { throw APIError.decoding(error.localizedDescription) } + } catch let error as APIError { throw error } catch { + throw APIError.transport(error.localizedDescription) + } } public func request( - _ method: String, path: String, query: [URLQueryItem] = [], response: Response.Type = Response.self + _ method: String, path: String, query: [URLQueryItem] = [], + response: Response.Type = Response.self ) async throws -> Response { - try await request(method, path: path, query: query, body: Optional.none, response: response) + try await request( + method, path: path, query: query, body: Optional.none, response: response) } - private struct EmptyBody: Encodable, Sendable {} - public struct EmptyResponse: Decodable, Sendable { public init() {} } + nonisolated private struct EmptyBody: Encodable, Sendable {} + nonisolated public struct EmptyResponse: Decodable, Sendable { public init() {} } } -private extension URL { var origin: String? { guard let scheme, let host else { return nil }; return "\(scheme)://\(host)" + (port.map { ":\($0)" } ?? "") } } +extension URL { + fileprivate var origin: String? { + guard let scheme, let host else { return nil } + return "\(scheme)://\(host)" + (port.map { ":\($0)" } ?? "") + } +} diff --git a/Music/API/Models.swift b/Music/API/Models.swift index c1f1dc6..169dc18 100644 --- a/Music/API/Models.swift +++ b/Music/API/Models.swift @@ -19,13 +19,19 @@ nonisolated public struct Artist: Decodable, Identifiable, Sendable { public let id: String public let name: String public let file: String? - enum CodingKeys: String, CodingKey { case id = "_id", name, file } + enum CodingKeys: String, CodingKey { + case id = "_id" + case name, file + } } nonisolated public struct Genre: Decodable, Identifiable, Sendable { public let id: String public let name: String - enum CodingKeys: String, CodingKey { case id = "_id", name } + enum CodingKeys: String, CodingKey { + case id = "_id" + case name + } } nonisolated public struct Album: Decodable, Identifiable, Sendable { @@ -34,7 +40,10 @@ nonisolated public struct Album: Decodable, Identifiable, Sendable { public let artists: [APIReference] public let file: String? public let genre: APIReference? - enum CodingKeys: String, CodingKey { case id = "_id", name, artists, file, genre } + enum CodingKeys: String, CodingKey { + case id = "_id" + case name, artists, file, genre + } } nonisolated public struct Lyrics: Decodable, Sendable { @@ -51,7 +60,8 @@ nonisolated public struct Track: Decodable, Identifiable, Sendable { public let durationInSeconds: Double public let lyrics: Lyrics? enum CodingKeys: String, CodingKey { - case id = "_id", name, album, artists, fileDir, durationInSeconds, lyrics + case id = "_id" + case name, album, artists, fileDir, durationInSeconds, lyrics } } @@ -61,7 +71,10 @@ nonisolated public struct User: Decodable, Identifiable, Sendable { public let email: String public let role: String public let savedTracks: [String]? - enum CodingKeys: String, CodingKey { case id = "_id", name, email, role, savedTracks } + enum CodingKeys: String, CodingKey { + case id = "_id" + case name, email, role, savedTracks + } } nonisolated public struct SessionStatus: Decodable, Sendable { public let authenticated: Bool } diff --git a/Music/API/MusicAPI.swift b/Music/API/MusicAPI.swift index a7c80d6..68a378d 100644 --- a/Music/API/MusicAPI.swift +++ b/Music/API/MusicAPI.swift @@ -12,44 +12,116 @@ public struct MusicAPI: Sendable { } public func signIn(email: String, password: String) async throws { - let _: APIClient.EmptyResponse = try await client.request("POST", path: "auth/signin", body: Credentials(email: email, password: password)) + let _: APIClient.EmptyResponse = try await client.request( + "POST", path: "auth/signin", body: Credentials(email: email, password: password)) guard try await sessionStatus().authenticated else { - throw APIError.http(status: 401, message: "The server did not establish an authenticated session.") + throw APIError.http( + status: 401, message: "The server did not establish an authenticated session.") } } - public func sessionStatus() async throws -> SessionStatus { try await client.request("GET", path: "auth/session") } - public func renewSession() async throws -> Session { try await client.request("POST", path: "auth/session") } - public func signOut() async throws -> SignOutResponse { try await client.request("POST", path: "auth/signout") } + public func sessionStatus() async throws -> SessionStatus { + try await client.request("GET", path: "auth/session") + } + public func renewSession() async throws -> Session { + try await client.request("POST", path: "auth/session") + } + public func signOut() async throws -> SignOutResponse { + try await client.request("POST", path: "auth/signout") + } public func currentUser() async throws -> User { try await client.request("GET", path: "user") } - public func search(_ query: String, type: SearchType = .default, limit: Int? = nil) async throws -> SearchResults { - try await client.request("GET", path: "search", query: q([("q", query), ("type", type.rawValue), ("limit", limit.map(String.init))])) + public func search(_ query: String, type: SearchType = .default, limit: Int? = nil) async throws + -> SearchResults + { + try await client.request( + "GET", path: "search", + query: q([("q", query), ("type", type.rawValue), ("limit", limit.map(String.init))])) + } + public func randomGenres(limit: Int? = nil) async throws -> [Genre] { + try await client.request( + "GET", path: "genres/random", query: q([("limit", limit.map(String.init))])) + } + public func album(id: String) async throws -> Album? { + try await client.request("GET", path: "albums/\(id)") + } + public func artist(id: String) async throws -> Artist? { + try await client.request("GET", path: "artists/\(id)") + } + public func track(id: String) async throws -> Track? { + try await client.request("GET", path: "tracks/\(id)") + } + public func lyrics(trackID: String) async throws -> Lyrics? { + try await client.request("GET", path: "tracks/\(trackID)/lyrics") + } + public func albumTracks(id: String, limit: Int? = nil, skip: Int? = nil) async throws -> [Track] + { try await client.request("GET", path: "albums/\(id)/tracks", query: page(limit, skip)) } + public func artistTracks(id: String, limit: Int? = nil, skip: Int? = nil) async throws + -> [Track] + { try await client.request("GET", path: "artists/\(id)/tracks", query: page(limit, skip)) } + public func artistAlbums(id: String, limit: Int? = nil, skip: Int? = nil) async throws + -> [Album] + { try await client.request("GET", path: "artists/\(id)/albums", query: page(limit, skip)) } + public func genreAlbums(id: String, limit: Int? = nil, skip: Int? = nil) async throws -> [Album] + { try await client.request("GET", path: "genres/albums/\(id)", query: page(limit, skip)) } + public func genreTracks(id: String, limit: Int? = nil, skip: Int? = nil) async throws -> [Track] + { try await client.request("GET", path: "genres/tracks/\(id)", query: page(limit, skip)) } + public func allAlbums() async throws -> [Album] { + try await client.request("GET", path: "all/albums") + } + public func allArtists() async throws -> [Artist] { + try await client.request("GET", path: "all/artists") + } + public func allGenres() async throws -> [Genre] { + try await client.request("GET", path: "all/genres") + } + public func allTracks() async throws -> [Track] { + try await client.request("GET", path: "all/tracks") + } + public func savedTracks() async throws -> [Track] { + try await client.request("GET", path: "user/tracks") + } + public func savedAlbums() async throws -> [Album] { + try await client.request("GET", path: "user/albums") + } + public func savedArtists() async throws -> [Artist] { + try await client.request("GET", path: "user/artists") + } + public func isTrackSaved(id: String) async throws -> Bool { + let membership: TrackMembership = try await client.request( + "GET", + path: "user/tracks/contains", + query: q([("id", id)]) + ) + return membership.contains + } + public func saveTrack(id: String) async throws { + let _: APIClient.EmptyResponse = try await client.request( + "PATCH", path: "user/tracks", query: q([("id", id)])) + } + public func removeTrack(id: String) async throws { + let _: APIClient.EmptyResponse = try await client.request( + "DELETE", path: "user/tracks", query: q([("id", id)])) + } + public func removeTracks(ids: [String]) async throws { + let _: APIClient.EmptyResponse = try await client.request( + "DELETE", path: "user/tracks", query: ids.map { URLQueryItem(name: "ids", value: $0) }) + } + public func tracks(ids: [String]) async throws -> [Track] { + try await client.request( + "GET", path: "tracks", query: ids.map { URLQueryItem(name: "ids", value: $0) }) + } + public func albums(ids: [String]) async throws -> [Album] { + try await client.request( + "GET", path: "albums", query: ids.map { URLQueryItem(name: "ids", value: $0) }) + } + public func artists(ids: [String]) async throws -> [Artist] { + try await client.request( + "GET", path: "artists", query: ids.map { URLQueryItem(name: "ids", value: $0) }) } - public func randomGenres(limit: Int? = nil) async throws -> [Genre] { try await client.request("GET", path: "genres/random", query: q([("limit", limit.map(String.init))])) } - public func album(id: String) async throws -> Album? { try await client.request("GET", path: "albums/\(id)") } - public func artist(id: String) async throws -> Artist? { try await client.request("GET", path: "artists/\(id)") } - public func track(id: String) async throws -> Track? { try await client.request("GET", path: "tracks/\(id)") } - public func lyrics(trackID: String) async throws -> Lyrics? { try await client.request("GET", path: "tracks/\(trackID)/lyrics") } - public func albumTracks(id: String, limit: Int? = nil, skip: Int? = nil) async throws -> [Track] { try await client.request("GET", path: "albums/\(id)/tracks", query: page(limit, skip)) } - public func artistTracks(id: String, limit: Int? = nil, skip: Int? = nil) async throws -> [Track] { try await client.request("GET", path: "artists/\(id)/tracks", query: page(limit, skip)) } - public func artistAlbums(id: String, limit: Int? = nil, skip: Int? = nil) async throws -> [Album] { try await client.request("GET", path: "artists/\(id)/albums", query: page(limit, skip)) } - public func genreAlbums(id: String, limit: Int? = nil, skip: Int? = nil) async throws -> [Album] { try await client.request("GET", path: "genres/albums/\(id)", query: page(limit, skip)) } - public func genreTracks(id: String, limit: Int? = nil, skip: Int? = nil) async throws -> [Track] { try await client.request("GET", path: "genres/tracks/\(id)", query: page(limit, skip)) } - public func allAlbums() async throws -> [Album] { try await client.request("GET", path: "all/albums") } - public func allArtists() async throws -> [Artist] { try await client.request("GET", path: "all/artists") } - public func allGenres() async throws -> [Genre] { try await client.request("GET", path: "all/genres") } - public func allTracks() async throws -> [Track] { try await client.request("GET", path: "all/tracks") } - public func savedTracks() async throws -> [Track] { try await client.request("GET", path: "user/tracks") } - public func savedAlbums() async throws -> [Album] { try await client.request("GET", path: "user/albums") } - public func savedArtists() async throws -> [Artist] { try await client.request("GET", path: "user/artists") } - public func isTrackSaved(id: String) async throws -> Bool { try await client.request("GET", path: "user/tracks/contains", query: q([("id", id)])).contains } - public func saveTrack(id: String) async throws { let _: APIClient.EmptyResponse = try await client.request("PATCH", path: "user/tracks", query: q([("id", id)])) } - public func removeTrack(id: String) async throws { let _: APIClient.EmptyResponse = try await client.request("DELETE", path: "user/tracks", query: q([("id", id)])) } - public func removeTracks(ids: [String]) async throws { let _: APIClient.EmptyResponse = try await client.request("DELETE", path: "user/tracks", query: ids.map { URLQueryItem(name: "ids", value: $0) }) } - public func tracks(ids: [String]) async throws -> [Track] { try await client.request("GET", path: "tracks", query: ids.map { URLQueryItem(name: "ids", value: $0) }) } - public func albums(ids: [String]) async throws -> [Album] { try await client.request("GET", path: "albums", query: ids.map { URLQueryItem(name: "ids", value: $0) }) } - public func artists(ids: [String]) async throws -> [Artist] { try await client.request("GET", path: "artists", query: ids.map { URLQueryItem(name: "ids", value: $0) }) } } -private struct Credentials: Encodable, Sendable { let email: String; let password: String } -public struct SignOutResponse: Decodable, Sendable { public let success: Bool? } +nonisolated private struct Credentials: Encodable, Sendable { + let email: String + let password: String +} +nonisolated public struct SignOutResponse: Decodable, Sendable { public let success: Bool? }