• Stars
    star
    376
  • Rank 113,810 (Top 3 %)
  • Language
    Objective-C
  • Created about 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A react native module for the Spotify SDK. [Deprecated]

Spotify for React Native

A react native module for the Spotify SDK

NOTE: This repo is using the deprecated Spotify streaming SDKs. I have been told by users that it is now no longer functional, since Spotify has turned off the API.

react-native-spotify-remote is being worked on by cjam to use the newer "remote" SDK.

Install

To add the Spotify SDK to your project, cd into your project directory and run the following commands:

npm install --save rn-spotify-sdk
react-native link react-native-events
react-native link rn-spotify-sdk

Next, do the manual setup for each platform:

iOS

Manually add SpotifyMetadata.framework and SpotifyAudioPlayback.framework from node_modules/rn-spotify-sdk/ios/external/SpotifySDK to Linked Frameworks and Libraries in your project settings. Then add ../node_modules/rn-spotify-sdk/ios/external/SpotifySDK to Framework Search Paths in your project settings.

Android

Edit android/build.gradle and add flatDir

...
allprojects {
	repositories {
		mavenLocal()
		jcenter()
		maven {
			// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
			url "$rootDir/../node_modules/react-native/android"
		}
		flatDir {
			dirs project(':rn-spotify-sdk').file('libs'), 'libs'
		}
	}
}
...

Edit android/app/build.gradle and add packagingOptions

...
buildTypes {
    release {
        minifyEnabled enableProguardInReleaseBuilds
        proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
    }
}
packagingOptions {
    pickFirst 'lib/armeabi-v7a/libgnustl_shared.so'
    pickFirst 'lib/x86/libgnustl_shared.so'
    exclude 'lib/arm64-v8a/libgnustl_shared.so'
    exclude 'lib/x86_64/libgnustl_shared.so'
}
...

In some cases, the two exclude lines cause issues when compiling and can be omitted. I need to look further into what causes this.

On Android, react-native link has a bug where it imports RNSpotifyPackage using the wrong bundle. You may have to make the following change to MainApplication.java:

...
import com.spotify.sdk.android.authentication.RNSpotifyPackage; // remove this line
import com.lufinkey.react.spotify.RNSpotifyPackage; // replace with this line
...

If you have issues linking the module, please check that gradle is updated to the latest version and that your project is synced. Please reference the example app to ensure you've implemented things correctly before opening any issues.

Usage

import Spotify from 'rn-spotify-sdk';

Types

  • Session

    Contains information about a session

    • Properties

      • accessToken - A token used to communicate with the Spotify API
      • expireTime - The time that the access token expires, in milliseconds from January 1, 1970 00:00:00 UTC
      • refreshToken - An encrypted token used to get a new access token when they expire. This should be encrypted by your token swap service, as per OAuth standards.
      • scopes - An array of scopes that the session has access to. A list of scopes can be found here.
  • PlaybackState

    Contains information about the current state of the player

    • Properties

      • playing - boolean indicating whether the player is playing
      • repeating - boolean indicating whether the player is repeating
      • shuffling - boolean indicating whether the player is shuffling
      • activeDevice - boolean indicating whether the current device is the one playing
      • position - the position of the player in the current track, in seconds
  • PlaybackTrack

    Contains information about a track in the playback queue

    • Properties

      • name - The title of the track
      • uri - The uri of the track
      • contextName - The name of the playlist or album that the track is being played from
      • contextUri - The uri of the playlist or album that the track is being played from
      • artistName - The name of the track's artist
      • artistUri - The uri of the track's artist
      • albumName - The name of the album that the track belongs to
      • albumUri - The uri of the album that the track belongs to
      • albumCoverArtURL - A URL for the album art image
      • duration - The length of the track in seconds
      • indexInContext - The track index in the playlist or album that the track is being played from
  • PlaybackMetadata

    Contains information about the previous, current, and next tracks in the player

    • Properties

      • prevTrack - A PlaybackTrack with information about the previous track
      • currentTrack - A PlaybackTrack with information about the current track
      • nextTrack - A PlaybackTrack with information about the next track
  • PlaybackEvent

    Contains information about a playback event and the state of the player.

    • Properties

      • state - the player's current PlaybackState
      • metadata - the player's current PlaybackMetadata

Events

This module uses react-native-events, so it has all of the same methods as an EventEmitter object. All of the events except for 'disconnect' / 'reconnect' (on Android) and 'login' / 'logout' come from Spotify's native SDK and are simply forwarded to javascript. If one of these events occurs at a weird time or has strange data, please open an issue on Spotify's ios-streaming-sdk or android-streaming-sdk repo, and not here.

  • 'login'

    • session {Session}

    Emitted when the module has successfully logged in.

  • 'logout'

    Emitted when the module is logged out.

  • 'sessionRenewed'

    • session {Session}

    Emitted when the session has been renewed.

  • 'play'

    • event {PlaybackEvent}

    Emitted when playback has started or has resumed.

  • 'pause'

    • event {PlaybackEvent}

    Emitted when playback is paused.

  • 'trackChange'

    • event {PlaybackEvent}

    Emitted when playback of a new/different track starts.

  • 'metadataChange'

    • event {PlaybackEvent}

    Emitted when metadata has changed. This event occurs when playback starts or changes to a different context, when a track switch occurs, etc. This is an informational event that does not require action, but should be used to keep the UI display updated with the latest metadata information.

  • 'contextChange'

    • event {PlaybackEvent}

    Emitted when playback starts or changes to a different context than was playing before, such as a change in album or playlist.

  • 'shuffleStatusChange'

    • event {PlaybackEvent}

    Emitted when "shuffle" is switched on or off.

  • 'repeatStatusChange'

    • event {PlaybackEvent}

    Emitted when "repeat" is switched on or off.

  • 'active'

    • event {PlaybackEvent}

    Emitted when this device has become the active playback device. This event occurs when the users moves playback to this device using Spotify Connect.

  • 'inactive'

    • event {PlaybackEvent}

    Emitted when this device is no longer the active playback device. This event occurs when the user moves playback to a different device using Spotify Connect.

  • 'permissionLost'

    • event {PlaybackEvent}

    Emitted when this device has temporarily lost permission to stream audio from Spotify. A user can only stream audio on one of her devices at any given time. If playback is started on a different device, this event may occur.

  • 'audioFlush'

    • event {PlaybackEvent}

    Emitted when the application should flush its audio buffers (you don't need to deal with this since that's handled by the native code). For example, this event occurs when seeking to a different position within a track.

  • 'audioDeliveryDone'

    • event {PlaybackEvent}

    Emitted when the library reaches the end of a playback context and has no more audio to deliver.

  • 'trackDelivered'

    • event {PlaybackEvent}

    Emitted when the application accepted all samples from the current track. This is an informative event that indicates that all samples from the current track have been delivered to and accepted by the application. The track has not yet finished playing the last audio sample, but no more audio will be delivered for this track. For nearly all intents and purposes, the track has finished playing.

  • 'disconnect'

    Emitted when the player loses network connectivity.

  • 'reconnect'

    Emitted when the player regains network connectivity.

  • 'temporaryPlayerError'

    Emitted when service has been interrupted, usually by lack of network access. However, it can also occur if there is a problem with Spotify's backend services, or also when the user switches from WiFi to 3G. These errors can occur in many non-critical situations, and thus it is not necessary to show toasts or alert dialogs when receiving this event, or else you will unnecessarily annoy or panic the user. However, it can be useful to know about these events if operations are consistently failing, in which case showing a toast or alert may be justified.

  • 'playerMessage'

    • message {String}

    Called when the player has recieved a message for the end user from the Spotify service.

Initialization/Authorization Methods

  • initialize( options )

    Initializes the Spotify module and resumes a logged in session if there is one. This must be the first method you call when using this module.

    • Parameters

      • options - an object with options to pass to the Spotify Module
        • clientID - (Required) Your spotify application's client ID that you registered with spotify here
        • redirectURL - (Required) The redirect URL to use when you've finished logging in. You NEED to set this URL for your application here, otherwise the login screen will not close
        • sessionUserDefaultsKey - The preference key to use in order to store session data for this module. Set this to a string of your choice when you initialize in order to persist user information between app uses.
        • scopes - An array of scopes that define permissions for the Spotify API. A list of scopes can be found here
        • tokenSwapURL - The URL to use to swap an authentication code for an access token (see Token swap and refresh section for more info)
        • tokenRefreshURL - The URL to use to get a new access token from a refresh token
        • tokenRefreshEarliness - The number of seconds to set a token refresh timer before the access token expires. Default is 300
        • ios - iOS specific options
          • audioSessionCategory - The name of the audio session category to use for playing music in the app. Default is 'AVAudioSessionCategoryPlayback'
        • android - Android specific options
          • loginLoadingText - The "Loading" text that will show on the login popup
    • Returns

      • A Promise that resolves to a boolean when the module finishes initialization, indicating whether or not a session was automatically logged back in
  • isInitialized()

    Checks if the Spotify module has been initialized yet.

    • Returns

      • true if the Spotify module has been initialized
      • false if the Spotify module has not been initialized
  • isInitializedAsync()

    Checks if the Spotify module has been initialized yet, but returns a Promise that resolves to the result.

    • Returns

      • A Promise that resolves to a boolean, indicating whether or not the Spotify module has been initialized
  • login( options? )

    Opens a UI to log into Spotify.

    • Parameters

      • options
        • showDialog - Whether or not to force the user to approve the app again if they’ve already done so.
        • clientID - Your spotify application's client ID that you registered with spotify here. Falls back to value given in initialize.
        • redirectURL - The redirect URL to use when you've finished logging in. You NEED to set this URL for your application here, otherwise the login screen will not close. Falls back to value given in initialize.
        • scopes - An array of scopes that define permissions for the Spotify API. A list of scopes can be found here. Falls back to value given in initialize.
        • tokenSwapURL - The URL to use to swap an authentication code for an access token (see Token swap and refresh section for more info). Falls back to value given in initialize.
    • Returns

      • A Promise that resolves to a boolean, indicating whether or not the user was logged in
  • isLoggedIn()

    Checks if the client is logged in.

    • Returns

      • true if the client is logged in
      • false if the client is not logged in
  • isLoggedInAsync()

    Checks if the client is logged in, but returns a Promise that resolves to the result.

    • Returns

      • A Promise that resolves to a boolean, indicating whether or not a user is currently logged in
  • logout()

    Logs out of Spotify.

    • Returns

      • A Promise that resolves when the logout completes
  • getSession()

    Gives information about the current session.

    • Returns

      • An Session object, or null if not logged in
  • getSessionAsync()

    Gives information about the current session, but returns a Promise that resolves to the result.

    • Returns

      • A Promise that resolves to an Session object, or null if not logged in
  • renewSession()

    Renews a logged in session. If no token refresh URL was given to initialize or if the session does not have a refresh token, this function returns without error

    • Returns

      • A Promise that resolves when the session renewal attempt finishes
  • authenticate( options? )

    Opens a UI to perform the auth flow for Spotify, but returns a session instead of logging in.

    • Parameters

      • options
        • showDialog - Whether or not to force the user to approve the app again if they’ve already done so.
        • clientID - Your spotify application's client ID that you registered with spotify here. Falls back to value given in initialize.
        • redirectURL - The redirect URL to use when you've finished logging in. You NEED to set this URL for your application here, otherwise the login screen will not close. Falls back to value given in initialize.
        • scopes - An array of scopes that define permissions for the Spotify API. A list of scopes can be found here. Falls back to value given in initialize.
        • tokenSwapURL - The URL to use to swap an authentication code for an access token (see Token swap and refresh section for more info). Falls back to value given in initialize.
    • Returns

      • A Promise that resolves to an Session object, or null if login is cancelled
  • loginWithSession( options )

    Logs into the app with a given session

    • Parameters

      • options
        • accessToken (Required) - The token to use to communicate with the Spotify API.
        • expireTime (Required) - The time that the access token expires, in milliseconds from January 1, 1970 00:00:00 UTC
        • refreshToken - An encrypted token used to get a new access token when it expires.
        • scopes - An array of scopes that the session has access to. A list of scopes can be found here.
        • clientID - Your spotify application's client ID that you registered with spotify here. Falls back to value given in initialize.
        • tokenRefreshURL - The URL to use to get a new access token from a refresh token (see Token swap and refresh section for more info). Falls back to value given in initialize.
    • Returns

      • A Promise that resolves when the login finishes

Playback Methods

  • playURI( spotifyURI, startIndex, startPosition )

    Play a Spotify URI.

    • Parameters

      • spotifyURI - The Spotify URI to play
      • startIndex - The index of an item that should be played first, e.g. 0 - for the very first track in the playlist or a single track
      • startPosition - starting position for playback in seconds
    • Returns

      • A Promise that resolves or rejects when the operation is complete
  • queueURI( spotifyURI )

    Queue a Spotify URI. WARNING: This function has proven to be very inconsistent and buggy.

    • Parameters

      • spotifyURI - The Spotify URI to queue
    • Returns

      • A Promise that resolves or rejects when the operation is complete
  • setPlaying( playing )

    Set the “playing” status of the player.

    • Parameters

      • playing - true to resume playback, or false to pause it
    • Returns

      • A Promise that resolves or rejects when the operation is complete
  • getPlaybackState()

    Gives the player's current state.

    • Returns

      • A PlaybackState object, or null if the player has not yet initialized
  • getPlaybackStateAsync()

    Gives the player's current state, but returns a Promise that resolves to the result.

    • Returns

      • A Promise that resolves to a PlaybackState object or null if the player has not yet initialized
  • getPlaybackMetadata()

    Gives information about the previous, current, and next track in the player.

    • Returns

      • A PlaybackMetadata object, or null if the player has yet initialized
  • getPlaybackMetadataAsync()

    Gives information about the previous, current, and next track in the player, but returns a Promise that resolves to the result.

    • Returns

      • A Promise that resolves to a PlaybackMetadata object or null if the player has not yet initialized
  • skipToNext()

    Skips to the next track.

    • Returns

      • A Promise that resolves or rejects when the operation is complete
  • skipToPrevious()

    Skips to the previous track.

    • Returns

      • A Promise that resolves or rejects when the operation is complete
  • seek( position )

    Seeks to a position within the current track

    • Parameters

      • position - The position in seconds to seek to
    • Returns

      • A Promise that resolves or rejects when the operation is complete
  • setShuffling( shuffling )

    Enables or disables shuffling on the player.

    • Parameters

      • shuffling - true to enable shuffle, false to disable it
    • Returns

      • A Promise that resolves or rejects when the operation is complete
  • setRepeating( repeating )

    Enables or disables repeating on the player.

    • Parameters

      • repeating - true to enable repeat, false to disable it
    • Returns

      • A Promise that resolves or rejects when the operation is complete

Metadata Methods

  • sendRequest( endpoint, method, params, isJSONBody )

    Sends a general request to the spotify api. A list of potential endpoints can be found here.

    • Parameters

      • endpoint - the api endpoint, without a leading slash, e.g. 'v1/browse/new-releases'
      • method - the HTTP method to use
      • params - the request parameters
      • isJSONBody - whether or not to send the parameters as json in the body of the request
    • Returns

      • A Promise that resolves to the result of the API request
  • getMe()

    Retrieves information about the logged in Spotify user.

    • Returns

      • A Promise that resolves to the request result object. An example response can be seen here
  • search( query, types, options? )

    Sends a search request to spotify.

    • Parameters

      • query - The search query string. Same as the q parameter on the search endpoint
      • types - An array of item types to search for. Valid types are: 'album', 'artist', 'playlist', and 'track'.
      • options - A map of other optional parameters to specify for the query
    • Returns

      • A Promise that resolves to the search result object. An example response can be seen here
  • getAlbum( albumID, options? )

    Gets Spotify catalog information for a single album.

    • Parameters

      • albumID - The Spotify ID for the album
      • options - A map of other optional parameters to specify for the query
    • Returns

      • A Promise that resolves to the request result object. An example response can be seen here
  • getAlbums( albumIDs, options? )

    Gets Spotify catalog information for multiple albums identified by their Spotify IDs.

    • Parameters

      • albumIDs - An array of the Spotify IDs for the albums
      • options - A map of other optional parameters to specify for the query
    • Returns

      • A Promise that resolves to the request result object. An example response can be seen here
  • getAlbumTracks( albumID, options? )

    Gets Spotify catalog information about an album’s tracks.

    • Parameters

      • albumID - The Spotify ID for the album
      • options - A map of other optional parameters to specify for the query
    • Returns

      • A Promise that resolves to the request result object. An example response can be seen here
  • getArtist( artistID, options? )

    Gets Spotify catalog information for a single artist.

    • Parameters

      • artistID - The Spotify ID for the artist
      • options - A map of other optional parameters to specify for the query
    • Returns

      • A Promise that resolves to the request result object. An example response can be seen here
  • getArtists( artistIDs, options? )

    Gets Spotify catalog information for several artists based on their Spotify IDs.

    • Parameters

      • artistIDs - An array of the Spotify IDs for the artists
      • options - A map of other optional parameters to specify for the query
    • Returns

      • A Promise that resolves to the request result object. An example response can be seen here
  • getArtistAlbums( artistID, options? )

    Gets Spotify catalog information about an artist’s albums.

    • Parameters

      • artistID - The Spotify ID for the artist
      • options - A map of other optional parameters to specify for the query
    • Returns

      • A Promise that resolves to the request result object. An example response can be seen here
  • getArtistTopTracks( artistID, country, options? )

    Gets Spotify catalog information about an artist’s top tracks by country.

    • Parameters

      • artistID - The Spotify ID for the artist
      • country - The country: an ISO 3166-1 alpha-2 country code.
      • options - A map of other optional parameters to specify for the query
    • Returns

      • A Promise that resolves to the request result object. An example response can be seen here
  • getArtistRelatedArtists( artistID, options? )

    Gets Spotify catalog information about artists similar to a given artist.

    • Parameters

      • artistID - The Spotify ID for the artist
      • options - A map of other optional parameters to specify for the query
    • Returns

      • A Promise that resolves to the request result object. An example response can be seen here
  • getTrack( trackID, options? )

    Gets Spotify catalog information for a single track identified by its unique Spotify ID.

    • Parameters

      • trackID - The Spotify ID for the track
      • options - A map of other optional parameters to specify for the query
    • Returns

      • A Promise that resolves to the request result object. An example response can be seen here
  • getTracks( trackIDs, options? )

    Gets Spotify catalog information for multiple tracks based on their Spotify IDs.

    • Parameters

      • trackIDs - An array of the Spotify IDs for the tracks
      • options - A map of other optional parameters to specify for the query
    • Returns

      • A Promise that resolves to the request result object. An example response can be seen here
  • getTrackAudioAnalysis( trackID, options? )

    Gets a detailed audio analysis for a single track identified by its unique Spotify ID.

    • Parameters

      • trackID - The Spotify ID for the track
      • options - A map of other optional parameters to specify for the query
    • Returns

      • A Promise that resolves to the request result object. An example response can be seen here
  • getTrackAudioFeatures( trackID, options? )

    Gets audio feature information for a single track identified by its unique Spotify ID.

    • Parameters

      • trackID - The Spotify ID for the track
      • options - A map of other optional parameters to specify for the query
    • Returns

      • A Promise that resolves to the request result object. An example response can be seen here
  • getTracksAudioFeatures( trackIDs, options? )

    Gets audio features for multiple tracks based on their Spotify IDs.

    • Parameters

      • trackIDs - An array of the Spotify IDs for the tracks
      • options - A map of other optional parameters to specify for the query
    • Returns

      • A Promise that resolves to the request result object. An example response can be seen here

Token swap and refresh

In order for your app to stay logged into Spotify for more than an hour, you must set up your own server with endpoints for token swap and refresh, and specify your tokenSwapURL and tokenRefreshURL parameters in the Spotify.initialize method

The tokenSwapURL parameter is used to swap the authentication code provided by the Spotify login process for an access token and a refresh token.

The tokenRefreshURL parameter is used to retrieve new access tokens for the user using the refresh token received from the tokenSwapURL.

Both URLs are queried using POST with a Content-Type of application/x-www-form-urlencoded.

You can find an example server implementation here.

Refresh tokens are part of OAuth standard. If you are not familiar with them, Understanding Refresh Tokens can give you a basic idea on how they work.

Additional notes

This module only works for Spotify Premium users.

More Repositories

1

node-justwatch-api

The JustWatch API for nodejs
JavaScript
68
star
2

react-native-events

Send and receive events from react native modules
Objective-C
53
star
3

miniCode

miniCode is a mobile iOS IDE for writing and compiling code directly on iOS (requires "LLVM+Clang", "iOS Toolchain", and "Open" from Cydia, and must be installed to the root /Applications directory). Badly written and probably doesn't work anymore on new iOS versions
Objective-C++
51
star
4

iSSB

A cross-platform "Super Smash Bros. Brawl" fan-game
C++
35
star
5

kodi-openbox

An xsession that runs Kodi media center on top of a minimal Openbox session. Useful for launching emulators and other external apps
Shell
20
star
6

MobileBrawler

A mobile brawler (rewrite of iSSB). I'm probably not going to work on this for a while. The menu works and that's about all that's been written
C++
14
star
7

Promise.swift

A small promise library for swift
Swift
8
star
8

BrowserCommand

Control any webextension-supported browser from nodejs or the terminal
JavaScript
8
star
9

chromecast-decky-plugin

A decky plugin to allow casting your steam deck screen to a chromecast. (WIP, please help me figure out how to fix the delay!)
Python
7
star
10

battery-decky-plugin

Show in-depth battery information about your steam deck (wip)
Python
6
star
11

iSSB-Windows

A version of iSSB that uses SFML instead of SDL. This project is also no longer maintained or updated. Refer to https://github.com/lufinkey/iSSB for the latest iSSB code
C++
4
star
12

Windows7-Clock-Prank

A prank for windows 7 to cover an unsuspecting user's screen in clocks
Batchfile
3
star
13

nodejs-embed

A C++ library to easily embed NodeJS
C++
3
star
14

RandomInputPrank

Reads messages from a server and simulates keystrokes to type them, or types random messages at random times
C++
2
star
15

spooky

#2spooky4u
HTML
2
star
16

BoilermakeWormhole

Boilermake hackathon wormhole. Bends space and time. Doesn't work at all
C++
2
star
17

sharkle-cinnamon-desklet

The Sharkle desklet from Night In The Woods for Cinnamon desktop
JavaScript
2
star
18

lufinkey.github.io

My personal website
JavaScript
2
star
19

cloakbox

Manages downloads inside a virtual machine connected to a VPN
Shell
2
star
20

DJayy

Portable jukebox web server - HackIllinois 2015
C++
1
star
21

cygwin-tools

a decent sudo and su for cygwin, plus whatever else I decide to add here
Shell
1
star
22

GameLibrary

A game library used by many of my other projects
C++
1
star
23

gyso-server

Get Your Shit Organized Server. Web server that tags and organizes uploaded music/tvshow/movie torrents or zip archives into a user-defined folder structure. (work in progress. not functional yet)
PHP
1
star
24

bandcamp-retriever

An unofficial library for accessing bandcamp
TypeScript
1
star