diff --git a/Sources/MusadoraKit/Library/LibraryPlaylist.swift b/Sources/MusadoraKit/Library/LibraryPlaylist.swift index 48cf960ca..60fff51e6 100644 --- a/Sources/MusadoraKit/Library/LibraryPlaylist.swift +++ b/Sources/MusadoraKit/Library/LibraryPlaylist.swift @@ -8,6 +8,8 @@ import MusicKit import MediaPlayer + + public extension MusadoraKit { /// Fetch a playlist from the user's library by using its identifier. /// - Parameters: @@ -176,3 +178,27 @@ public extension MusadoraKit { return playlist } } + +// MARK: - `LibraryPlaylist` methods +extension MusadoraKit { + + /// Fetch all playlists from the user's library in alphabetical order. + /// - Returns: `LibraryPlaylists` for the given limit. + static func libraryPlaylists() async throws -> LibraryPlaylists { + let playlistsURL = URL(string: "https://api.music.apple.com/v1/me/library/playlists")! + let request = MusicDataRequest(urlRequest: .init(url: playlistsURL)) + let response = try await request.response() + + var libraryPlaylists = try JSONDecoder().decode(LibraryPlaylists.self, from: response.data) + + repeat { + if let nextBatchOfPlaylists = try await libraryPlaylists.nextBatch() { + libraryPlaylists += nextBatchOfPlaylists + } else { + break + } + } while libraryPlaylists.hasNextBatch + + return libraryPlaylists + } +} diff --git a/Sources/MusadoraKit/Library/LibraryPlaylists.swift b/Sources/MusadoraKit/Library/LibraryPlaylists.swift new file mode 100644 index 000000000..31777626c --- /dev/null +++ b/Sources/MusadoraKit/Library/LibraryPlaylists.swift @@ -0,0 +1,46 @@ +// +// LibraryPlaylists.swift +// LibraryPlaylists +// +// Created by Rudrank Riyam on 06/10/22. +// + +import Foundation +import MusicKit + +/// A collection of library playlists. +public typealias LibraryPlaylists = MusicItemCollection + +public struct LibraryPlaylist: Codable, MusicItem { + public let id: MusicItemID + public let attributes: Attributes + + public struct Attributes: Codable, Sendable { + public let canEdit: Bool + public let name: String + public let isPublic: Bool + public let hasCatalog: Bool + public let playParams: PlayParameters + public let description: Description? + public let artwork: Artwork? + } + + public struct Description: Codable, Sendable { + public let standard: String + } + + public struct PlayParameters: Codable, Sendable { + public let id: MusicItemID + public let isLibrary: Bool + public let globalID: MusicItemID? + + enum CodingKeys: String, CodingKey { + case id, isLibrary + case globalID = "globalId" + } + } + + public var globalID: String? { + attributes.playParams.globalID?.rawValue + } +}