UNPKG

cody-music

Version:

mac osx spotify and itunes music player controller, spotify audio features, itunes and spotify genre, and playlist control

1,187 lines 43.9 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.setShuffle = exports.setRepeat = exports.setRepeatOff = exports.setRepeatTrack = exports.setRepeatPlaylist = exports.previous = exports.next = exports.playPause = exports.pause = exports.playTrack = exports.playSpotifyTrack = exports.play = exports.spotifyAuthState = exports.getUserProfile = exports.accessExpired = exports.transferSpotifyDevice = exports.playSpotifyDevice = exports.playTrackInLibrary = exports.quitMacPlayer = exports.playItunesTrackNumberInPlaylist = exports.playTrackInContext = exports.playSpotifyPlaylist = exports.getPlaylistTracks = exports.getSpotifyPlaylist = exports.getSavedTracks = exports.getSpotifyLikedSongs = exports.getSpotifyAlbumTracks = exports.getTracksByPlaylistName = exports.getTrack = exports.getSpotifyTracks = exports.getSpotifyTrackById = exports.getSpotifyPlayerContext = exports.getSpotifyRecentlyPlayedAfter = exports.getSpotifyRecentlyPlayedBefore = exports.getSpotifyRecentlyPlayedTracks = exports.getRunningTrack = exports.getRecommendationsForTracks = exports.hasActiveTrack = exports.isPlayerRunning = exports.isItunesRunning = exports.isSpotifyRunning = exports.isSpotifyDesktopEnabled = exports.refreshSpotifyAccessToken = exports.getSpotifyAccessToken = exports.isItunesDesktopSongTrackingEnabled = exports.isItunesDesktopEnabled = exports.isItunesAccessGranted = exports.searchArtists = exports.searchTracks = exports.setConfig = void 0; exports.getAccessToken = exports.setCredentials = exports.unMute = exports.repeatOff = exports.repeatOn = exports.isRunning = exports.startItunesIfNotRunning = exports.startSpotifyIfNotRunning = exports.getState = exports.getCurrentlyRunningTrackState = exports.getPlayerState = exports.requiresSpotifyAccessInfo = exports.removeTracksFromPlaylist = exports.addTracksToPlaylist = exports.replacePlaylistTracks = exports.followPlaylist = exports.deletePlaylist = exports.createPlaylist = exports.getSpotifyAudioFeatures = exports.getTopSpotifyTracks = exports.getHighestFrequencySpotifyGenre = exports.getSpotifyGenreByArtistId = exports.getSpotifyGenre = exports.getGenre = exports.getSpotifyDevices = exports.playSpotifyMacDesktopTrack = exports.launchAndPlaySpotifyTrack = exports.launchPlayer = exports.getPlaylistNames = exports.getPlaylists = exports.removeFromSpotifyLiked = exports.saveToSpotifyLiked = exports.setItunesLoved = exports.unmute = exports.mute = exports.volumeDown = exports.volumeUp = exports.setVolume = exports.isRepeating = exports.isShuffling = void 0; const controller_1 = require("./controller"); const models_1 = require("./models"); const client_1 = require("./client"); const playerstate_1 = require("./playerstate"); const audiostat_1 = require("./audiostat"); const store_1 = require("./store"); const util_1 = require("./util"); const playlist_service_1 = require("./playlist.service"); const profile_1 = require("./profile"); const album_service_1 = require("./album.service"); // initi the props require('dotenv').config(); // get the instances const musicClient = client_1.MusicClient.getInstance(); const musicCtr = controller_1.MusicController.getInstance(); const musicPlayerCtr = playerstate_1.MusicPlayerState.getInstance(); const musicStore = store_1.MusicStore.getInstance(); const musicUtil = new util_1.MusicUtil(); const audioStat = audiostat_1.AudioStat.getInstance(); const playlist = playlist_service_1.PlaylistService.getInstance(); const userProfile = profile_1.UserProfile.getInstance(); const albumSvc = album_service_1.AlbumService.getInstance(); /** * Initialize/set music credentials and settings * @param config <CodyConfig> */ function setConfig(config) { musicStore.setConfig(config); } exports.setConfig = setConfig; /** * Valid types are: album, artist, playlist, and track * keywords: send the keywords to search against. * Use specific filter name if you want to search against certain * fields. * Example searchTracks("track:what a time artist:tom") * * @param string * @param limit (min of 1 and a max of 50) */ function searchTracks(keywords, limit = 50) { return playlist.search("track", keywords, limit); } exports.searchTracks = searchTracks; /** * Valid types are: album, artist, playlist, and track * keywords: send the keywords to search against. * Use specific filter name if you want to search against certain * fields. * Example searchTracks("track:what a time artist:tom") * * @param string * @param limit (min of 1 and a max of 50) */ function searchArtists(keywords, limit = 50) { return playlist.search("artist", keywords, limit); } exports.searchArtists = searchArtists; /** * Returns true if the user has granted Mac OS access for iTunes control */ function isItunesAccessGranted() { return musicStore.itunesAccessGranted; } exports.isItunesAccessGranted = isItunesAccessGranted; /** * Returns false if cody music has been configured to to disable it * or if it's the OS is not Mac, * otherwise it's set to true by default */ function isItunesDesktopEnabled() { return musicStore.itunesDesktopEnabled; } exports.isItunesDesktopEnabled = isItunesDesktopEnabled; /** * Returns false if cody music has been configured to to disable it * or if it's the OS is not Mac, * otherwise it's set to true by default */ function isItunesDesktopSongTrackingEnabled() { return musicStore.itunesDesktopTrackingEnabled; } exports.isItunesDesktopSongTrackingEnabled = isItunesDesktopSongTrackingEnabled; /** * Get the Spotify accessToken provided via through the setConfig api * @returns {string} the spotify access token string */ function getSpotifyAccessToken() { return musicStore.credentialByKey("spotifyAccessToken"); } exports.getSpotifyAccessToken = getSpotifyAccessToken; /** * Refresh the Spotify accessToken * @returns {Promise<boolean>} whether or not the refresh was successful */ async function refreshSpotifyAccessToken() { const response = await musicClient.refreshSpotifyToken(); return response.status === "success"; } exports.refreshSpotifyAccessToken = refreshSpotifyAccessToken; /** * Returns false if cody music has been configured to to disable it, * otherwise it's set to true by default */ function isSpotifyDesktopEnabled() { return musicStore.spotifyDesktopEnabled; } exports.isSpotifyDesktopEnabled = isSpotifyDesktopEnabled; /** * Checks if the Spotify desktop or web player is running or not * @returns {Promise<boolean>} */ async function isSpotifyRunning() { let running = await isPlayerRunning(models_1.PlayerName.SpotifyDesktop); if (!running) { // check the web running = await musicPlayerCtr.isSpotifyWebRunning(); } return running; } exports.isSpotifyRunning = isSpotifyRunning; /** * Checks if the iTunes desktop player is running or not * @returns {Promise<boolean>} */ function isItunesRunning() { return isPlayerRunning(models_1.PlayerName.ItunesDesktop); } exports.isItunesRunning = isItunesRunning; /** * Checks if one of the specified players is running * @param player {spotify|spotify-web|itunes} * @returns {Promise<boolean>} */ async function isPlayerRunning(player) { if (player === models_1.PlayerName.SpotifyWeb) { return await musicPlayerCtr.isSpotifyWebRunning(); } else { let state = await musicCtr.run(player, "checkPlayerRunningState"); try { return JSON.parse(state); } catch (err) { return false; } } } exports.isPlayerRunning = isPlayerRunning; /** * Returns whether there's an active track, * (spotify web, spotify desktop, or itunes desktop) * @returns {Promise<boolean>} */ async function hasActiveTrack() { const track = await getRunningTrack(); if (track && track.id) { return true; } return false; } exports.hasActiveTrack = hasActiveTrack; /** * Returns the recommended tracks. * @param trackIds (optional) track IDs or URIs (5 max) * @param limit (optional) will default to 40 if not specified * @param market (optional) will default to none if not specified * @param min_popularity (optional) will default to a min or 20 * @param target_popularity (optional) will default to 90 * @param seed_genres (optional) the supported spotify genres (5 max) * @param seed_genres (optional) artist IDs or URIs (5 max) * @param features (optional) supports the tunable track attributes using min_*, max_*, and target_* * i.e. {max_valence: 0.3, target_valence: 0.1} */ async function getRecommendationsForTracks(trackIds = [], limit = 40, market = "", min_popularity = 20, target_popularity = 100, seed_genres = [], seed_artists = [], features = {}) { return musicPlayerCtr.getRecommendationsForTracks(trackIds, limit, market, min_popularity, target_popularity, seed_genres, seed_artists, features); } exports.getRecommendationsForTracks = getRecommendationsForTracks; /** * Returns the currently running track. * Spotify web, desktop, or itunes desktop. * If it finds a spotify device but it's not playing, and mac iTunes is not playing * or paused, then it will return the Spotify track. * It will return an empty Track object if it's unable to * find a running track. * @returns {Promise<Track>} **/ async function getRunningTrack() { let spotifyWebTrack = null; // spotify web try // 1st try spotify web if (musicStore.spotifyApiEnabled) { spotifyWebTrack = await getTrack(models_1.PlayerName.SpotifyWeb); // check if the spotify track is running (playing or paused) let spotifyWebTrackRunning = musicUtil.isTrackRunning(spotifyWebTrack); // if it's playing then return it if (spotifyWebTrackRunning && spotifyWebTrack.state === models_1.TrackStatus.Playing) { // spotify web track is running. it's the highest priority track return spotifyWebTrack; } } let spotifyDesktopTrack = null; // spotify desktop try if (musicStore.spotifyDesktopEnabled) { // next try spotify desktop const spotifyDesktopRunning = await isPlayerRunning(models_1.PlayerName.SpotifyDesktop); if (spotifyDesktopRunning) { spotifyDesktopTrack = await getTrack(models_1.PlayerName.SpotifyDesktop); const isSpotifyDesktopRunning = musicUtil.isTrackRunning(spotifyDesktopTrack); if (isSpotifyDesktopRunning && spotifyDesktopTrack.state === models_1.TrackStatus.Playing) { spotifyDesktopTrack["playerType"] = models_1.PlayerType.MacSpotifyDesktop; return spotifyDesktopTrack; } } } let itunesDesktopTrack = null; // itunes desktop try if (musicStore.itunesDesktopTrackingEnabled && musicStore.itunesAccessGranted) { // still no track or it's paused, try itunes desktop const itunesDesktopRunning = await isPlayerRunning(models_1.PlayerName.ItunesDesktop); if (itunesDesktopRunning) { itunesDesktopTrack = await getTrack(models_1.PlayerName.ItunesDesktop); if (itunesDesktopTrack && !itunesDesktopTrack.id) { // get the 1st track itunesDesktopTrack = await musicCtr.run(models_1.PlayerName.ItunesDesktop, "firstTrackState"); if (typeof itunesDesktopTrack === "string" && itunesDesktopTrack.includes("GRANT_ERROR")) { const errorStr = itunesDesktopTrack; itunesDesktopTrack = new models_1.Track(); itunesDesktopTrack.error = errorStr; } else if (itunesDesktopTrack) { try { itunesDesktopTrack = JSON.parse(itunesDesktopTrack); if (itunesDesktopTrack) { itunesDesktopTrack["playerType"] = models_1.PlayerType.MacItunesDesktop; } } catch (e) { // } } } // if itunes is not running, return the spotify web track we've gathered const isItunesTrackRunning = musicUtil.isTrackRunning(itunesDesktopTrack); if (isItunesTrackRunning && itunesDesktopTrack.state === models_1.TrackStatus.Playing) { // itunes track is playing, return it return itunesDesktopTrack; } } } // nothing is playing, check if any are paused in the following order // 1) spotify web // 2) spotify desktop // 3) itunes desktop if (spotifyWebTrack && spotifyWebTrack.state == models_1.TrackStatus.Paused) { return spotifyWebTrack; } else if (spotifyDesktopTrack && spotifyDesktopTrack.state === models_1.TrackStatus.Paused) { return spotifyDesktopTrack; } else if (itunesDesktopTrack && itunesDesktopTrack.state === models_1.TrackStatus.Paused) { return itunesDesktopTrack; } return new models_1.Track(); } exports.getRunningTrack = getRunningTrack; /** * Fetch the recently played spotify tracks * @param limit - The maximum number of items to return. Default: 50. Minimum: 1. Maximum: 50 */ async function getSpotifyRecentlyPlayedTracks(limit = 50) { return musicPlayerCtr.getSpotifyRecentlyPlayedTracks(limit); } exports.getSpotifyRecentlyPlayedTracks = getSpotifyRecentlyPlayedTracks; /** * Fetch the recently played spotify tracks * @param limit - The maximum number of items to return. Default: 50. Minimum: 1. Maximum: 50 * @param before - Returns all items before (but not including) this cursor position */ async function getSpotifyRecentlyPlayedBefore(limit = 50, before = 0) { return musicPlayerCtr.getSpotifyRecentlyPlayedTracksBefore(limit, before); } exports.getSpotifyRecentlyPlayedBefore = getSpotifyRecentlyPlayedBefore; /** * Fetch the recently played spotify tracks * @param limit - The maximum number of items to return. Default: 50. Minimum: 1. Maximum: 50 * @param after - Returns all items before (but not including) this cursor position */ async function getSpotifyRecentlyPlayedAfter(limit = 50, after = 0) { return musicPlayerCtr.getSpotifyRecentlyPlayedTracksAfter(limit, after); } exports.getSpotifyRecentlyPlayedAfter = getSpotifyRecentlyPlayedAfter; /** * Fetch the spotify player context * Info about the device, is playing state, etc. */ async function getSpotifyPlayerContext() { return musicPlayerCtr.getSpotifyPlayerContext(); } exports.getSpotifyPlayerContext = getSpotifyPlayerContext; /** * Returns a track by the given spotify track id * @param id * @param includeFullArtistData (optional - if true it will return full artist info) * @package includeAudioFeaturesData (optional) * @param includeGenre (optional) */ async function getSpotifyTrackById(id, includeFullArtistData = false, includeAudioFeaturesData = false, includeGenre = false) { return musicPlayerCtr.getSpotifyTrackById(id, includeFullArtistData, includeAudioFeaturesData, includeGenre); } exports.getSpotifyTrackById = getSpotifyTrackById; /** * Returns tracks by the given spotify track ids * @param ids * @param includeFullArtistData (optional - if true it will return full artist info) * @package includeAudioFeaturesData (optional) * @param includeGenre (optional) */ async function getSpotifyTracks(ids, includeFullArtistData = false, includeAudioFeaturesData = false, includeGenre = true) { return musicPlayerCtr.getSpotifyTracks(ids, includeFullArtistData, includeAudioFeaturesData, includeGenre); } exports.getSpotifyTracks = getSpotifyTracks; /** * Returns the track of a given player {spotify|spotify-web|itunes} * - Spotify does not return a "genre" * - duration is in milliseconds * @param player {spotify|spotif-web|itunes} * @returns {artist, album, genre, disc_number, duration, played_count, track_number, id, name, state} */ async function getTrack(player) { let track; if (player === models_1.PlayerName.SpotifyWeb) { // fetch the web track track = await musicPlayerCtr.getSpotifyWebCurrentTrack(); } else { // get the string representation of the track. // fetch the track from the specified player name. // first check to see if the app is running before checking const running = await isPlayerRunning(player); if (running) { track = await musicCtr.run(player, "state"); if (track) { try { track = JSON.parse(track); if (track) { if (player === models_1.PlayerName.ItunesDesktop) { track.playerType = models_1.PlayerType.MacItunesDesktop; } else { track.playerType = models_1.PlayerType.MacSpotifyDesktop; } } } catch (e) { } } } } if (!track) { track = new models_1.Track(); } else if (track && !track["playerType"]) { if (player === models_1.PlayerName.SpotifyWeb) { track["playerType"] = models_1.PlayerType.WebSpotify; } else if (player === models_1.PlayerName.SpotifyDesktop) { track["playerType"] = models_1.PlayerType.MacSpotifyDesktop; } else { track["playerType"] = models_1.PlayerType.MacItunesDesktop; } } return track; } exports.getTrack = getTrack; /** * Returns the tracks that are found for itunes * @param player {itunes} * @param playListName */ async function getTracksByPlaylistName(player, playListName) { let playlistItems = []; const params = null; const argv = [playListName]; const result = await musicCtr.run(player, "playlistTracksOfPlaylist", params, argv); let jsonResult = {}; if (result) { try { let jsonList; if (result.indexOf("[TRACK_END],") !== -1) { jsonList = result.split("[TRACK_END],"); } else { jsonList = result.split("[TRACK_END]"); } if (jsonList && jsonList.length > 0) { for (let i = 0; i < jsonList.length; i++) { let jsonStr = jsonList[i].trim(); if (jsonStr.toLowerCase() !== "ok") { try { jsonResult[i] = JSON.parse(jsonStr); } catch (err) { // it might be the success response "ok" } } } } } catch (err) { // } } /** * result will have ... * '38': { artist: 'ZAYN', album: 'Dusk Till Dawn (feat. Sia) [Radio Edit] - Single', duration: 239000, played_count: 260, name: 'Dusk Till Dawn (feat. Sia) [Radio Edit]', id: '6680' }, */ if (jsonResult) { // go through the keys and create an array // of PlaylistItem playlistItems = Object.keys(jsonResult).map((key) => { let trackItem = jsonResult[key]; let track = new models_1.Track(); track.name = trackItem.name; track.type = "track"; track.id = trackItem.id; track.artist = trackItem.artist; track.album = trackItem.album; track.played_count = trackItem.played_count; track.duration = trackItem.duration; track.playerType = models_1.PlayerType.MacItunesDesktop; return track; }); } return playlistItems; } exports.getTracksByPlaylistName = getTracksByPlaylistName; function getSpotifyAlbumTracks(albumId) { return albumSvc.getSpotifyAlbumTracks(albumId); } exports.getSpotifyAlbumTracks = getSpotifyAlbumTracks; /** * Currently only returns Spotify Web tracks not associated with a playlist. * @param player * @param qsOptions */ async function getSpotifyLikedSongs(qsOptions = {}) { return getSavedTracks(models_1.PlayerName.SpotifyWeb, qsOptions); } exports.getSpotifyLikedSongs = getSpotifyLikedSongs; /** * Currently only returns Spotify Web tracks not associated with a playlist. * @param player * @param qsOptions */ async function getSavedTracks(player, qsOptions = {}) { let tracks = []; if (player === models_1.PlayerName.SpotifyWeb) { tracks = await playlist.getSavedTracks(qsOptions); } return tracks; } exports.getSavedTracks = getSavedTracks; /** * Returns a playlist by ID * @param playlist_id ID is preferred, but we'll transform a URI to an ID */ async function getSpotifyPlaylist(playlist_id) { return playlist.getSpotifyPlaylist(playlist_id); } exports.getSpotifyPlaylist = getSpotifyPlaylist; /** * Returns the tracks that are found by the given playlist name * - currently spofity-web support only * @param player {spotify-web} * @param playlist_id (optional) * @param qsOptions (optional) {offset, limit} */ async function getPlaylistTracks(player, playlist_id, qsOptions = {}) { if (player === models_1.PlayerName.SpotifyWeb) { return playlist.getPlaylistTracks(playlist_id, qsOptions); } // itunes or spotify desktop const tracks = await getTracksByPlaylistName(player, playlist_id); let codyResp = new models_1.CodyResponse(); let pageItem = new models_1.PaginationItem(); pageItem.offset = 0; pageItem.next = ""; pageItem.previous = ""; pageItem.limit = -1; pageItem.total = tracks.length; pageItem.items = tracks; codyResp.data = pageItem; return codyResp; } exports.getPlaylistTracks = getPlaylistTracks; /** * Plays a playlist at the beginning if the starting track id is not provided. * @param playlistId either the ID or URI of the playlist * @param startingTrackId either the ID or URI of the track * @param deviceId */ function playSpotifyPlaylist(playlistId, startingTrackId = "", deviceId = "") { return musicCtr.spotifyWebPlayPlaylist(playlistId, startingTrackId, deviceId); } exports.playSpotifyPlaylist = playSpotifyPlaylist; /** * Plays a specific track on the Spotify or iTunes desktop * @param player * @param params * spotify example ["spotify:track:0R8P9KfGJCDULmlEoBagcO", "spotify:album:6ZG5lRT77aJ3btmArcykra"] * -- provide the trackID then the album or playlist ID * -- they can either be in either URI or ID format * itunes example ["Let Me Down Slowly", "MostRecents"] * -- provide the track name then the playlist name */ function playTrackInContext(player, params) { return musicCtr.playTrackInContext(player, params); } exports.playTrackInContext = playTrackInContext; /** * Mac iTunes only * This will allow you to play a playlist starting at a specific playlist track number. */ function playItunesTrackNumberInPlaylist(playlistName, trackNumber) { const emptyParams = []; const scriptArgs = [playlistName, trackNumber]; return musicCtr.run(models_1.PlayerName.ItunesDesktop, "playTrackNumberInPlaylist", emptyParams, scriptArgs); } exports.playItunesTrackNumberInPlaylist = playItunesTrackNumberInPlaylist; /** * Quits/closes the mac Spotify or iTunes player * @param player */ function quitMacPlayer(player) { return musicCtr.quitApp(player); } exports.quitMacPlayer = quitMacPlayer; /** * This is only meant for Mac iTunes or Mac Spotify desktop * @param player * @param params */ async function playTrackInLibrary(player, params) { return await musicCtr.run(player, "playSongFromLibrary", params); } exports.playTrackInLibrary = playTrackInLibrary; /** * Initiate and play the specified Spotify device * @param device_id {string} */ function playSpotifyDevice(device_id) { return musicCtr.playPauseSpotifyDevice(device_id, true); } exports.playSpotifyDevice = playSpotifyDevice; /** * Initiate and play the specified Spotify device * @param device_id {string} * @param play {boolean} true to play and false to keep current play state */ function transferSpotifyDevice(device_id, play) { return musicCtr.playPauseSpotifyDevice(device_id, play); } exports.transferSpotifyDevice = transferSpotifyDevice; /** * Check if the access/refresh tokens have expired */ function accessExpired() { return userProfile.accessExpired(); } exports.accessExpired = accessExpired; /** * Fetch the user's profile */ function getUserProfile() { return userProfile.getUserProfile(); } exports.getUserProfile = getUserProfile; /** * Helper API to return whether or not the user is logged in to their spotify account or not. * It's not fool proof as it only determines if there are any devices found or not. * {oauthActivated, loggedIn} */ function spotifyAuthState() { return userProfile.spotifyAuthState(); } exports.spotifyAuthState = spotifyAuthState; /** * Initiate the play command for a specific player * @param player {spotify|spotify-web|itunes} * @param options { uris, device_id } * example * -- the uris can be in either URI or ID format * {device_id: <spotify_device_id>, uris: ["spotify:track:4iV5W9uYEdYUVa79Axb7Rh", "spotify:track:1301WleyT98MSxVHPZCA6M"], context_uri: <playlist_uri, album_uri>} */ function play(player, options = {}) { if (player === models_1.PlayerName.SpotifyWeb) { return musicCtr.spotifyWebPlay(options); } else { return musicCtr.run(player, "play"); } } exports.play = play; /** * Play a specific spotify track by trackId (it can be the URI or the ID) * @param trackId * @param deviceId (optional) */ function playSpotifyTrack(trackId, deviceId = "") { return musicCtr.spotifyWebPlayTrack(trackId, deviceId); } exports.playSpotifyTrack = playSpotifyTrack; /** * Initiate the play command for a given trackId for a specific player * @param player {spotify|spotify-web|itunes} * @param trackId {any (string|number)} */ function playTrack(PlayerName, trackId) { return musicCtr.run(PlayerName, "playTrack", [trackId]); } exports.playTrack = playTrack; /** * Initiate the pause command for a given player * @param player {spotify|spotify-web|itunes} * @param options */ function pause(player, options = {}) { if (player === models_1.PlayerName.SpotifyWeb) { return musicCtr.spotifyWebPause(options); } else { return musicCtr.run(player, "pause"); } } exports.pause = pause; /** * Initiate the play/pause command for a given player * @param player {spotify|spotify-web|itunes} * @param options */ function playPause(player) { return musicCtr.run(player, "playPause"); } exports.playPause = playPause; /** * Initiate the next command for a given player * @param player {spotify|spotify-web|itunes} * @param options */ function next(player, options = {}) { if (player === models_1.PlayerName.SpotifyWeb) { return musicCtr.spotifyWebNext(options); } else { return musicCtr.run(player, "next"); } } exports.next = next; /** * Initiate the previous command for a given player * @param player {spotify|spotify-web|itunes} * @param options */ function previous(player, options = {}) { if (player === models_1.PlayerName.SpotifyWeb) { return musicCtr.spotifyWebPrevious(options); } else { return musicCtr.run(player, "previous"); } } exports.previous = previous; /** * Repeats a playlist * @param player * @param deviceId */ function setRepeatPlaylist(player, deviceId = "") { if (player === models_1.PlayerName.SpotifyWeb) { return musicPlayerCtr.setPlaylistRepeat(deviceId); } else { return musicCtr.run(player, "repeatOn"); } } exports.setRepeatPlaylist = setRepeatPlaylist; /** * Repeats a track * @param player * @param deviceId */ function setRepeatTrack(player, deviceId = "") { if (player === models_1.PlayerName.SpotifyWeb) { return musicPlayerCtr.setTrackRepeat(deviceId); } else { return musicCtr.run(player, "repeatOn"); } } exports.setRepeatTrack = setRepeatTrack; /** * Turn repeat off * @param player * @param deviceId */ function setRepeatOff(player, deviceId = "") { if (player === models_1.PlayerName.SpotifyWeb) { return musicPlayerCtr.setRepeatOff(deviceId); } else { return musicCtr.run(player, "repeatOff"); } } exports.setRepeatOff = setRepeatOff; /** * Turn on/off repeat for a given player * @param player {spotify|spotify-web|itunes} * @param options */ function setRepeat(player, repeat, deviceId = "") { if (player === models_1.PlayerName.SpotifyWeb || (player === models_1.PlayerName.SpotifyDesktop && musicUtil.isWindows())) { return musicPlayerCtr.updateRepeatMode(repeat, deviceId); } else { let repeatParam = repeat ? "repeatOn" : "repeatOff"; return musicCtr.run(player, repeatParam); } } exports.setRepeat = setRepeat; /** * Turn on/off shuffling for a given player * @param player {spotify|spotify-web|itunes} */ function setShuffle(player, shuffle, deviceId = "") { if (player === models_1.PlayerName.SpotifyWeb) { // use spotify web api return musicPlayerCtr.setShuffle(shuffle, deviceId); } else { let shuffleParam = shuffle ? ["true"] : ["false"]; return musicCtr.run(player, "setShuffling", shuffleParam); } } exports.setShuffle = setShuffle; /** * Return whether shuffling is on or not * @param player {spotify|spotify-web|itunes} */ async function isShuffling(player) { if (player === models_1.PlayerName.SpotifyWeb) { // use the web api } const val = await musicCtr.run(player, "isShuffling"); if (musicUtil.isBooleanString(val)) { return JSON.parse(val); } return val; } exports.isShuffling = isShuffling; /** * Returns whether the player is on repeat or not * - spotify returns true or false, and itunes returns "off", "one", "all" * @param player {spotify|spotify-web|itunes} */ async function isRepeating(player) { let val = await musicCtr.run(player, "isRepeating"); if (musicUtil.isBooleanString(val)) { return JSON.parse(val); } return val; } exports.isRepeating = isRepeating; /** * Update the players volume * @param player {spotify|spotify-web|itunes} * @param volume {0-100} */ function setVolume(player, volume) { return musicCtr.setVolume(player, volume); } exports.setVolume = setVolume; /** * Increments the players volume by a number * @param player {spotify|spotify-web|itunes} */ function volumeUp(player) { return musicCtr.run(player, "volumeUp"); } exports.volumeUp = volumeUp; /** * Decrements the players volume by a number * @param player {spotify|spotify-web|itunes} */ function volumeDown(player) { return musicCtr.run(player, "volumeDown"); } exports.volumeDown = volumeDown; /** * Mutes the players volume * @param player {spotify|spotify-web|itunes} */ function mute(player, device_id = "") { if (player === models_1.PlayerName.SpotifyWeb) { return musicPlayerCtr.setMute(true, device_id); } return musicCtr.run(player, "mute"); } exports.mute = mute; /** * Unmutes the players volume * @param player {spotify|spotify-web|itunes} */ function unmute(player, device_id = "") { if (player === models_1.PlayerName.SpotifyWeb) { return musicPlayerCtr.setMute(false, device_id); } return musicCtr.run(player, "unMute"); } exports.unmute = unmute; /** * Unmutes the players volume * @param player {spotify|spotify-web|itunes} */ function setItunesLoved(loved) { return musicCtr.setItunesLoved(loved); } exports.setItunesLoved = setItunesLoved; /** * Save tracks to your liked playlist * @param trackIds (i.e. ["4iV5W9uYEdYUVa79Axb7Rh", "1301WleyT98MSxVHPZCA6M"]) */ function saveToSpotifyLiked(trackIds) { return playlist.saveToSpotifyLiked(trackIds); } exports.saveToSpotifyLiked = saveToSpotifyLiked; /** * Remove tracks from your liked playlist * @param trackIds (i.e. ["4iV5W9uYEdYUVa79Axb7Rh", "1301WleyT98MSxVHPZCA6M"]) */ function removeFromSpotifyLiked(trackIds) { return playlist.removeFromSpotifyLiked(trackIds); } exports.removeFromSpotifyLiked = removeFromSpotifyLiked; /** * Returns the playlists for a given player * @param player {spotify|spotify-web|itunes} * @param (optional) {limit, offset, all} */ async function getPlaylists(player, qsOptions = {}) { let playlists = []; if (player === models_1.PlayerName.SpotifyWeb) { playlists = await playlist.getPlaylists(qsOptions); } else { let result = await musicCtr.run(player, "playlistTrackCounts"); if (result) { try { if (result.indexOf("[TRACK_END],") !== -1) { result = result.split("[TRACK_END],"); } else { result = result.split("[TRACK_END]"); } if (result && result.length > 0) { for (let i = 0; i < result.length; i++) { let resultItem = result[i]; if (resultItem && resultItem.trim().length > 0) { try { // {name, count} let item = JSON.parse(resultItem.trim()); let playlistItem = new models_1.PlaylistItem(); playlistItem.type = "playlist"; playlistItem.public = true; playlistItem.name = item.name; playlistItem.id = item.name; playlistItem.tracks.total = item.count; if (player === models_1.PlayerName.ItunesDesktop) { playlistItem.playerType = models_1.PlayerType.MacItunesDesktop; } else { playlistItem.playerType = models_1.PlayerType.MacSpotifyDesktop; } playlists.push(playlistItem); } catch (err) { // } } } } } catch (err) { // } } } return playlists; } exports.getPlaylists = getPlaylists; /** * Get the full list of the playlist names for a given player * @param player {spotify|spotify-web|itunes} * @param qsOptions (optional) {limit, offset} */ async function getPlaylistNames(player, qsOptions = {}) { if (player === models_1.PlayerName.SpotifyWeb) { return playlist.getPlaylistNames(qsOptions); } // result will string of playlist names separated by a comma let result = await musicCtr.run(player, "playlistNames"); // trim the names just in case if (result) { result = result.split(","); // now trim result = result.map((name) => { return name.trim(); }); } return result; } exports.getPlaylistNames = getPlaylistNames; /** * Launches a player device * @param playerName {spotify|spotify-web|itunes} * @param options (spotify-web only) {playlist_id | album_id | track_id } */ function launchPlayer(playerName, options = {}) { if (playerName === models_1.PlayerName.SpotifyWeb) { return musicPlayerCtr.launchWebPlayer(options); } else { return musicCtr.startPlayer(playerName, options); } } exports.launchPlayer = launchPlayer; /** * Plays a Spotify track within a playlist. * It will also launch Spotify if it is not already available by checking the device Ids. * @param trackId (optional) If it's not supplied then the playlistId must be provided * @param playlistId (optional) If it's not supplied then the trackId must be provided * @param playerName (optional) SpotifyWeb or SpotifyDesktop */ function launchAndPlaySpotifyTrack(trackId = "", playlistId = "", playerName = models_1.PlayerName.SpotifyWeb) { return musicPlayerCtr.launchAndPlaySpotifyTrack(trackId, playlistId, playerName); } exports.launchAndPlaySpotifyTrack = launchAndPlaySpotifyTrack; /** * Plays a Spotify Mac Desktop track within a playlist. * It will also launch Spotify if it is not already available by checking the device Ids. * @param trackId (optional) If it's not supplied then the playlistId must be provided * @param playlistId (optional) If it's not supplied then the trackId must be provided */ function playSpotifyMacDesktopTrack(trackId = "", playlistId = "") { musicCtr.playSpotifyDesktopTrack(trackId, playlistId); } exports.playSpotifyMacDesktopTrack = playSpotifyMacDesktopTrack; /** * Returns available Spotify devices * @returns {Promise<PlayerDevice[]>} */ function getSpotifyDevices() { return musicPlayerCtr.getSpotifyDevices(); } exports.getSpotifyDevices = getSpotifyDevices; /** * Returns the genre for a provided arguments * @param artist {string} is required * @param songName {string} is optional * @param spotifyArtistId {string} is optional */ function getGenre(artist, songName = "", spotifyArtistId = "") { return musicCtr.getGenre(artist, songName, spotifyArtistId); } exports.getGenre = getGenre; /** * Returns the spotify genre for a provided arguments * @param artist {string} is required * @param spotifyArtistId {string} is optional */ function getSpotifyGenre(artist) { return musicCtr.getGenreFromSpotify(artist); } exports.getSpotifyGenre = getSpotifyGenre; /** * Returns the spotify genre for a provided arguments * @param spotifyArtistId {string} is required */ function getSpotifyGenreByArtistId(spotifyArtistId) { return musicCtr.getGenreFromSpotify("" /*artist name*/, spotifyArtistId); } exports.getSpotifyGenreByArtistId = getSpotifyGenreByArtistId; /** * Returns the highest frequency single genre from the provided list * @param genreList */ function getHighestFrequencySpotifyGenre(genreList) { return musicCtr.getHighestFrequencySpotifyGenre(genreList); } exports.getHighestFrequencySpotifyGenre = getHighestFrequencySpotifyGenre; /** * Returns the recent top tracks Spotify for a user. */ function getTopSpotifyTracks() { return playlist.getTopSpotifyTracks(); } exports.getTopSpotifyTracks = getTopSpotifyTracks; /** * Returns the audio features of the given track IDs * @param ids these are the track ids (sans spotify:track) */ function getSpotifyAudioFeatures(ids) { return audioStat.getSpotifyAudioFeatures(ids); } exports.getSpotifyAudioFeatures = getSpotifyAudioFeatures; /** * Create a playlist for a Spotify user. (The playlist will be empty until you add tracks.) * @param name the name of the playlist you want to create * @param isPublic if the playlist will be public or private * @param description (Optioal) displayed in Spotify Clients and in the Web API */ function createPlaylist(name, isPublic, description = "") { return playlist.createPlaylist(name, isPublic, description); } exports.createPlaylist = createPlaylist; /** * Deletes a playlist of a given playlist ID. * @param playlist_id (uri or id) */ function deletePlaylist(playlist_id) { return playlist.deletePlaylist(playlist_id); } exports.deletePlaylist = deletePlaylist; /** * Follow a playlist of a given playlist ID. * @param playlist_id (uri or id) */ function followPlaylist(playlist_id) { return playlist.followPlaylist(playlist_id); } exports.followPlaylist = followPlaylist; /** * Replace tracks of a given playlist. This will wipe out * the current set of tracks and add the tracks specified. * @param playlist_id * @param track_ids */ function replacePlaylistTracks(playlist_id, track_ids) { return playlist.replacePlaylistTracks(playlist_id, track_ids); } exports.replacePlaylistTracks = replacePlaylistTracks; /** * Add tracks to a given Spotify playlist. * @param playlist_id the Spotify ID for the playlist * @param tracks Tracks should be the uri (i.e. "spotify:track:4iV5W9uYEdYUVa79Axb7Rh") * but if it's only the id (i.e. "4iV5W9uYEdYUVa79Axb7Rh") this will add * the uri part "spotify:track:" * @param position The position to insert the tracks, a zero-based index. */ function addTracksToPlaylist(playlist_id, tracks, position = 0) { return playlist.addTracksToPlaylist(playlist_id, tracks, position); } exports.addTracksToPlaylist = addTracksToPlaylist; /** * Remove tracks from a given Spotify playlist. * @param playlist_id the Spotify ID for the playlist * @param tracks Tracks should be the uri (i.e. "spotify:track:4iV5W9uYEdYUVa79Axb7Rh") * but if it's only the id (i.e. "4iV5W9uYEdYUVa79Axb7Rh") this will add * the uri part "spotify:track:" */ function removeTracksFromPlaylist(playlist_id, tracks) { return playlist.removeTracksFromPlaylist(playlist_id, tracks); } exports.removeTracksFromPlaylist = removeTracksFromPlaylist; /** * Returns whether or not the spotify access token has been provided. * @returns <boolean> */ function requiresSpotifyAccessInfo() { return !musicStore.hasSpotifyAccessToken() ? true : false; } exports.requiresSpotifyAccessInfo = requiresSpotifyAccessInfo; /** * Deprecated - use "getTrack(player)" */ function getPlayerState(player) { return getTrack(player); } exports.getPlayerState = getPlayerState; /** * Deprecated - use "getRunningTrack()" instead */ function getCurrentlyRunningTrackState() { return getRunningTrack(); } exports.getCurrentlyRunningTrackState = getCurrentlyRunningTrackState; /** * Deprecated - please use "getPlayerState" */ function getState(player) { return getTrack(player); } exports.getState = getState; /** * Deprecated - please use "launchPlayer('spotify')" **/ function startSpotifyIfNotRunning() { return musicCtr.launchApp(models_1.PlayerName.SpotifyDesktop); } exports.startSpotifyIfNotRunning = startSpotifyIfNotRunning; /** * Deprecated - please use "launchPlayer('itunes')" */ function startItunesIfNotRunning() { return musicCtr.launchApp(models_1.PlayerName.ItunesDesktop); } exports.startItunesIfNotRunning = startItunesIfNotRunning; /** * Deprecated - please use "isSpotifyRunning" or "isItunesRunning" */ function isRunning(player) { return isPlayerRunning(player); } exports.isRunning = isRunning; /** * Deprecated - please use "setRepat(player, repeat)" */ function repeatOn(player) { return setRepeat(player, true); } exports.repeatOn = repeatOn; /** * Deprecated - please use "setRepat(player, repeat)" */ function repeatOff(player) { return setRepeat(player, false); } exports.repeatOff = repeatOff; /** * Deprecated - please use "unmute(player)" */ function unMute(player) { return unmute(player); } exports.unMute = unMute; /** * Deprecated - please use "setConfig(config: CodyConfig)" * Set Credentials (currently only supports Spotify) * Accepted credentials: clientId, clientSecret, refreshToken, accessToken * @param credentials */ function setCredentials(credentials) { musicStore.setCredentials(credentials); } exports.setCredentials = setCredentials; /** * Deprecated - please use "getSpotifyAccessToken()" * Get the accessToken provided via through the setCredentials api * @returns {string} the access token string */ function getAccessToken() { return musicStore.credentialByKey("spotifyAccessToken"); } exports.getAccessToken = getAccessToken; //# sourceMappingURL=apis.js.map