Organize views and utilities
This commit is contained in:
1 parent
9e82949c1d
commit
7ce0827c9a
15 files changed
+5
No files matched your search
@@ -0,0 +1,207 @@
|
||||
import Foundation
|
||||
|
||||
public struct APIConfiguration: Sendable {
|
||||
public let apiBaseURL: URL
|
||||
/// Object storage may use a different host from the JSON API. Defaults to the API origin.
|
||||
public let mediaBaseURL: URL
|
||||
|
||||
public init(
|
||||
apiBaseURL: URL = URL(string: "https://music.lucasskt.dk/api")!,
|
||||
mediaBaseURL: URL? = nil
|
||||
) {
|
||||
self.apiBaseURL = apiBaseURL
|
||||
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: directoryURL
|
||||
)?.absoluteURL
|
||||
}
|
||||
|
||||
public func audioURL(for track: Track) -> URL? {
|
||||
mediaURL(
|
||||
for: "\(track.fileDir.trimmingCharacters(in: CharacterSet(charactersIn: "/")))/high.m4a"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
public enum APIError: Error, LocalizedError, Sendable {
|
||||
case invalidURL
|
||||
case nonHTTPResponse
|
||||
case http(status: Int, message: String?)
|
||||
case decoding(String)
|
||||
case transport(String)
|
||||
|
||||
public var errorDescription: String? {
|
||||
switch self {
|
||||
case .invalidURL: "The API URL is invalid."
|
||||
case .nonHTTPResponse: "The server returned an invalid response."
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public final class APIClient: @unchecked Sendable {
|
||||
public let configuration: APIConfiguration
|
||||
private let session: URLSession
|
||||
private let decoder: JSONDecoder
|
||||
|
||||
public init(configuration: APIConfiguration = APIConfiguration(), session: URLSession? = nil) {
|
||||
self.configuration = configuration
|
||||
if let session {
|
||||
self.session = session
|
||||
} else {
|
||||
let config = URLSessionConfiguration.default
|
||||
config.httpCookieStorage = .shared
|
||||
config.httpCookieAcceptPolicy = .always
|
||||
config.httpShouldSetCookies = true
|
||||
self.session = URLSession(configuration: config)
|
||||
}
|
||||
if let cookieStorage = self.session.configuration.httpCookieStorage {
|
||||
AuthCookiePersistence.restore(into: cookieStorage, for: configuration.apiBaseURL)
|
||||
}
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .iso8601
|
||||
self.decoder = decoder
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
public func request<Response: Decodable & Sendable, Body: Encodable & Sendable>(
|
||||
_ method: String,
|
||||
path: String,
|
||||
query: [URLQueryItem] = [],
|
||||
body: Body? = nil,
|
||||
response: Response.Type = Response.self
|
||||
) async throws -> Response {
|
||||
do {
|
||||
return try await perform(
|
||||
method, path: path, query: query, body: body, response: response,
|
||||
refreshAfterUnauthorized: true)
|
||||
} catch {
|
||||
print("[APIClient] \(method) \(path) failed: \(error.localizedDescription)")
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private func perform<Response: Decodable & Sendable, Body: Encodable & Sendable>(
|
||||
_ method: String,
|
||||
path: String,
|
||||
query: [URLQueryItem],
|
||||
body: Body?,
|
||||
response: Response.Type,
|
||||
refreshAfterUnauthorized: Bool
|
||||
) async throws -> Response {
|
||||
guard
|
||||
var components = URLComponents(
|
||||
url: configuration.apiBaseURL.appending(path: path), resolvingAgainstBaseURL: false)
|
||||
else {
|
||||
throw APIError.invalidURL
|
||||
}
|
||||
if !query.isEmpty { components.queryItems = query }
|
||||
guard let url = components.url else { throw APIError.invalidURL }
|
||||
if let cookieStorage = session.configuration.httpCookieStorage {
|
||||
AuthCookiePersistence.restore(into: cookieStorage, for: url)
|
||||
if path.hasPrefix("auth/") {
|
||||
AuthCookiePersistence.logRequestCookies(from: cookieStorage, for: url, phase: "before \(path)")
|
||||
}
|
||||
}
|
||||
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
|
||||
{
|
||||
request.setValue(origin, forHTTPHeaderField: "Origin")
|
||||
}
|
||||
if let body {
|
||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
request.httpBody = try JSONEncoder().encode(body)
|
||||
}
|
||||
do {
|
||||
let (data, rawResponse) = try await session.data(for: request)
|
||||
if let cookieStorage = session.configuration.httpCookieStorage {
|
||||
AuthCookiePersistence.save(from: cookieStorage, for: url)
|
||||
if path.hasPrefix("auth/") {
|
||||
AuthCookiePersistence.logRequestCookies(from: cookieStorage, for: url, phase: "after \(path)")
|
||||
}
|
||||
}
|
||||
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
|
||||
if http.statusCode == 401, refreshAfterUnauthorized, !path.hasPrefix("auth/") {
|
||||
let status: SessionStatus = try await perform(
|
||||
"GET",
|
||||
path: "auth/session",
|
||||
query: [],
|
||||
body: Optional<EmptyBody>.none,
|
||||
response: SessionStatus.self,
|
||||
refreshAfterUnauthorized: false
|
||||
)
|
||||
if status.authenticated {
|
||||
return try await perform(
|
||||
method,
|
||||
path: path,
|
||||
query: query,
|
||||
body: body,
|
||||
response: response,
|
||||
refreshAfterUnauthorized: false
|
||||
)
|
||||
}
|
||||
}
|
||||
throw APIError.http(status: http.statusCode, message: message)
|
||||
}
|
||||
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
|
||||
{
|
||||
return try decoder.decode(Response.self, from: Data("null".utf8))
|
||||
}
|
||||
return try decoder.decode(Response.self, from: data)
|
||||
} catch { throw APIError.decoding(String(describing: error)) }
|
||||
} catch let error as APIError { throw error } catch {
|
||||
if Task.isCancelled || error is CancellationError
|
||||
|| (error as? URLError)?.code == .cancelled
|
||||
{
|
||||
throw CancellationError()
|
||||
}
|
||||
throw APIError.transport(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
public func request<Response: Decodable & Sendable>(
|
||||
_ method: String, path: String, query: [URLQueryItem] = [],
|
||||
response: Response.Type = Response.self
|
||||
) async throws -> Response {
|
||||
try await request(
|
||||
method, path: path, query: query, body: Optional<EmptyBody>.none, response: response)
|
||||
}
|
||||
|
||||
nonisolated private struct EmptyBody: Encodable, Sendable {}
|
||||
nonisolated public struct EmptyResponse: Decodable, Sendable { public init() {} }
|
||||
}
|
||||
|
||||
extension URL {
|
||||
fileprivate var origin: String? {
|
||||
guard let scheme, let host else { return nil }
|
||||
return "\(scheme)://\(host)" + (port.map { ":\($0)" } ?? "")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import Foundation
|
||||
import Security
|
||||
|
||||
/// Keeps the backend's HttpOnly session and refresh cookies available when Xcode
|
||||
/// replaces a SwiftUI preview process. Cookie values stay in the Keychain.
|
||||
enum AuthCookiePersistence {
|
||||
private static let service = "dk.lucasskt.MusicApp.auth-cookies"
|
||||
private static let account = "music.lucasskt.dk"
|
||||
|
||||
static func restore(into storage: HTTPCookieStorage, for url: URL) {
|
||||
guard let data = read() else {
|
||||
debug("restore: no Keychain record for host=\(url.host ?? "?")")
|
||||
return
|
||||
}
|
||||
guard let properties = try? PropertyListSerialization.propertyList(
|
||||
from: data, options: [], format: nil) as? [[HTTPCookiePropertyKey: Any]] else {
|
||||
debug("restore: Keychain data could not be decoded (\(data.count) bytes)")
|
||||
return
|
||||
}
|
||||
|
||||
let cookies = properties.compactMap(HTTPCookie.init(properties:))
|
||||
.filter { $0.domain.hasSuffix("music.lucasskt.dk") && $0.expiresDate.map { $0 > Date() } ?? true }
|
||||
storage.setCookies(cookies, for: url, mainDocumentURL: nil)
|
||||
debug("restore: loaded \(cookies.count) cookies [\(cookieNames(cookies))] for host=\(url.host ?? "?")")
|
||||
}
|
||||
|
||||
static func save(from storage: HTTPCookieStorage, for url: URL) {
|
||||
let properties = storage.cookies(for: url)?
|
||||
.filter { $0.domain.hasSuffix("music.lucasskt.dk") }
|
||||
.compactMap(\.properties) ?? []
|
||||
guard let data = try? PropertyListSerialization.data(
|
||||
fromPropertyList: properties, format: .binary, options: 0)
|
||||
else {
|
||||
debug("save: cookie properties could not be encoded [\(cookieNames(storage.cookies(for: url) ?? []))]")
|
||||
return
|
||||
}
|
||||
|
||||
let query: [String: Any] = [
|
||||
kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: service,
|
||||
kSecAttrAccount as String: account,
|
||||
]
|
||||
let update: [String: Any] = [kSecValueData as String: data]
|
||||
let status = SecItemUpdate(query as CFDictionary, update as CFDictionary)
|
||||
if status == errSecItemNotFound {
|
||||
var insert = query
|
||||
insert[kSecValueData as String] = data
|
||||
insert[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
|
||||
let addStatus = SecItemAdd(insert as CFDictionary, nil)
|
||||
debug("save: insert status=\(addStatus), cookies=\(properties.count) [\(cookieNames(storage.cookies(for: url) ?? []))]")
|
||||
} else {
|
||||
debug("save: update status=\(status), cookies=\(properties.count) [\(cookieNames(storage.cookies(for: url) ?? []))]")
|
||||
}
|
||||
}
|
||||
|
||||
static func logRequestCookies(from storage: HTTPCookieStorage, for url: URL, phase: String) {
|
||||
debug("\(phase): request cookie names [\(cookieNames(storage.cookies(for: url) ?? []))] host=\(url.host ?? "?")")
|
||||
}
|
||||
|
||||
static func clear() {
|
||||
SecItemDelete([
|
||||
kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: service,
|
||||
kSecAttrAccount as String: account,
|
||||
] as CFDictionary)
|
||||
}
|
||||
|
||||
private static func read() -> Data? {
|
||||
var query: [String: Any] = [
|
||||
kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: service,
|
||||
kSecAttrAccount as String: account,
|
||||
kSecReturnData as String: true,
|
||||
kSecMatchLimit as String: kSecMatchLimitOne,
|
||||
]
|
||||
query[kSecUseAuthenticationUI as String] = kSecUseAuthenticationUIFail
|
||||
var result: CFTypeRef?
|
||||
let status = SecItemCopyMatching(query as CFDictionary, &result)
|
||||
guard status == errSecSuccess else {
|
||||
debug("read: Keychain status=\(status)")
|
||||
return nil
|
||||
}
|
||||
debug("read: Keychain success")
|
||||
return result as? Data
|
||||
}
|
||||
|
||||
private static func cookieNames(_ cookies: [HTTPCookie]) -> String {
|
||||
cookies.map(\.name).sorted().joined(separator: ",")
|
||||
}
|
||||
|
||||
private static func debug(_ message: String) {
|
||||
#if DEBUG
|
||||
print("[AuthCookiePersistence] pid=\(ProcessInfo.processInfo.processIdentifier) bundle=\(Bundle.main.bundleIdentifier ?? "?") \(message)")
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import Foundation
|
||||
|
||||
/// MongoDB references are populated on some API routes and bare ObjectIds on others.
|
||||
nonisolated public enum APIReference<Value: Decodable & Sendable>: Decodable, Sendable {
|
||||
case id(String)
|
||||
case value(Value)
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
if let id = try? container.decode(String.self) {
|
||||
self = .id(id)
|
||||
} else {
|
||||
self = .value(try container.decode(Value.self))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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"
|
||||
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"
|
||||
case name
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated public struct Album: Decodable, Identifiable, Sendable {
|
||||
public let id: String
|
||||
public let name: String
|
||||
public let artists: [APIReference<Artist>]
|
||||
public let file: String?
|
||||
public let genre: APIReference<Genre>?
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "_id"
|
||||
case name, artists, file, genre
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated public struct TrackAlbum: Decodable, Identifiable, Sendable {
|
||||
public let id: String
|
||||
public let name: String
|
||||
public let file: String
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "_id"
|
||||
case name, file
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated public struct Lyrics: Decodable, Sendable {
|
||||
public let synced: Bool
|
||||
public let text: String
|
||||
}
|
||||
|
||||
nonisolated public struct Track: Decodable, Identifiable, Sendable {
|
||||
public let id: String
|
||||
public let name: String
|
||||
public let album: APIReference<TrackAlbum>
|
||||
public let artists: [APIReference<Artist>]
|
||||
public let fileDir: String
|
||||
public let durationInSeconds: Double
|
||||
public let lyrics: Lyrics?
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "_id"
|
||||
case name, album, artists, fileDir, durationInSeconds, lyrics
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated public struct User: Decodable, Identifiable, Sendable {
|
||||
public let id: String
|
||||
public let name: String
|
||||
public let email: String
|
||||
public let role: String
|
||||
public let savedTracks: [String]?
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "_id"
|
||||
case name, email, role, savedTracks
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated public struct SessionStatus: Decodable, Sendable { public let authenticated: Bool }
|
||||
nonisolated public struct Session: Decodable, Sendable {
|
||||
public let expireAt: Date
|
||||
/// Returned for administrative bearer auth; ordinary user auth uses the HttpOnly cookie.
|
||||
public let sessionToken: String
|
||||
}
|
||||
nonisolated public struct SearchResults: Decodable, Sendable {
|
||||
public let tracks: [Track]
|
||||
public let albums: [Album]
|
||||
public let artists: [Artist]
|
||||
}
|
||||
nonisolated public struct TrackMembership: Decodable, Sendable { public let contains: Bool }
|
||||
|
||||
nonisolated public enum SearchType: String, Sendable { case track, album, artist, `default` }
|
||||
@@ -0,0 +1,131 @@
|
||||
import Foundation
|
||||
|
||||
public struct MusicAPI: Sendable {
|
||||
public let client: APIClient
|
||||
public init(client: APIClient = APIClient()) { self.client = client }
|
||||
|
||||
private func q(_ pairs: [(String, String?)]) -> [URLQueryItem] {
|
||||
pairs.compactMap { key, value in value.map { URLQueryItem(name: key, value: $0) } }
|
||||
}
|
||||
private func page(_ limit: Int?, _ skip: Int?) -> [URLQueryItem] {
|
||||
q([("limit", limit.map(String.init)), ("skip", skip.map(String.init))])
|
||||
}
|
||||
|
||||
public func signIn(email: String, password: String, remember: Bool = true) async throws {
|
||||
let _: APIClient.EmptyResponse = try await client.request(
|
||||
"POST", path: "auth/signin",
|
||||
body: Credentials(email: email, password: password, remember: remember))
|
||||
guard try await sessionStatus().authenticated else {
|
||||
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 {
|
||||
let response: SignOutResponse = try await client.request("POST", path: "auth/signout")
|
||||
AuthCookiePersistence.clear()
|
||||
return response
|
||||
}
|
||||
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 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) })
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated private struct Credentials: Encodable, Sendable {
|
||||
let email: String
|
||||
let password: String
|
||||
let remember: Bool
|
||||
}
|
||||
nonisolated public struct SignOutResponse: Decodable, Sendable { public let success: Bool? }
|
||||
@@ -0,0 +1,68 @@
|
||||
import Combine
|
||||
import Foundation
|
||||
|
||||
@MainActor
|
||||
final class AuthSessionStore: ObservableObject {
|
||||
enum State {
|
||||
case checking
|
||||
case signedOut
|
||||
case signedIn
|
||||
}
|
||||
|
||||
@Published private(set) var state: State = .checking
|
||||
@Published private(set) var isSigningIn = false
|
||||
|
||||
static let shared = AuthSessionStore()
|
||||
private let api = MusicAPI()
|
||||
|
||||
init(initialState: State = .checking) {
|
||||
state = initialState
|
||||
debug("store initialized; state=\(stateName(state))")
|
||||
}
|
||||
|
||||
func restoreSession() async {
|
||||
debug("restore requested; state=\(stateName(state))")
|
||||
guard state == .checking else { return }
|
||||
|
||||
do {
|
||||
let authenticated = try await api.sessionStatus().authenticated
|
||||
guard !Task.isCancelled else {
|
||||
debug("session restore cancelled; leaving state unchanged")
|
||||
return
|
||||
}
|
||||
state = authenticated ? .signedIn : .signedOut
|
||||
debug("session restore completed; authenticated=\(authenticated)")
|
||||
} catch is CancellationError {
|
||||
debug("session restore cancelled; leaving state unchanged")
|
||||
} catch {
|
||||
guard !Task.isCancelled else {
|
||||
debug("session restore cancelled after request error; leaving state unchanged")
|
||||
return
|
||||
}
|
||||
debug("session restore failed: \(error.localizedDescription)")
|
||||
state = .signedOut
|
||||
}
|
||||
}
|
||||
|
||||
func signIn(email: String, password: String) async throws {
|
||||
isSigningIn = true
|
||||
defer { isSigningIn = false }
|
||||
|
||||
try await api.signIn(email: email, password: password)
|
||||
state = .signedIn
|
||||
}
|
||||
|
||||
private func debug(_ message: String) {
|
||||
#if DEBUG
|
||||
print("[AuthSessionStore] pid=\(ProcessInfo.processInfo.processIdentifier) \(message)")
|
||||
#endif
|
||||
}
|
||||
|
||||
private func stateName(_ state: State) -> String {
|
||||
switch state {
|
||||
case .checking: "checking"
|
||||
case .signedOut: "signedOut"
|
||||
case .signedIn: "signedIn"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
import Combine
|
||||
import AVFAudio
|
||||
import Foundation
|
||||
import SwiftAudioEx
|
||||
import UIKit
|
||||
|
||||
enum PlayerRepeatMode: CaseIterable {
|
||||
case off
|
||||
case one
|
||||
case all
|
||||
}
|
||||
|
||||
/// App-owned playback state and actions backed by SwiftAudioEx.
|
||||
@MainActor
|
||||
final class PlayerManager: ObservableObject {
|
||||
@Published private(set) var currentTrack: Track?
|
||||
@Published private(set) var upcomingTracks: [Track] = []
|
||||
@Published private(set) var previousTracks: [Track] = []
|
||||
@Published private(set) var isPlaying = false
|
||||
@Published private(set) var elapsedTime: TimeInterval = 0
|
||||
@Published private(set) var duration: TimeInterval = 0
|
||||
@Published private(set) var errorMessage: String?
|
||||
@Published private(set) var isMiniPlayerCompact = false
|
||||
@Published var repeatMode: PlayerRepeatMode = .off {
|
||||
didSet { applyRepeatMode() }
|
||||
}
|
||||
@Published var volume: Double {
|
||||
didSet {
|
||||
let clamped = min(1, max(0, volume))
|
||||
if clamped != volume {
|
||||
volume = clamped
|
||||
return
|
||||
}
|
||||
player.volume = Float(clamped)
|
||||
UserDefaults.standard.set(clamped, forKey: Self.volumeStorageKey)
|
||||
}
|
||||
}
|
||||
|
||||
private static let volumeStorageKey = "music-v2-player-volume"
|
||||
private let player = QueuedAudioPlayer()
|
||||
private let apiConfiguration: APIConfiguration
|
||||
private var tracksByItemID: [ObjectIdentifier: Track] = [:]
|
||||
private var playbackIntent: Bool?
|
||||
|
||||
init() {
|
||||
self.apiConfiguration = APIConfiguration()
|
||||
let storedVolume = UserDefaults.standard.object(forKey: Self.volumeStorageKey) as? Double
|
||||
volume = min(1, max(0, storedVolume ?? 0.5))
|
||||
player.volume = Float(volume)
|
||||
player.automaticallyUpdateNowPlayingInfo = true
|
||||
player.remoteCommands = [.play, .pause, .togglePlayPause, .next, .previous, .changePlaybackPosition]
|
||||
installEventListeners()
|
||||
}
|
||||
|
||||
func play() {
|
||||
do {
|
||||
try AudioSessionController.shared.set(category: .playback)
|
||||
try AudioSessionController.shared.activateSession()
|
||||
playbackIntent = true
|
||||
player.play()
|
||||
isPlaying = true
|
||||
errorMessage = nil
|
||||
} catch {
|
||||
playbackIntent = nil
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
refreshState()
|
||||
}
|
||||
|
||||
func pause() {
|
||||
playbackIntent = false
|
||||
isPlaying = false
|
||||
player.pause()
|
||||
}
|
||||
|
||||
func play(_ track: Track) {
|
||||
play([track], startingAt: 0, shuffled: false)
|
||||
}
|
||||
|
||||
func play(_ tracks: [Track], startingAt index: Int = 0, shuffled: Bool = false) {
|
||||
guard !tracks.isEmpty else { clear(); return }
|
||||
guard tracks.indices.contains(index) else { return }
|
||||
isMiniPlayerCompact = false
|
||||
|
||||
let orderedTracks: [Track]
|
||||
if shuffled {
|
||||
let selected = tracks[index]
|
||||
orderedTracks = [selected] + tracks.enumerated()
|
||||
.filter { $0.offset != index }
|
||||
.map(\.element)
|
||||
.shuffled()
|
||||
} else {
|
||||
orderedTracks = Array(tracks[index...])
|
||||
}
|
||||
|
||||
player.clear()
|
||||
tracksByItemID.removeAll()
|
||||
let items = orderedTracks.compactMap(makeAudioItem(for:))
|
||||
guard !items.isEmpty else {
|
||||
errorMessage = "Could not create an audio URL for this track."
|
||||
return
|
||||
}
|
||||
playbackIntent = true
|
||||
player.add(items: items, playWhenReady: true)
|
||||
refreshState()
|
||||
loadArtwork(for: player.currentItem)
|
||||
}
|
||||
|
||||
func next() {
|
||||
player.next()
|
||||
refreshState()
|
||||
loadArtwork(for: player.currentItem)
|
||||
}
|
||||
|
||||
func previous() {
|
||||
if player.currentTime > 5 {
|
||||
seek(to: 0)
|
||||
} else {
|
||||
player.previous()
|
||||
refreshState()
|
||||
loadArtwork(for: player.currentItem)
|
||||
}
|
||||
}
|
||||
|
||||
func seek(to seconds: TimeInterval) {
|
||||
player.seek(to: min(max(0, seconds), max(duration, 0)))
|
||||
elapsedTime = min(max(0, seconds), max(duration, 0))
|
||||
}
|
||||
|
||||
func addToQueue(_ track: Track) {
|
||||
guard let item = makeAudioItem(for: track) else { return }
|
||||
if player.currentItem == nil {
|
||||
player.add(item: item, playWhenReady: false)
|
||||
} else {
|
||||
player.add(item: item)
|
||||
}
|
||||
refreshState()
|
||||
}
|
||||
|
||||
func playNext(_ track: Track) {
|
||||
guard let item = makeAudioItem(for: track) else { return }
|
||||
guard player.currentItem != nil else {
|
||||
player.add(item: item, playWhenReady: true)
|
||||
refreshState()
|
||||
return
|
||||
}
|
||||
do {
|
||||
try player.add(items: [item], at: player.currentIndex + 1)
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
refreshState()
|
||||
}
|
||||
|
||||
func playQueuedTrack(at index: Int) {
|
||||
guard player.items.indices.contains(index) else { return }
|
||||
do {
|
||||
try player.jumpToItem(atIndex: index, playWhenReady: true)
|
||||
refreshState()
|
||||
loadArtwork(for: player.currentItem)
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func moveQueuedTrack(from sourceIndex: Int, to destinationIndex: Int) {
|
||||
guard player.items.indices.contains(sourceIndex),
|
||||
player.items.indices.contains(destinationIndex)
|
||||
else { return }
|
||||
do {
|
||||
try player.moveItem(fromIndex: sourceIndex, toIndex: destinationIndex)
|
||||
refreshState()
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func removeQueuedTrack(at index: Int) {
|
||||
guard player.items.indices.contains(index) else { return }
|
||||
let item = player.items[index]
|
||||
do {
|
||||
_ = try player.removeItem(at: index)
|
||||
tracksByItemID.removeValue(forKey: ObjectIdentifier(item as AnyObject))
|
||||
refreshState()
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func clear() {
|
||||
playbackIntent = nil
|
||||
player.clear()
|
||||
tracksByItemID.removeAll()
|
||||
isPlaying = false
|
||||
currentTrack = nil
|
||||
upcomingTracks = []
|
||||
previousTracks = []
|
||||
elapsedTime = 0
|
||||
duration = 0
|
||||
errorMessage = nil
|
||||
}
|
||||
|
||||
func artworkURL(for track: Track) -> URL? {
|
||||
guard case .value(let album) = track.album else { return nil }
|
||||
return apiConfiguration.mediaURL(for: album.file)
|
||||
}
|
||||
|
||||
func compactMiniPlayerForDownwardScroll() {
|
||||
isMiniPlayerCompact = true
|
||||
}
|
||||
|
||||
func shuffleUpcoming() {
|
||||
let currentIndex = player.currentIndex
|
||||
guard currentIndex >= 0, player.items.count - currentIndex > 2 else { return }
|
||||
|
||||
let targetOrder = Array(player.items.dropFirst(currentIndex + 1)).shuffled()
|
||||
for (offset, target) in targetOrder.enumerated() {
|
||||
let targetID = ObjectIdentifier(target as AnyObject)
|
||||
guard let existingIndex = player.items.firstIndex(where: {
|
||||
ObjectIdentifier($0 as AnyObject) == targetID
|
||||
}) else { continue }
|
||||
let targetIndex = currentIndex + 1 + offset
|
||||
if existingIndex != targetIndex {
|
||||
try? player.moveItem(fromIndex: existingIndex, toIndex: targetIndex)
|
||||
}
|
||||
}
|
||||
refreshState()
|
||||
}
|
||||
|
||||
func cycleRepeat() {
|
||||
switch repeatMode {
|
||||
case .off: repeatMode = .one
|
||||
case .one: repeatMode = .all
|
||||
case .all: repeatMode = .off
|
||||
}
|
||||
}
|
||||
|
||||
private func applyRepeatMode() {
|
||||
switch repeatMode {
|
||||
case .off: player.repeatMode = .off
|
||||
case .one: player.repeatMode = .track
|
||||
case .all: player.repeatMode = .queue
|
||||
}
|
||||
}
|
||||
|
||||
private func makeAudioItem(for track: Track) -> DefaultAudioItem? {
|
||||
guard let url = apiConfiguration.audioURL(for: track) else { return nil }
|
||||
let artistNames = track.artists.compactMap { reference -> String? in
|
||||
guard case .value(let artist) = reference else { return nil }
|
||||
return artist.name
|
||||
}
|
||||
let albumName: String?
|
||||
if case .value(let album) = track.album {
|
||||
albumName = album.name
|
||||
} else {
|
||||
albumName = nil
|
||||
}
|
||||
let item = DefaultAudioItem(
|
||||
audioUrl: url.absoluteString,
|
||||
artist: artistNames.joined(separator: ", "),
|
||||
title: track.name,
|
||||
albumTitle: albumName,
|
||||
sourceType: .stream
|
||||
)
|
||||
tracksByItemID[ObjectIdentifier(item)] = track
|
||||
return item
|
||||
}
|
||||
|
||||
private func installEventListeners() {
|
||||
player.event.stateChange.addListener(self) { [weak self] state in
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
switch state {
|
||||
case .playing:
|
||||
if self.playbackIntent != false {
|
||||
self.playbackIntent = nil
|
||||
self.isPlaying = true
|
||||
}
|
||||
case .paused:
|
||||
self.playbackIntent = nil
|
||||
self.isPlaying = false
|
||||
case .buffering:
|
||||
if self.playbackIntent != false { self.isPlaying = true }
|
||||
case .stopped, .idle, .failed, .ended:
|
||||
self.playbackIntent = nil
|
||||
self.isPlaying = false
|
||||
case .loading, .ready:
|
||||
break
|
||||
}
|
||||
self.refreshState()
|
||||
}
|
||||
}
|
||||
player.event.currentItem.addListener(self) { [weak self] _ in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.refreshState()
|
||||
self?.loadArtwork(for: self?.player.currentItem)
|
||||
}
|
||||
}
|
||||
player.event.secondElapse.addListener(self) { [weak self] elapsed in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.elapsedTime = elapsed
|
||||
self?.duration = self?.player.duration ?? 0
|
||||
}
|
||||
}
|
||||
player.event.updateDuration.addListener(self) { [weak self] duration in
|
||||
Task { @MainActor [weak self] in self?.duration = duration }
|
||||
}
|
||||
player.event.fail.addListener(self) { [weak self] error in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.errorMessage = error?.localizedDescription ?? "Playback failed."
|
||||
self?.isPlaying = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func refreshState() {
|
||||
currentTrack = track(for: player.currentItem)
|
||||
upcomingTracks = player.nextItems.compactMap { track(for: $0) }
|
||||
previousTracks = player.previousItems.compactMap { track(for: $0) }
|
||||
elapsedTime = player.currentTime
|
||||
duration = player.duration
|
||||
isPlaying = playbackIntent ?? (player.playerState == .playing || player.playerState == .buffering)
|
||||
}
|
||||
|
||||
private func track(for item: AudioItem?) -> Track? {
|
||||
guard let item else { return nil }
|
||||
return tracksByItemID[ObjectIdentifier(item as AnyObject)]
|
||||
}
|
||||
|
||||
private func loadArtwork(for item: AudioItem?) {
|
||||
guard let item,
|
||||
let track = track(for: item),
|
||||
let audioItem = item as? DefaultAudioItem,
|
||||
case .value(let album) = track.album,
|
||||
let url = apiConfiguration.mediaURL(for: album.file)
|
||||
else { return }
|
||||
|
||||
Task {
|
||||
guard let (data, _) = try? await URLSession.shared.data(from: url),
|
||||
let image = UIImage(data: data)
|
||||
else { return }
|
||||
audioItem.artwork = image
|
||||
guard let currentItem = player.currentItem,
|
||||
ObjectIdentifier(currentItem as AnyObject) == ObjectIdentifier(item as AnyObject)
|
||||
else { return }
|
||||
player.loadNowPlayingMetaValues()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user