Skip to content

patrickkfkan/soundcloud-fetch

Repository files navigation

soundcloud-fetch

Fetches SoundCloud resources through API v2.

This project was created primarily for use with the SoundCloud plugin for Volumio. Its scope of application might therefore be limited. If you need a more general-purpose API, you might want to take a look at soundcloud.ts.

npm i --save soundcloud-fetch
import SoundCloud from 'soundcloud-fetch';

const api = new SoundCloud({
  accessToken: ...
});

const album = await api.getPlaylistOrAlbum(...);
const myLikes = await api.me.getLikes({ type: 'track'});
...

API

Constructor

new SoundCloud([args])

Constructs an instance of the SoundCloud API.

args: (optional)

  • clientId: (string) (optional) Client ID for making API requests. If not specified, value will be obtained from SoundCloud website.
  • accessToken: (string) (optional) Token for accessing your private resources. See How to obtain an access token.
  • locale: (string) (optional) Locale code as defined in Constants.

Config

getClientId()

Returns

The Client ID used by the API.


static generateClientId()

Fetches the Client ID from SoundCloud website. Normally, you don't have to call this method as it is automatically called during initialization of the API (unless you provided one yourself in constructor args).

Returns

Client ID from SoundCloud website.


setLocale([locale])

Sets the locale.

Params

  • locale: (string) (optional) The locale to set. If undefined, the locale will be determined by SoundCloud.

setAccessToken([value])

Sets the access token.

Params

  • value: (string) (optional) The access token to be used by the API. If undefined, access to your private resources will trigger an error.

Selections

getMixedSelections([options])

Fetches mixed selections.

Params

options: (optional)

  • limit: (number) (optional) The number of items to return.

Returns

Promise that resolves to a Collection of Selection objects.


Playlists / Albums / Tracks

getPlaylistOrAlbum(id)

Fetches a playlist or album with the given id.

In SoundCloud, an album is a type of playlist with overlapping and distinct properties. To check whether an item returned by this method is a playlist or album, inspect its type property or use instanceof:

const item = await api.getPlaylistOrAlbum(id);

if (item && item.type === Album.type) { // <-- item is an Album
  const album = item as Album; // Type assertion
  const genre = album.genre;   // Access Album-specific properties
}

// or

if (item instanceof Album) {
  const genre = item.genre;  // No need to do type assertion here
}

Params

  • id: (number) The ID of the playlist or album to fetch.

Returns

Promise that resolves to an instance of Album or Playlist, or null if fetched result is neither an album nor a playlist.


getSystemPlaylist(id)

Fetches a system playlist with the given id.

Params

  • id: (string) The ID of the system playlist to fetch.

Returns

Promise that resolves to an instance of SystemPlaylist, or null if fetched result is not a system playlist.


getPlaylistsByUser(userId, [options])

Fetches the playlists created by the user with the given userId. The fetched items do not include albums.

Params

  • userId: (number) The ID of the user.
  • options: (optional)
    • limit: (number) (optional) The number of items to return.

Returns

Promise that resolves to a Collection of Playlist objects.


getAlbumsByUser(userId, [options])

Fetches the albums created by the user with the given userId. The fetched items do not include playlists.

Params

  • userId: (number) The ID of the user.
  • options: (optional)
    • limit: (number) (optional) The number of items to return.

Returns

Promise that resolves to a Collection of Album objects.


getTopFeaturedTracks([options])

Fetches the top-featured tracks.

Params

options (optional)

  • genre: (string) (optional) The genre of tracks to fetch.
  • limit: (number) (optional) The number of items to return.

Returns

Promise that resolves to a Collection of Track objects.


getTracks(ids)

Fetches the track(s) with the given ids.

Params

  • ids: (number | number[]) The IDs of the tracks to fetch. If ids is a number, as oppose to an array of numbers, then result will contain a single track matching it.

Returns

Promise that resolves to a Collection of Track objects.


getTracksByUser(userId, [options])

Fetches the tracks uploaded by the user with the given userId.

Params

  • userId: (number) The ID of the user.
  • options: (optional)
    • limit: (number) (optional) The number of items to return.

Returns

Promise that resolves to a Collection of Track objects.


getTrack(id)

Fetches the track with the given id.

Params

  • ids: (number) The ID of the track to fetch.

Returns

Promise that resolves to a Track object, or null if no result.


getLikesByUser(userId, options)

Fetches the items liked by the user with the given userId.

Params

  • userId: (number) The ID of the user.
  • options:
    • type: (string) The type of resource to fetch. Can be one of the following values: track | playlistAndAlbum.
    • limit: (number) (optional) The number of items to return.

Returns

Promise that resolves to a Collection of Like objects. For each Like:

  • if type is track, Like.item points to a Track object;
  • if type is playlistAndAlbum, Like.item points to an Album or Playlist object.

Note that Like.item can also be null if the item could not be parsed.


getStreamingUrl(transcodingUrl)

Fetches the streaming URL from transcodingUrl.

Transcoding URLs are embedded in the mediaInfo.transcodings property of a Track object. See example.

Params

  • transcodingUrl: (string) The transcoding URL for a Track.

Returns

Promise that resolves to the streaming URL, or null if no result.


Users

getUser(id)

Fetches the user given by id.

Params

  • id: (number) The ID of the user to fetch.

Returns

Promise that resolves to a User object, or null if no result.


getFollowing(userId, [options])

Fetches the list of users followed by the user with the given userId.

Params

  • userId: (number) The ID of the user.
  • options: (optional)
    • limit: (number) (optional) The number of items to return.

Returns

Promise that resolves to a Collection of User objects.


Search

search(q, options)

Performs a search.

Params

  • q: (string) Search query.
  • options:
    • type: (string) The type of resource to search for. Can be one of the following values: playlist | album | track | user.
    • limit: (number) (optional) The number of items to return.

Returns

Promise that resolves to a Collection of Playlist, Album, Track or User objects (depending on type you passed in options) matching the given search query.


Private resources

These methods require a valid access token, which you can provide in the constructor or through setAccessToken(). Private resources methods are grouped under me:

import SoundCloud from 'soundcloud-fetch';

const api = new SoundCloud({
  accessToken: ...
});

const profile = await api.me.getProfile();
...
me.getProfile()

Fetches your user profile.

Returns

Promise that resolves to a User object representing your user profile, or null if no result.


me.getPlayHistory(options)

Fetches items from your play history.

Params

  • options:
    • type: (string) The type of resource to fetch. Can be one of the following values: track | set.
    • limit: (number) (optional) The number of items to return.

Returns

Promise that resolves to a Collection of PlayHistoryItem objects. For each PlayHistoryItem:

Note that PlayHistoryItem.item can also be null if the item could not be parsed.


me.getLibraryItems([options])

Fetches items from your library.

Params

  • options: (optional)
    • limit: (number) (optional) The number of items to return.

Returns

Promise that resolves to a Collection of LibraryItem objects. Each LibraryItem wraps around an Album, Playlist or SystemPlaylist object, as well as null if an item could not be parsed. You can obtain the wrapped item through LibraryItem.item, as well as inspect the itemType property to get its exact type (such as whether it is liked).


me.getLikes(options)

Fetches items you have liked.

This is a convenience method that passes your User ID to getLikesByUser(userId, options), and thus have the same return type and options param as that method.


me.getStations([options])

Fetches the artist stations added to your library. An artist station is represented by a SystemPlaylist.

Note that me.getLibraryItems() also returns artist stations. If you are presenting results from both method calls, you might want to check the type of SystemPlaylist through its playlistType property to filter out overlaps.

Params

  • options: (optional)
    • limit: (number) (optional) The number of items to return.

Returns

Promise that resolves to a Collection of LibraryItem objects. Use LibraryItem.item to obtain the SystemPlaylist object representing an artist station.


me.getFollowing([options])

Fetches the users you are following.

This is a convenience method that passes your User ID to getFollowing(userId, [options]), and thus have the same return type and options param as that method.


me.addToPlayHistory(trackOrUrn, [setOrUrn])

Adds the track given by trackOrUrn, and optionally the album, playlist or system playlist given by setOrUrn, to your play history.

Params

  • trackOrUrn: (Track | string) The track or URN of the track to add to play history. You can obtain the URN of a Track through its apiInfo.urn property.
  • setOrUrn: (Album | Playlist | SystemPlaylist | string) (optional) The album, playlist, system playlist or URN of system playlist to add to play history. You can obtain the URN of a SystemPlaylist through its apiInfo.urn property.

Note that albums and playlists do not have URNs, at least not from data returned by SoundCloud. If you must pass an URN for an album or playlist, you can provide a string in the following format (this is what the API generates internally):

// Substitute <id> with playlist or album ID
soundcloud:playlists:<id>

Fetching tracks of playlists, albums and system playlists

You will note that the Playlist, Album and SystemPlaylist classes do not define a tracks property. To obtain the tracks of these items, call the getTracks() method:

const api = new SoundCloud();
const playlist = api.getPlaylistOrAlbum(...);
if (playlist) {
  const tracks = await playlist.getTracks();
  ...
}

In the above example, getTracks() returns an array of Track objects.

Accessing underlying data

Call getJSON() to access the underlying data of a fetched item:

const api = new SoundCloud();
const track = await api.getTrack(...);
if (track) {
  // Gets the 'track_authorization' field of underlying data
  const trackAuthorization = track.getJSON<string>('track_authorization');

  // Gets the full underlying data
  const fullData = track.getJSON();
}

Collections

When a method returns a collection of items, it does so through an instance of the Collection class. A Collection has the following key properties:

  • items: (Array) The items fetched.
  • continuation: (CollectionContinuation | null) An object encapsulating the data required by the API for fetching the next set of items; null if there are no more items available.

The continuation property can be used to obtain further items as follows:

const api = new SoundCloud();
const tracks = await api.getTopFeaturedTracks();
if (tracks.continuation) { // More items available
  const moreTracks = await api.getContinuation(tracks.continuation);
  ...
}

In the above example, getContinuation() returns another instance of Collection containing the next set of Track objects.

Changelog

1.0.2:

  • Fix connection error in getClientId()

1.0.1:

  • Apply access token in getStreamingUrl()

1.0.0:

  • Initial release

License

MIT

About

Fetches SoundCloud resources through API v2.

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published