├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── __mocks__
└── superagent.js
├── __tests__
├── authentication-request.js
├── base-request.js
├── http-manager.js
├── response-error.js
├── spotify-web-api.js
└── webapi-request.js
├── examples
├── access-token-refresh.js
├── access-token-using-client-credentials.js
├── add-remove-replace-tracks-in-a-playlist.js
├── add-tracks-to-a-playlist.js
├── client-credentials.js
├── get-info-about-current-user.js
├── get-related-artists.js
├── get-top-tracks-for-artist.js
├── search-for-tracks.js
└── tutorial
│ ├── 00-get-access-token.js
│ ├── 01-basics
│ └── 01-get-info-about-current-user.js
│ └── README.md
├── package-lock.json
├── package.json
└── src
├── authentication-request.js
├── base-request.js
├── client.js
├── http-manager.js
├── response-error.js
├── server-methods.js
├── server.js
├── spotify-web-api.js
└── webapi-request.js
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | lerna-debug.log*
8 | .pnpm-debug.log*
9 |
10 | # Diagnostic reports (https://nodejs.org/api/report.html)
11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
12 |
13 | # Runtime data
14 | pids
15 | *.pid
16 | *.seed
17 | *.pid.lock
18 |
19 | # Directory for instrumented libs generated by jscoverage/JSCover
20 | lib-cov
21 |
22 | # Coverage directory used by tools like istanbul
23 | coverage
24 | *.lcov
25 |
26 | # nyc test coverage
27 | .nyc_output
28 |
29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
30 | .grunt
31 |
32 | # Bower dependency directory (https://bower.io/)
33 | bower_components
34 |
35 | # node-waf configuration
36 | .lock-wscript
37 |
38 | # Compiled binary addons (https://nodejs.org/api/addons.html)
39 | build/Release
40 |
41 | # Dependency directories
42 | node_modules/
43 | jspm_packages/
44 |
45 | # Snowpack dependency directory (https://snowpack.dev/)
46 | web_modules/
47 |
48 | # TypeScript cache
49 | *.tsbuildinfo
50 |
51 | # Optional npm cache directory
52 | .npm
53 |
54 | # Optional eslint cache
55 | .eslintcache
56 |
57 | # Optional stylelint cache
58 | .stylelintcache
59 |
60 | # Microbundle cache
61 | .rpt2_cache/
62 | .rts2_cache_cjs/
63 | .rts2_cache_es/
64 | .rts2_cache_umd/
65 |
66 | # Optional REPL history
67 | .node_repl_history
68 |
69 | # Output of 'npm pack'
70 | *.tgz
71 |
72 | # Yarn Integrity file
73 | .yarn-integrity
74 |
75 | # dotenv environment variable files
76 | .env
77 | .env.development.local
78 | .env.test.local
79 | .env.production.local
80 | .env.local
81 |
82 | # parcel-bundler cache (https://parceljs.org/)
83 | .cache
84 | .parcel-cache
85 |
86 | # Next.js build output
87 | .next
88 | out
89 |
90 | # Nuxt.js build / generate output
91 | .nuxt
92 | dist
93 |
94 | # Gatsby files
95 | .cache/
96 | # Comment in the public line in if your project uses Gatsby and not Next.js
97 | # https://nextjs.org/blog/next-9-1#public-directory-support
98 | # public
99 |
100 | # vuepress build output
101 | .vuepress/dist
102 |
103 | # vuepress v2.x temp and cache directory
104 | .temp
105 | .cache
106 |
107 | # Docusaurus cache and generated files
108 | .docusaurus
109 |
110 | # Serverless directories
111 | .serverless/
112 |
113 | # FuseBox cache
114 | .fusebox/
115 |
116 | # DynamoDB Local files
117 | .dynamodb/
118 |
119 | # TernJS port file
120 | .tern-port
121 |
122 | # Stores VSCode versions used for testing VSCode extensions
123 | .vscode-test
124 |
125 | # yarn v2
126 | .yarn/cache
127 | .yarn/unplugged
128 | .yarn/build-state.yml
129 | .yarn/install-state.gz
130 | .pnp.*
131 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ## Change log
2 |
3 | #### 5.0.2 (Jan 2021)
4 |
5 | * Fix: Make `transferMyPlayback` not require the `options` object, since it should be optional. Thanks for the heads-up [@Simber1](https://github.com/Simber1)!
6 |
7 | #### 5.0.1 (Jan 2021)
8 |
9 | * Fix error handling in the HTTP client. Thanks [@yamadapc](https://github.com/yamadapc)!
10 | * This package can currently not be built on **Node 15 on Linux**, due to a dependency not being available yet. Issue can be followed on the [node-canvas](https://github.com/Automattic/node-canvas/issues/1688) issue tracker. In the mean time, Travis CI will run on earlier versions of Node.
11 |
12 | #### 5.0.0 (Oct 2020)
13 |
14 | * **BREAKING CHANGES**.
15 | * Arguments for some API methods have changed, causing incorrect behaviour using argument order from version 4.x. See the `README.md` for examples of how the methods can be used.
16 | * Create Playlist (`createPlaylist`) method no longer accepts a `userId` string as its first argument.
17 | * Transfer A User's Playback (`transferMyPlayback`) method takes a `deviceIds` array as its first argument.
18 | * Skip to Previous (`skipToPrevious`) method takes an `options` object as its first argument.
19 | * Skip to Next (`skipToNext`) method takes an `options` object as its first argument.
20 | * Set Repeat Mode on the Current User's Playback (`setRepeat`) method takes a `state` string as its first argument.
21 | * Set Shuffle Mode on the Current User's Playback (`setShuffle`) method takes a `state` string as its first argument.
22 |
23 | Cheers [@marinacrachi](https://github.com/marinacrachi) for the createPlaylist update.
24 | * Removed legacy support for not passing an `options` object while providing a callback method. This was only supported on a few of the older endpoints, and could lead to tricky bugs. The affected endpoints are `getTrack`, `getTracks`, `getAlbum`, `getAlbums`, and `createPlaylist`. Again, check the `README.md` for examples on how these methods can be used if needed.
25 | * Removed `options` argument for retrieving an access token using the Client Credentials flow, `clientCredentialsGrant`.
26 | * API errors come in five different flavours.
27 | * WebapiRegularError - For errors returned by most API endpoints.
28 | * WebapiPlayerError - For errors returned by the Player API. These contain a bit more information.
29 | * WebapiAuthenticationError - For errors related to authentication.
30 | * WebapiError - For errors that come from the Web API that didn't fit into one of the above.
31 | * TimeoutError - For network timeout errors.
32 |
33 | More importantly, errors now contain the response body, headers, and status code. One side-effect of this is that rate limited requests can be handled by checking the `Retry-After` header. Thanks for the PRs [@kauffecup](https://github.com/kauffecup), [@lantelyes](https://github.com/lantelyes), [@dkliemsch](https://github.com/dkliemsch), and [@erezny](https://github.com/erezny).
34 |
35 | Much appreciated [@konstantinjdobler](https://github.com/konstantinjdobler) for updates to the Player API errors.
36 | * Added support for [Implicit Grant flow](https://developer.spotify.com/documentation/general/guides/authorization-guide/#implicit-grant-flow) - Thanks [@gaganza](https://github.com/gaganza), [@reblws](https://github.com/reblws) and [@noahp78](https://github.com/noahp78)!
37 | * Starts or Resumes the Current User's Playback (`play`) method now supports the `position_ms` option. Thanks [@alqubo](https://github.com/alqubo), [@koflin](https://github.com/koflin), [@DoctorFishy](https://github.com/DoctorFishy). Thanks [@carmilso](https://github.com/carmilso) for general improvements to the Player API methods.
38 | * Binding for [Add an Item to the User's Playback Queue](https://developer.spotify.com/documentation/web-api/reference/player/add-to-queue/) endpoint added. Thanks [@thattomperson](https://github.com/thattomperson) and [@AriciducaZagaria](https://github.com/AriciducaZagaria)!
39 | * Binding for all [Shows and Episodes endpoints](https://developer.spotify.com/console/shows/). Thanks a _lot_ [@andyruwruw](https://github.com/andyruwruw)!
40 | * Documentation updates to keep up to date with ES6, thanks [@dandv](https://github.com/dandv)! Other documentation improvements by [@terensu-desu](https://github.com/terensu-desu), and examples by [@dersimn](https://github.com/dersimn). Thanks!
41 | * Bumped dependencies to resolve critical security issues.
42 | * Finally, hat off to [@dersimn](https://github.com/dersimn). Thanks for collecting all of the lingering PRs and merging them into a working and up-to-date fork. You really stepped up.
43 |
44 | Likely more changes coming before release to npm, which will happen shortly.
45 |
46 | #### 4.0.0 (14 Sep 2018)
47 |
48 | * Modified functions that operate on playlists to drop the user id parameter. This is a breaking change. [PR](https://github.com/thelinmichael/spotify-web-api-node/pull/243)
49 | * Updated superagent to fix a security warning [PR](https://github.com/thelinmichael/spotify-web-api-node/pull/211)
50 | * Fixed a bug by which an empty user was not handled properly in getUserPlaylists(). [PR](https://github.com/thelinmichael/spotify-web-api-node/pull/244)
51 |
52 | #### 3.1.1 (29 Apr 2018)
53 |
54 | * Modernized stack for a better developer experience. Integrated [prettier](https://github.com/thelinmichael/spotify-web-api-node/pull/205) and [jest](https://github.com/thelinmichael/spotify-web-api-node/pull/206). This simplifies the amount of dev dependencies.
55 | * Improved calls to save and remove saved tracks by adding a key as specified in the Spotify docs (See [PR](https://github.com/thelinmichael/spotify-web-api-node/pull/207)). Thanks to [@yanniz0r](https://github.com/yanniz0r) and [@adcar](https://github.com/adcar) for bringing it up.
56 |
57 | #### 3.1.0 (26 Apr 2018)
58 |
59 | * Added support for seeking and setting volume. Thanks to [@isokar](https://github.com/isokar), [@jamesemwallis](https://github.com/jamesemwallis), [@ashthespy](https://github.com/ashthespy), and [@vanderlin](https://github.com/vanderlin) for your PRs.
60 |
61 | #### 3.0.0 (8 Mar 2018)
62 |
63 | * @DalerAsrorov added support for uploading a custom image to a playlist in [this PR](https://github.com/thelinmichael/spotify-web-api-node/pull/169).
64 | * You can now pass a `device_id` when playing and pausing playback. @pfftdammitchris started [a PR to add device_id to the play() method](https://github.com/thelinmichael/spotify-web-api-node/pull/185). The changes served to another PR where we included the functionality. Thanks!
65 | * Added documentation in the README for `getMyCurrentPlaybackState()`. Thanks @PanMan for [your PR](https://github.com/thelinmichael/spotify-web-api-node/pull/160)!
66 | * @brodin realized we there was a lot of duplicated code and refactored it in a [great PR](https://github.com/thelinmichael/spotify-web-api-node/pull/123).
67 |
68 | #### 2.5.0 (4 Sep 2017)
69 |
70 | * Change README to reflect new authorization. Thanks [@arirawr](https://github.com/arirawr) for the [PR](https://github.com/thelinmichael/spotify-web-api-node/pull/146).
71 | * Add support for 'show_dialog' parameter when creating authorization url. Thanks [@ajhaupt7](https://github.com/ajhaupt7) for [the PR](https://github.com/thelinmichael/spotify-web-api-node/pull/101).
72 | * Add support for playback control (play, pause, prev, next), shuffle and repeat. Thanks [@JoseMCO](https://github.com/JoseMCO) for [the PR](https://github.com/thelinmichael/spotify-web-api-node/pull/150).
73 | * Add support for currently playing. Thanks [@dustinblackman](https://github.com/dustinblackman) for [the PR](https://github.com/thelinmichael/spotify-web-api-node/pull/145).
74 | * Fix to remove unnecessary deviceIds parameter from request to transfer playback. Thanks [@philnash](https://github.com/philnash) for [the PR](https://github.com/thelinmichael/spotify-web-api-node/pull/154).
75 |
76 | #### 2.4.0 (2 May 2017)
77 |
78 | * Change `addTracksToPlaylist` to pass the data in the body, preventing an issue with a long URL when passing many tracks. Thanks [@dolcalmi](https://github.com/dolcalmi) for [the PR](https://github.com/thelinmichael/spotify-web-api-node/pull/117)
79 | * Add support for fetching [recently played tracks](https://developer.spotify.com/web-api/console/get-recently-played/). Thanks [@jeremyboles](https://github.com/jeremyboles) for [the PR](https://github.com/thelinmichael/spotify-web-api-node/pull/111).
80 |
81 | #### 2.3.6 (15 October 2016)
82 |
83 | * Add language bindings for the **[Get Audio Analysis for a Track](https://developer.spotify.com/web-api/get-audio-analysis/)** endpoint.
84 |
85 | #### 2.3.5 (20 July 2016)
86 |
87 | * Use `encodeURIComponent` instead of `encodeURI` to encode the user's id. 'encodeURI' wasn't encoding characters like `/` or `#` that were generating an invalid endpoint url. Thanks [@jgranstrom](https://github.com/jgranstrom) for the PR.
88 |
89 | #### 2.3.4 (18 July 2016)
90 |
91 | * Fixed a bug in `clientCredentialsGrant()`.
92 |
93 | #### 2.3.3 (18 July 2016)
94 |
95 | * Migrated to the `superagent` request library to support Node.JS and browsers. Thanks [@SomeoneWeird](https://github.com/SomeoneWeird) for the PR to add it, and [@erezny](https://github.com/erezny) for reporting bugs.
96 |
97 | #### 2.3.2 (10 July 2016)
98 |
99 | * Add language bindings for **[Get a List of Current User's Playlists](https://developer.spotify.com/web-api/get-a-list-of-current-users-playlists/)**. Thanks [@JMPerez](https://github.com/JMPerez) and [@vinialbano](https://github.com/vinialbano).
100 |
101 | #### 2.3.1 (3 July 2016)
102 |
103 | * Fix for `getRecomendations` method causing client error response from the API when making the request. Thanks [@kyv](https://github.com/kyv) for reporting, and [@Boberober](https://github.com/Boberober) and [@JMPerez](https://github.com/JMPerez) for providing fixes.
104 |
105 | #### 2.3.0 (2 April 2016)
106 |
107 | * Add language bindings for **[Get Recommendations Based on Seeds](https://developer.spotify.com/web-api/get-recommendations/)**, **[Get a User's Top Artists and Tracks](https://developer.spotify.com/web-api/get-users-top-artists-and-tracks/)**, **[Get Audio Features for a Track](https://developer.spotify.com/web-api/get-audio-features/)**, and **[Get Audio Features for Several Tracks](https://developer.spotify.com/web-api/get-several-audio-features/)**. Read more about the endpoints in the links above or in this [blog post](https://developer.spotify.com/news-stories/2016/03/29/api-improvements-update/).
108 | * Add generic search method enabling searches for several types at once, e.g. search for both tracks and albums in a single request, instead of one request for track results and one request for album results.
109 |
110 | #### 2.2.0 (23 November 2015)
111 |
112 | * Add language bindings for **[Get User's Saved Albums](https://developer.spotify.com/web-api/get-users-saved-albums/)** and other endpoints related to the user's saved albums.
113 |
114 | #### 2.1.1 (23 November 2015)
115 |
116 | * Username encoding bugfix.
117 |
118 | #### 2.1.0 (16 July 2015)
119 |
120 | * Add language binding for **[Get Followed Artists](https://developer.spotify.com/web-api/get-followed-artists/)**
121 |
122 | #### 2.0.2 (11 May 2015)
123 |
124 | * Bugfix for retrieving an access token through the Client Credentials flow. (Thanks [Nate Wilkins](https://github.com/Nate-Wilkins)!)
125 | * Add test coverage and Travis CI.
126 |
127 | #### 2.0.1 (2 Mar 2015)
128 |
129 | * Return WebApiError objects if error occurs during authentication.
130 |
131 | #### 2.0.0 (27 Feb 2015)
132 |
133 | * **Breaking change**: Response object changed. Add headers and status code to all responses to enable users to implement caching.
134 |
135 | #### 1.3.13 (26 Feb 2015)
136 |
137 | * Add language binding for **[Reorder tracks in a Playlist](https://developer.spotify.com/web-api/reorder-playlists-tracks/)**
138 |
139 | #### 1.3.12 (22 Feb 2015)
140 |
141 | * Add language binding for **[Remove tracks in a Playlist by Position](https://developer.spotify.com/web-api/remove-tracks-playlist/)**
142 |
143 | #### 1.3.11
144 |
145 | * Add **[Search for Playlists](https://developer.spotify.com/web-api/search-item/)** endpoint.
146 |
147 | #### 1.3.10
148 |
149 | * Add market parameter to endpoints supporting **[Track Relinking](https://developer.spotify.com/web-api/track-relinking-guide/)**.
150 | * Improve SEO by adding keywords to the package.json file. ;-)
151 |
152 | #### 1.3.8
153 |
154 | * Add **[Get a List of Categories](https://developer.spotify.com/web-api/get-list-categories/)**, **[Get a Category](https://developer.spotify.com/web-api/get-category/)**, and **[Get A Category's Playlists](https://developer.spotify.com/web-api/get-categorys-playlists/)** endpoints.
155 |
156 | #### 1.3.7
157 |
158 | * Add **[Check if Users are Following Playlist](https://developer.spotify.com/web-api/check-user-following-playlist/)** endpoint.
159 |
160 | #### 1.3.5
161 |
162 | * Add missing options parameter in createPlaylist (issue #19). Thanks for raising this [allinallin](https://github.com/allinallin).
163 |
164 | #### 1.3.4
165 |
166 | * Add **[Follow Playlist](https://developer.spotify.com/web-api/follow-playlist/)** and **[Unfollow Playlist](https://developer.spotify.com/web-api/unfollow-playlist/)** endpoints.
167 |
168 | #### 1.3.3
169 |
170 | * [Fix](https://github.com/thelinmichael/spotify-web-api-node/pull/18) error format. Thanks [extrakt](https://github.com/extrakt).
171 |
172 | #### 1.3.2
173 |
174 | * Add ability to use callback methods instead of promise.
175 |
176 | #### 1.2.2
177 |
178 | * Bugfix. api.addTracksToPlaylist tracks parameter can be a string or an array. Thanks [ofagbemi](https://github.com/ofagbemi)!
179 |
180 | #### 1.2.1
181 |
182 | * Add **[Follow endpoints](https://developer.spotify.com/web-api/web-api-follow-endpoints/)**. Great work [JMPerez](https://github.com/JMPerez).
183 |
184 | #### 1.1.0
185 |
186 | * Add **[Browse endpoints](https://developer.spotify.com/web-api/browse-endpoints/)**. Thanks [fsahin](https://github.com/fsahin).
187 |
188 | #### 1.0.2
189 |
190 | * Specify module's git repository. Thanks [vincentorback](https://github.com/vincentorback).
191 |
192 | #### 1.0.1
193 |
194 | * Allow options to be set when retrieving a user's playlists. Thanks [EaterOfCode](https://github.com/EaterOfCode).
195 |
196 | #### 1.0.0
197 |
198 | * Add **[Replace tracks in a Playlist](https://developer.spotify.com/web-api/replace-playlists-tracks/)** endpoint
199 | * Add **[Remove tracks in a Playlist](https://developer.spotify.com/web-api/remove-tracks-playlist/)** endpoint
200 | * Return errors as Error objects instead of unparsed JSON. Thanks [niftylettuce](https://github.com/niftylettuce).
201 |
202 | #### 0.0.11
203 |
204 | * Add **[Change Playlist details](https://developer.spotify.com/web-api/change-playlist-details/)** endpoint (change published status and name). Gracias [JMPerez](https://github.com/JMPerez).
205 |
206 | #### 0.0.10
207 |
208 | * Add Your Music Endpoints (**[Add tracks](https://developer.spotify.com/web-api/save-tracks-user/)**, **[Remove tracks](https://developer.spotify.com/web-api/remove-tracks-user/)**, **[Contains tracks](https://developer.spotify.com/web-api/check-users-saved-tracks/)**, **[Get tracks](https://developer.spotify.com/web-api/get-users-saved-tracks/)**).
209 | * Documentation updates (change scope name of playlist-modify to playlist-modify-public, and a fix to a parameter type). Thanks [JMPerez](https://github.com/JMPerez) and [matiassingers](https://github.com/matiassingers).
210 |
211 | #### 0.0.9
212 |
213 | * Add **[Related artists](https://developer.spotify.com/web-api/get-related-artists/)** endpoint
214 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Spotify Web API Node
2 |
3 | [](https://travis-ci.org/thelinmichael/spotify-web-api-node)
4 | [](https://coveralls.io/r/thelinmichael/spotify-web-api-node)
5 | [](https://bundlephobia.com/result?p=spotify-web-api-node)
6 |
7 | This is a universal wrapper/client for the [Spotify Web API](https://developer.spotify.com/web-api/) that runs on Node.JS and the browser, using [browserify](http://browserify.org/)/[webpack](https://webpack.github.io/)/[rollup](http://rollupjs.org/).
8 |
9 | ## Version 5
10 |
11 | > :warning: Since the last release (4.0.0, released over year ago) a lot of new functionality has been added by a lot of different contributors. **Thank you.** In order to implement some of the feature requests, some **breaking changes** had to be made. A list of them, along with a list of the new functionality, can be found in the [CHANGELOG](https://github.com/thelinmichael/spotify-web-api-node/blob/master/CHANGELOG.md).
12 |
13 | ## Table of contents
14 |
15 | * [Features](#features)
16 | * [Installation](#installation)
17 | * [Usage](#usage)
18 | * [Development](#development)
19 |
20 | ## Features
21 |
22 | The library includes helper functions to do the following:
23 |
24 | #### Fetch music metadata
25 |
26 | * Albums, artists, and tracks
27 | * Audio features and analysis for tracks
28 | * Albums for a specific artist
29 | * Top tracks for a specific artist
30 | * Artists similar to a specific artist
31 |
32 | #### Profiles
33 |
34 | * User's emails, product type, display name, birthdate, image
35 |
36 | #### Search
37 |
38 | * Albums, artists, tracks, and playlists
39 |
40 | #### Playlist manipulation
41 |
42 | * Get a user's playlists
43 | * Create playlists
44 | * Change playlist details
45 | * Add tracks to a playlist
46 | * Remove tracks from a playlist
47 | * Replace tracks in a playlist
48 | * Reorder tracks in a playlist
49 |
50 | #### Your Music library
51 |
52 | * Add, remove, and get tracks and albums that are in the signed in user's Your Music library
53 | * Check if a track or album is in the signed in user's Your Music library
54 |
55 | #### Personalization
56 |
57 | * Get a user’s top artists and tracks based on calculated affinity
58 |
59 | #### Browse
60 |
61 | * Get New Releases
62 | * Get Featured Playlists
63 | * Get a List of Categories
64 | * Get a Category
65 | * Get a Category's Playlists
66 | * Get recommendations based on seeds
67 | * Get available genre seeds
68 |
69 | #### Player
70 |
71 | * Get a User's Available Devices
72 | * Get Information About The User's Current Playback State
73 | * Get Current User's Recently Played Tracks
74 | * Get the User's Currently Playing Track
75 | * Pause a User's Playback
76 | * Seek To Position In Currently Playing Track
77 | * Set Repeat Mode On User’s Playback
78 | * Set Volume For User's Playback
79 | * Skip User’s Playback To Next Track
80 | * Skip User’s Playback To Previous Track
81 | * Start/Resume a User's Playback
82 | * Toggle Shuffle For User’s Playback
83 | * Transfer a User's Playback
84 |
85 | #### Follow
86 |
87 | * Follow and unfollow users
88 | * Follow and unfollow artists
89 | * Check if the logged in user follows a user or artist
90 | * Follow a playlist
91 | * Unfollow a playlist
92 | * Get followed artists
93 | * Check if users are following a Playlist
94 |
95 | #### Player
96 |
97 | * Add an Item to the User's Playback Queue
98 | * Get a user's available devices
99 | * Get information about the user's current playback
100 | * Get current user’s recently played tracks
101 | * Transfer a user's playback
102 | * Resume a user's playback
103 | * Skip a user's playback to next track
104 | * Skip a user's playback to previous track
105 | * Set a user's shuffle mode
106 | * Set a user's repeat mode
107 | * Set volume
108 | * Seek playback to a given position
109 |
110 | #### Shows
111 |
112 | * [Get a Show](https://developer.spotify.com/documentation/web-api/reference/shows/get-a-show/)
113 |
114 | ### Authentication
115 |
116 | All methods require authentication, which can be done using these flows:
117 |
118 | * [Client credentials flow](http://tools.ietf.org/html/rfc6749#section-4.4) (Application-only authentication)
119 | * [Authorization code grant](http://tools.ietf.org/html/rfc6749#section-4.1) (Signed by user)
120 | * [Implicit Grant Flow](https://tools.ietf.org/html/rfc6749#section-4.2) (Client-side Authentication)
121 |
122 | ##### Dependencies
123 |
124 | This project depends on [superagent](https://github.com/visionmedia/superagent) to make HTTP requests.
125 |
126 | ## Installation
127 |
128 | $ npm install spotify-web-api-node --save
129 |
130 | ## Usage
131 |
132 | First, instantiate the wrapper.
133 |
134 | ```javascript
135 | var SpotifyWebApi = require('spotify-web-api-node');
136 |
137 | // credentials are optional
138 | var spotifyApi = new SpotifyWebApi({
139 | clientId: 'fcecfc72172e4cd267473117a17cbd4d',
140 | clientSecret: 'a6338157c9bb5ac9c71924cb2940e1a7',
141 | redirectUri: 'http://www.example.com/callback'
142 | });
143 | ```
144 |
145 | If you've got an access token and want to use it for all calls, simply use the API object's set method. Handling credentials is described in detail in the Authorization section.
146 |
147 | ```javascript
148 | spotifyApi.setAccessToken('');
149 | ```
150 |
151 | Lastly, use the wrapper's helper methods to make the request to Spotify's Web API. The wrapper uses promises, so you need to provide a success callback as well as an error callback.
152 |
153 | ```javascript
154 | // Get Elvis' albums
155 | spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE').then(
156 | function(data) {
157 | console.log('Artist albums', data.body);
158 | },
159 | function(err) {
160 | console.error(err);
161 | }
162 | );
163 | ```
164 |
165 | If you dont wan't to use promises, you can provide a callback method instead.
166 |
167 | ```javascript
168 | // Get Elvis' albums
169 | spotifyApi.getArtistAlbums(
170 | '43ZHCT0cAZBISjO8DG9PnE',
171 | { limit: 10, offset: 20 },
172 | function(err, data) {
173 | if (err) {
174 | console.error('Something went wrong!');
175 | } else {
176 | console.log(data.body);
177 | }
178 | }
179 | );
180 | ```
181 |
182 | The functions that fetch data from the API also accept a JSON object with a set of options. For example, `limit` and `offset` can be used in functions that returns paginated results, such as search and retrieving an artist's albums.
183 |
184 | Note that the **options** parameter is **required if you're using a callback method.**, even if it's empty.
185 |
186 | ```javascript
187 | // Passing a callback - get Elvis' albums in range [20...29]
188 | spotifyApi
189 | .getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE', { limit: 10, offset: 20 })
190 | .then(
191 | function(data) {
192 | console.log('Album information', data.body);
193 | },
194 | function(err) {
195 | console.error(err);
196 | }
197 | );
198 | ```
199 |
200 | ### Responses and errors
201 |
202 | This exposes the response headers, status code and body.
203 |
204 | ```json
205 | {
206 | "body" : {
207 |
208 | },
209 | "headers" : {
210 |
211 | },
212 | "statusCode" :
213 | }
214 | ```
215 |
216 | Errors have same fields, as well as a human readable `message`. This is especially useful since
217 | Spotify's Web API returns different types of error objects depending on the endpoint being called.
218 |
219 | #### Example of a response
220 |
221 | Retrieving a track's metadata in `spotify-web-api-node` version 1.4.0 and later:
222 |
223 | ```json
224 | {
225 | "body": {
226 | "name": "Golpe Maestro",
227 | "popularity": 42,
228 | "preview_url":
229 | "https://p.scdn.co/mp3-preview/4ac44a56e3a4b7b354c1273d7550bbad38c51f5d",
230 | "track_number": 1,
231 | "type": "track",
232 | "uri": "spotify:track:3Qm86XLflmIXVm1wcwkgDK"
233 | },
234 | "headers": {
235 | "date": "Fri, 27 Feb 2015 09:25:48 GMT",
236 | "content-type": "application/json; charset=utf-8",
237 | "cache-control": "public, max-age=7200"
238 | },
239 | "statusCode": 200
240 | }
241 | ```
242 |
243 | ### More examples
244 |
245 | Below are examples for all helper functions. Longer examples of some requests can be found in the [examples folder](examples/).
246 |
247 | ```javascript
248 | var SpotifyWebApi = require('spotify-web-api-node');
249 |
250 | var spotifyApi = new SpotifyWebApi();
251 |
252 | /**
253 | * Get metadata of tracks, albums, artists, shows, and episodes
254 | */
255 |
256 | // Get album
257 | spotifyApi.getAlbum('5U4W9E5WsYb2jUQWePT8Xm')
258 | .then(function(data) {
259 | console.log('Album information', data.body);
260 | }, function(err) {
261 | console.error(err);
262 | });
263 |
264 | // Get multiple albums
265 | spotifyApi.getAlbums(['5U4W9E5WsYb2jUQWePT8Xm', '3KyVcddATClQKIdtaap4bV'])
266 | .then(function(data) {
267 | console.log('Albums information', data.body);
268 | }, function(err) {
269 | console.error(err);
270 | });
271 |
272 | // Get an artist
273 | spotifyApi.getArtist('2hazSY4Ef3aB9ATXW7F5w3')
274 | .then(function(data) {
275 | console.log('Artist information', data.body);
276 | }, function(err) {
277 | console.error(err);
278 | });
279 |
280 | // Get multiple artists
281 | spotifyApi.getArtists(['2hazSY4Ef3aB9ATXW7F5w3', '6J6yx1t3nwIDyPXk5xa7O8'])
282 | .then(function(data) {
283 | console.log('Artists information', data.body);
284 | }, function(err) {
285 | console.error(err);
286 | });
287 |
288 | // Get albums by a certain artist
289 | spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE')
290 | .then(function(data) {
291 | console.log('Artist albums', data.body);
292 | }, function(err) {
293 | console.error(err);
294 | });
295 |
296 | // Search tracks whose name, album or artist contains 'Love'
297 | spotifyApi.searchTracks('Love')
298 | .then(function(data) {
299 | console.log('Search by "Love"', data.body);
300 | }, function(err) {
301 | console.error(err);
302 | });
303 |
304 | // Search artists whose name contains 'Love'
305 | spotifyApi.searchArtists('Love')
306 | .then(function(data) {
307 | console.log('Search artists by "Love"', data.body);
308 | }, function(err) {
309 | console.error(err);
310 | });
311 |
312 | // Search tracks whose artist's name contains 'Love'
313 | spotifyApi.searchTracks('artist:Love')
314 | .then(function(data) {
315 | console.log('Search tracks by "Love" in the artist name', data.body);
316 | }, function(err) {
317 | console.log('Something went wrong!', err);
318 | });
319 |
320 | // Search tracks whose artist's name contains 'Kendrick Lamar', and track name contains 'Alright'
321 | spotifyApi.searchTracks('track:Alright artist:Kendrick Lamar')
322 | .then(function(data) {
323 | console.log('Search tracks by "Alright" in the track name and "Kendrick Lamar" in the artist name', data.body);
324 | }, function(err) {
325 | console.log('Something went wrong!', err);
326 | });
327 |
328 |
329 | // Search playlists whose name or description contains 'workout'
330 | spotifyApi.searchPlaylists('workout')
331 | .then(function(data) {
332 | console.log('Found playlists are', data.body);
333 | }, function(err) {
334 | console.log('Something went wrong!', err);
335 | });
336 |
337 | // Get tracks in an album
338 | spotifyApi.getAlbumTracks('41MnTivkwTO3UUJ8DrqEJJ', { limit : 5, offset : 1 })
339 | .then(function(data) {
340 | console.log(data.body);
341 | }, function(err) {
342 | console.log('Something went wrong!', err);
343 | });
344 |
345 | // Get an artist's top tracks
346 | spotifyApi.getArtistTopTracks('0oSGxfWSnnOXhD2fKuz2Gy', 'GB')
347 | .then(function(data) {
348 | console.log(data.body);
349 | }, function(err) {
350 | console.log('Something went wrong!', err);
351 | });
352 |
353 | // Get artists related to an artist
354 | spotifyApi.getArtistRelatedArtists('0qeei9KQnptjwb8MgkqEoy')
355 | .then(function(data) {
356 | console.log(data.body);
357 | }, function(err) {
358 | done(err);
359 | });
360 |
361 | /* Get Audio Features for a Track */
362 | spotifyApi.getAudioFeaturesForTrack('3Qm86XLflmIXVm1wcwkgDK')
363 | .then(function(data) {
364 | console.log(data.body);
365 | }, function(err) {
366 | done(err);
367 | });
368 |
369 | /* Get Audio Analysis for a Track */
370 | spotifyApi.getAudioAnalysisForTrack('3Qm86XLflmIXVm1wcwkgDK')
371 | .then(function(data) {
372 | console.log(data.body);
373 | }, function(err) {
374 | done(err);
375 | });
376 |
377 | /* Get Audio Features for several tracks */
378 | spotifyApi.getAudioFeaturesForTracks(['4iV5W9uYEdYUVa79Axb7Rh', '3Qm86XLflmIXVm1wcwkgDK'])
379 | .then(function(data) {
380 | console.log(data.body);
381 | }, function(err) {
382 | done(err);
383 | });
384 |
385 |
386 | /*
387 | * User methods
388 | */
389 |
390 | // Get a user
391 | spotifyApi.getUser('petteralexis')
392 | .then(function(data) {
393 | console.log('Some information about this user', data.body);
394 | }, function(err) {
395 | console.log('Something went wrong!', err);
396 | });
397 |
398 | // Get the authenticated user
399 | spotifyApi.getMe()
400 | .then(function(data) {
401 | console.log('Some information about the authenticated user', data.body);
402 | }, function(err) {
403 | console.log('Something went wrong!', err);
404 | });
405 |
406 | /*
407 | * Playlist methods
408 | */
409 |
410 | // Get a playlist
411 | spotifyApi.getPlaylist('5ieJqeLJjjI8iJWaxeBLuK')
412 | .then(function(data) {
413 | console.log('Some information about this playlist', data.body);
414 | }, function(err) {
415 | console.log('Something went wrong!', err);
416 | });
417 |
418 | // Get a user's playlists
419 | spotifyApi.getUserPlaylists('thelinmichael')
420 | .then(function(data) {
421 | console.log('Retrieved playlists', data.body);
422 | },function(err) {
423 | console.log('Something went wrong!', err);
424 | });
425 |
426 | // Create a private playlist
427 | spotifyApi.createPlaylist('My playlist', { 'description': 'My description', 'public': true })
428 | .then(function(data) {
429 | console.log('Created playlist!');
430 | }, function(err) {
431 | console.log('Something went wrong!', err);
432 | });
433 |
434 | // Add tracks to a playlist
435 | spotifyApi.addTracksToPlaylist('5ieJqeLJjjI8iJWaxeBLuK', ["spotify:track:4iV5W9uYEdYUVa79Axb7Rh", "spotify:track:1301WleyT98MSxVHPZCA6M"])
436 | .then(function(data) {
437 | console.log('Added tracks to playlist!');
438 | }, function(err) {
439 | console.log('Something went wrong!', err);
440 | });
441 |
442 | // Add tracks to a specific position in a playlist
443 | spotifyApi.addTracksToPlaylist('5ieJqeLJjjI8iJWaxeBLuK', ["spotify:track:4iV5W9uYEdYUVa79Axb7Rh", "spotify:track:1301WleyT98MSxVHPZCA6M"],
444 | {
445 | position : 5
446 | })
447 | .then(function(data) {
448 | console.log('Added tracks to playlist!');
449 | }, function(err) {
450 | console.log('Something went wrong!', err);
451 | });
452 |
453 | // Remove tracks from a playlist at a specific position
454 | spotifyApi.removeTracksFromPlaylistByPosition('5ieJqeLJjjI8iJWaxeBLuK', [0, 2, 130], "0wD+DKCUxiSR/WY8lF3fiCTb7Z8X4ifTUtqn8rO82O4Mvi5wsX8BsLj7IbIpLVM9")
455 | .then(function(data) {
456 | console.log('Tracks removed from playlist!');
457 | }, function(err) {
458 | console.log('Something went wrong!', err);
459 | });
460 |
461 | // Remove all occurrence of a track
462 | var tracks = [{ uri : "spotify:track:4iV5W9uYEdYUVa79Axb7Rh" }];
463 | var playlistId = '5ieJqeLJjjI8iJWaxeBLuK';
464 | var options = { snapshot_id : "0wD+DKCUxiSR/WY8lF3fiCTb7Z8X4ifTUtqn8rO82O4Mvi5wsX8BsLj7IbIpLVM9" };
465 | spotifyApi.removeTracksFromPlaylist(playlistId, tracks, options)
466 | .then(function(data) {
467 | console.log('Tracks removed from playlist!');
468 | }, function(err) {
469 | console.log('Something went wrong!', err);
470 | });
471 |
472 | // Reorder the first two tracks in a playlist to the place before the track at the 10th position
473 | var options = { "range_length" : 2 };
474 | spotifyApi.reorderTracksInPlaylist('5ieJqeLJjjI8iJWaxeBLuK', 0, 10, options)
475 | .then(function(data) {
476 | console.log('Tracks reordered in playlist!');
477 | }, function(err) {
478 | console.log('Something went wrong!', err);
479 | });
480 |
481 | // Change playlist details
482 | spotifyApi.changePlaylistDetails('5ieJqeLJjjI8iJWaxeBLuK',
483 | {
484 | name: 'This is a new name for my Cool Playlist, and will become private',
485 | 'public' : false
486 | }).then(function(data) {
487 | console.log('Playlist is now private!');
488 | }, function(err) {
489 | console.log('Something went wrong!', err);
490 | });
491 |
492 | // Upload a custom playlist cover image
493 | spotifyApi.uploadCustomPlaylistCoverImage('5ieJqeLJjjI8iJWaxeBLuK','longbase64uri')
494 | .then(function(data) {
495 | console.log('Playlsit cover image uploaded!');
496 | }, function(err) {
497 | console.log('Something went wrong!', err);
498 | });
499 |
500 | // Follow a playlist (privately)
501 | spotifyApi.followPlaylist('5ieJqeLJjjI8iJWaxeBLuK',
502 | {
503 | 'public' : false
504 | }).then(function(data) {
505 | console.log('Playlist successfully followed privately!');
506 | }, function(err) {
507 | console.log('Something went wrong!', err);
508 | });
509 |
510 | // Unfollow a playlist
511 | spotifyApi.unfollowPlaylist('5ieJqeLJjjI8iJWaxeBLuK')
512 | .then(function(data) {
513 | console.log('Playlist successfully unfollowed!');
514 | }, function(err) {
515 | console.log('Something went wrong!', err);
516 | });
517 |
518 | // Check if Users are following a Playlist
519 | spotifyApi.areFollowingPlaylist('5ieJqeLJjjI8iJWaxeBLuK', ['thelinmichael', 'ella'])
520 | .then(function(data) {
521 | data.body.forEach(function(isFollowing) {
522 | console.log("User is following: " + isFollowing);
523 | });
524 | }, function(err) {
525 | console.log('Something went wrong!', err);
526 | });
527 |
528 | /*
529 | * Following Users and Artists methods
530 | */
531 |
532 | /* Get followed artists */
533 | spotifyApi.getFollowedArtists({ limit : 1 })
534 | .then(function(data) {
535 | // 'This user is following 1051 artists!'
536 | console.log('This user is following ', data.body.artists.total, ' artists!');
537 | }, function(err) {
538 | console.log('Something went wrong!', err);
539 | });
540 |
541 | /* Follow a user */
542 | spotifyApi.followUsers(['thelinmichael'])
543 | .then(function(data) {
544 | console.log(data);
545 | }, function(err) {
546 | console.log('Something went wrong!', err);
547 | });
548 |
549 | /* Follow an artist */
550 | spotifyApi.followArtists(['2hazSY4Ef3aB9ATXW7F5w3', '6J6yx1t3nwIDyPXk5xa7O8'])
551 | .then(function(data) {
552 | console.log(data);
553 | }, function(err) {
554 | console.log('Something went wrong!', err);
555 | });
556 |
557 | /* Unfollow a user */
558 | spotifyApi.unfollowUsers(['thelinmichael'])
559 | .then(function(data) {
560 | console.log(data);
561 | }, function(err) {
562 | console.log('Something went wrong!', err);
563 | });
564 |
565 | /* Unfollow an artist */
566 | spotifyApi.unfollowArtists(['2hazSY4Ef3aB9ATXW7F5w3', '6J6yx1t3nwIDyPXk5xa7O8'])
567 | .then(function(data) {
568 | console.log(data);
569 | }, function(err) {
570 | console.log('Something went wrong!', err);
571 | });
572 |
573 | /* Check if a user is following a user */
574 | let usersId = ['thelinmichael'];
575 |
576 | spotifyApi.isFollowingUsers(usersId)
577 | .then(function(data) {
578 | let isFollowing = data.body;
579 |
580 | for (let index = 0; index < usersId.length; index++) {
581 | console.log(usersId[index] + ':' + isFollowing[index])
582 | }
583 | }, function(err) {
584 | console.log('Something went wrong!', err);
585 | });
586 |
587 | /* Check if a user is following an artist */
588 | let artistsId = ['6mfK6Q2tzLMEchAr0e9Uzu', '4DYFVNKZ1uixa6SQTvzQwJ'];
589 |
590 | spotifyApi.isFollowingArtists(artistsId)
591 | .then(function(data) {
592 | let isFollowing = data.body;
593 |
594 | for (let index = 0; index < artistsId.length; index++) {
595 | console.log(artistsId[index] + ':' + isFollowing[index])
596 | }
597 | }, function(err) {
598 | console.log('Something went wrong!', err);
599 | });
600 |
601 | /*
602 | * Your Music library methods
603 | */
604 |
605 | /* Tracks */
606 |
607 | // Get tracks in the signed in user's Your Music library
608 | spotifyApi.getMySavedTracks({
609 | limit : 2,
610 | offset: 1
611 | })
612 | .then(function(data) {
613 | console.log('Done!');
614 | }, function(err) {
615 | console.log('Something went wrong!', err);
616 | });
617 |
618 |
619 | // Check if tracks are in the signed in user's Your Music library
620 | spotifyApi.containsMySavedTracks(["5ybJm6GczjQOgTqmJ0BomP"])
621 | .then(function(data) {
622 |
623 | // An array is returned, where the first element corresponds to the first track ID in the query
624 | var trackIsInYourMusic = data.body[0];
625 |
626 | if (trackIsInYourMusic) {
627 | console.log('Track was found in the user\'s Your Music library');
628 | } else {
629 | console.log('Track was not found.');
630 | }
631 | }, function(err) {
632 | console.log('Something went wrong!', err);
633 | });
634 |
635 | // Remove tracks from the signed in user's Your Music library
636 | spotifyApi.removeFromMySavedTracks(["3VNWq8rTnQG6fM1eldSpZ0"])
637 | .then(function(data) {
638 | console.log('Removed!');
639 | }, function(err) {
640 | console.log('Something went wrong!', err);
641 | });
642 | });
643 |
644 | // Add tracks to the signed in user's Your Music library
645 | spotifyApi.addToMySavedTracks(["3VNWq8rTnQG6fM1eldSpZ0"])
646 | .then(function(data) {
647 | console.log('Added track!');
648 | }, function(err) {
649 | console.log('Something went wrong!', err);
650 | });
651 | });
652 |
653 | /* Albums */
654 |
655 | // Get albums in the signed in user's Your Music library
656 | spotifyApi.getMySavedAlbums({
657 | limit : 1,
658 | offset: 0
659 | })
660 | .then(function(data) {
661 | // Output items
662 | console.log(data.body.items);
663 | }, function(err) {
664 | console.log('Something went wrong!', err);
665 | });
666 |
667 |
668 | // Check if albums are in the signed in user's Your Music library
669 | spotifyApi.containsMySavedAlbums(["1H8AHEB8VSE8irHViGOIrF"])
670 | .then(function(data) {
671 |
672 | // An array is returned, where the first element corresponds to the first album ID in the query
673 | var albumIsInYourMusic = data.body[0];
674 |
675 | if (albumIsInYourMusic) {
676 | console.log('Album was found in the user\'s Your Music library');
677 | } else {
678 | console.log('Album was not found.');
679 | }
680 | }, function(err) {
681 | console.log('Something went wrong!', err);
682 | });
683 |
684 | // Remove albums from the signed in user's Your Music library
685 | spotifyApi.removeFromMySavedAlbums(["1H8AHEB8VSE8irHViGOIrF"])
686 | .then(function(data) {
687 | console.log('Removed!');
688 | }, function(err) {
689 | console.log('Something went wrong!', err);
690 | });
691 | });
692 |
693 | // Add albums to the signed in user's Your Music library
694 | spotifyApi.addToMySavedAlbums(["1H8AHEB8VSE8irHViGOIrF"])
695 | .then(function(data) {
696 | console.log('Added album!');
697 | }, function(err) {
698 | console.log('Something went wrong!', err);
699 | });
700 | });
701 |
702 |
703 | /*
704 | * Browse methods
705 | */
706 |
707 | // Retrieve new releases
708 | spotifyApi.getNewReleases({ limit : 5, offset: 0, country: 'SE' })
709 | .then(function(data) {
710 | console.log(data.body);
711 | done();
712 | }, function(err) {
713 | console.log("Something went wrong!", err);
714 | });
715 | });
716 |
717 | // Retrieve featured playlists
718 | spotifyApi.getFeaturedPlaylists({ limit : 3, offset: 1, country: 'SE', locale: 'sv_SE', timestamp:'2014-10-23T09:00:00' })
719 | .then(function(data) {
720 | console.log(data.body);
721 | }, function(err) {
722 | console.log("Something went wrong!", err);
723 | });
724 |
725 | // Get a List of Categories
726 | spotifyApi.getCategories({
727 | limit : 5,
728 | offset: 0,
729 | country: 'SE',
730 | locale: 'sv_SE'
731 | })
732 | .then(function(data) {
733 | console.log(data.body);
734 | }, function(err) {
735 | console.log("Something went wrong!", err);
736 | });
737 |
738 | // Get a Category (in Sweden)
739 | spotifyApi.getCategory('party', {
740 | country: 'SE',
741 | locale: 'sv_SE'
742 | })
743 | .then(function(data) {
744 | console.log(data.body);
745 | }, function(err) {
746 | console.log("Something went wrong!", err);
747 | });
748 |
749 | // Get Playlists for a Category (Party in Brazil)
750 | spotifyApi.getPlaylistsForCategory('party', {
751 | country: 'BR',
752 | limit : 2,
753 | offset : 0
754 | })
755 | .then(function(data) {
756 | console.log(data.body);
757 | }, function(err) {
758 | console.log("Something went wrong!", err);
759 | });
760 |
761 | // Get Recommendations Based on Seeds
762 | spotifyApi.getRecommendations({
763 | min_energy: 0.4,
764 | seed_artists: ['6mfK6Q2tzLMEchAr0e9Uzu', '4DYFVNKZ1uixa6SQTvzQwJ'],
765 | min_popularity: 50
766 | })
767 | .then(function(data) {
768 | let recommendations = data.body;
769 | console.log(recommendations);
770 | }, function(err) {
771 | console.log("Something went wrong!", err);
772 | });
773 |
774 | // Get available genre seeds
775 | spotifyApi.getAvailableGenreSeeds()
776 | .then(function(data) {
777 | let genreSeeds = data.body;
778 | console.log(genreSeeds);
779 | }, function(err) {
780 | console.log('Something went wrong!', err);
781 | });
782 |
783 | /* Player */
784 |
785 | // Add an Item to the User's Playback Queue
786 | // TBD
787 |
788 | // Get a User's Available Devices
789 | spotifyApi.getMyDevices()
790 | .then(function(data) {
791 | let availableDevices = data.body.devices;
792 | console.log(availableDevices);
793 | }, function(err) {
794 | console.log('Something went wrong!', err);
795 | });
796 |
797 | // Get Information About The User's Current Playback State
798 | spotifyApi.getMyCurrentPlaybackState()
799 | .then(function(data) {
800 | // Output items
801 | if (data.body && data.body.is_playing) {
802 | console.log("User is currently playing something!");
803 | } else {
804 | console.log("User is not playing anything, or doing so in private.");
805 | }
806 | }, function(err) {
807 | console.log('Something went wrong!', err);
808 | });
809 |
810 | // Get Current User's Recently Played Tracks
811 | spotifyApi.getMyRecentlyPlayedTracks({
812 | limit : 20
813 | }).then(function(data) {
814 | // Output items
815 | console.log("Your 20 most recently played tracks are:");
816 | data.body.items.forEach(item => console.log(item.track));
817 | }, function(err) {
818 | console.log('Something went wrong!', err);
819 | });
820 |
821 | // Get the User's Currently Playing Track
822 | spotifyApi.getMyCurrentPlayingTrack()
823 | .then(function(data) {
824 | console.log('Now playing: ' + data.body.item.name);
825 | }, function(err) {
826 | console.log('Something went wrong!', err);
827 | });
828 |
829 | // Pause a User's Playback
830 | spotifyApi.pause()
831 | .then(function() {
832 | console.log('Playback paused');
833 | }, function(err) {
834 | //if the user making the request is non-premium, a 403 FORBIDDEN response code will be returned
835 | console.log('Something went wrong!', err);
836 | });
837 |
838 | // Seek To Position In Currently Playing Track
839 | spotifyApi.seek(positionMs)
840 | .then(function() {
841 | console.log('Seek to ' + positionMs);
842 | }, function(err) {
843 | //if the user making the request is non-premium, a 403 FORBIDDEN response code will be returned
844 | console.log('Something went wrong!', err);
845 | });
846 |
847 | // Set Repeat Mode On User’s Playback
848 | spotifyApi.setRepeat('track')
849 | .then(function () {
850 | console.log('Repeat track.');
851 | }, function(err) {
852 | //if the user making the request is non-premium, a 403 FORBIDDEN response code will be returned
853 | console.log('Something went wrong!', err);
854 | });
855 |
856 | // Set Volume For User's Playback
857 | spotifyApi.setVolume(50)
858 | .then(function () {
859 | console.log('Setting volume to 50.');
860 | }, function(err) {
861 | //if the user making the request is non-premium, a 403 FORBIDDEN response code will be returned
862 | console.log('Something went wrong!', err);
863 | });
864 |
865 | // Skip User’s Playback To Next Track
866 | spotifyApi.skipToNext()
867 | .then(function() {
868 | console.log('Skip to next');
869 | }, function(err) {
870 | //if the user making the request is non-premium, a 403 FORBIDDEN response code will be returned
871 | console.log('Something went wrong!', err);
872 | });
873 |
874 | // Skip User’s Playback To Previous Track
875 | spotifyApi.skipToPrevious()
876 | .then(function() {
877 | console.log('Skip to previous');
878 | }, function(err) {
879 | //if the user making the request is non-premium, a 403 FORBIDDEN response code will be returned
880 | console.log('Something went wrong!', err);
881 | });
882 |
883 | // Start/Resume a User's Playback
884 | spotifyApi.play()
885 | .then(function() {
886 | console.log('Playback started');
887 | }, function(err) {
888 | //if the user making the request is non-premium, a 403 FORBIDDEN response code will be returned
889 | console.log('Something went wrong!', err);
890 | });
891 |
892 | // Toggle Shuffle For User’s Playback
893 | spotifyApi.setShuffle(true)
894 | .then(function() {
895 | console.log('Shuffle is on.');
896 | }, function (err) {
897 | //if the user making the request is non-premium, a 403 FORBIDDEN response code will be returned
898 | console.log('Something went wrong!', err);
899 | });
900 |
901 | // Transfer a User's Playback
902 | spotifyApi.transferMyPlayback(deviceIds)
903 | .then(function() {
904 | console.log('Transfering playback to ' + deviceIds);
905 | }, function(err) {
906 | //if the user making the request is non-premium, a 403 FORBIDDEN response code will be returned
907 | console.log('Something went wrong!', err);
908 | });
909 |
910 |
911 | /**
912 | * Personalization Endpoints
913 | */
914 |
915 | /* Get a User’s Top Artists*/
916 | spotifyApi.getMyTopArtists()
917 | .then(function(data) {
918 | let topArtists = data.body.items;
919 | console.log(topArtists);
920 | }, function(err) {
921 | console.log('Something went wrong!', err);
922 | });
923 |
924 | /* Get a User’s Top Tracks*/
925 | spotifyApi.getMyTopTracks()
926 | .then(function(data) {
927 | let topTracks = data.body.items;
928 | console.log(topTracks);
929 | }, function(err) {
930 | console.log('Something went wrong!', err);
931 | });
932 |
933 | ```
934 |
935 | ### Chaining calls
936 |
937 | ```javascript
938 | // track detail information for album tracks
939 | spotifyApi
940 | .getAlbum('5U4W9E5WsYb2jUQWePT8Xm')
941 | .then(function(data) {
942 | return data.body.tracks.map(function(t) {
943 | return t.id;
944 | });
945 | })
946 | .then(function(trackIds) {
947 | return spotifyApi.getTracks(trackIds);
948 | })
949 | .then(function(data) {
950 | console.log(data.body);
951 | })
952 | .catch(function(error) {
953 | console.error(error);
954 | });
955 |
956 | // album detail for the first 10 Elvis' albums
957 | spotifyApi
958 | .getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE', { limit: 10 })
959 | .then(function(data) {
960 | return data.body.albums.map(function(a) {
961 | return a.id;
962 | });
963 | })
964 | .then(function(albums) {
965 | return spotifyApi.getAlbums(albums);
966 | })
967 | .then(function(data) {
968 | console.log(data.body);
969 | });
970 | ```
971 |
972 | ### Authorization
973 | Supplying an access token is required for all requests to the Spotify API. This wrapper supports three authorization flows - The Authorization Code flow (signed by a user), the Client Credentials flow (application authentication - the user isn't involved), and the Implicit Grant Flow (For completely clientside applications). See Spotify's [Authorization guide](https://developer.spotify.com/spotify-web-api/authorization-guide/) for detailed information on these flows.
974 |
975 | **Important: If you are writing a universal/isomorphic web app using this library, you will not be able to use methods that send a client secret to the Spotify authorization service. Client secrets should be kept server-side and not exposed to client browsers. Never include your client secret in the public JS served to the browser.**
976 |
977 | The first thing you need to do is to [create an application](https://developer.spotify.com/my-applications/). A step-by-step tutorial is offered by Spotify in this [tutorial](https://developer.spotify.com/spotify-web-api/tutorial/).
978 |
979 | #### Authorization code flow
980 |
981 | With the application created and its redirect URI set, the only thing necessary for the application to retrieve an **authorization code** is the user's permission. Which permissions you're able to ask for is documented in Spotify's [Using Scopes section](https://developer.spotify.com/spotify-web-api/using-scopes/).
982 |
983 | In order to get permissions, you need to direct the user to [Spotify's Accounts service](https://accounts.spotify.com). Generate the URL by using the wrapper's authorization URL method.
984 |
985 | ```javascript
986 | var scopes = ['user-read-private', 'user-read-email'],
987 | redirectUri = 'https://example.com/callback',
988 | clientId = '5fe01282e44241328a84e7c5cc169165',
989 | state = 'some-state-of-my-choice';
990 |
991 | // Setting credentials can be done in the wrapper's constructor, or using the API object's setters.
992 | var spotifyApi = new SpotifyWebApi({
993 | redirectUri: redirectUri,
994 | clientId: clientId
995 | });
996 |
997 | // Create the authorization URL
998 | var authorizeURL = spotifyApi.createAuthorizeURL(scopes, state);
999 |
1000 | // https://accounts.spotify.com:443/authorize?client_id=5fe01282e44241328a84e7c5cc169165&response_type=code&redirect_uri=https://example.com/callback&scope=user-read-private%20user-read-email&state=some-state-of-my-choice
1001 | console.log(authorizeURL);
1002 | ```
1003 |
1004 | The example below uses a hardcoded authorization code, retrieved from the Accounts service as described above.
1005 |
1006 | ```javascript
1007 | var credentials = {
1008 | clientId: 'someClientId',
1009 | clientSecret: 'someClientSecret',
1010 | redirectUri: 'http://www.michaelthelin.se/test-callback'
1011 | };
1012 |
1013 | var spotifyApi = new SpotifyWebApi(credentials);
1014 |
1015 | // The code that's returned as a query parameter to the redirect URI
1016 | var code = 'MQCbtKe23z7YzzS44KzZzZgjQa621hgSzHN';
1017 |
1018 | // Retrieve an access token and a refresh token
1019 | spotifyApi.authorizationCodeGrant(code).then(
1020 | function(data) {
1021 | console.log('The token expires in ' + data.body['expires_in']);
1022 | console.log('The access token is ' + data.body['access_token']);
1023 | console.log('The refresh token is ' + data.body['refresh_token']);
1024 |
1025 | // Set the access token on the API object to use it in later calls
1026 | spotifyApi.setAccessToken(data.body['access_token']);
1027 | spotifyApi.setRefreshToken(data.body['refresh_token']);
1028 | },
1029 | function(err) {
1030 | console.log('Something went wrong!', err);
1031 | }
1032 | );
1033 | ```
1034 |
1035 | Since the access token was set on the API object in the previous success callback, **it's going to be used in future calls**. As it was retrieved using the Authorization Code flow, it can also be refreshed.
1036 |
1037 | ```javascript
1038 | // clientId, clientSecret and refreshToken has been set on the api object previous to this call.
1039 | spotifyApi.refreshAccessToken().then(
1040 | function(data) {
1041 | console.log('The access token has been refreshed!');
1042 |
1043 | // Save the access token so that it's used in future calls
1044 | spotifyApi.setAccessToken(data.body['access_token']);
1045 | },
1046 | function(err) {
1047 | console.log('Could not refresh access token', err);
1048 | }
1049 | );
1050 | ```
1051 |
1052 | #### Client Credential flow
1053 |
1054 | The Client Credential flow doesn't require the user to give permissions, so it's suitable for requests where the application just needs to authenticate itself. This is the case with for example retrieving a playlist. However, note that the access token cannot be refreshed, and that it isn't connected to a specific user.
1055 |
1056 | ```javascript
1057 | var clientId = 'someClientId',
1058 | clientSecret = 'someClientSecret';
1059 |
1060 | // Create the api object with the credentials
1061 | var spotifyApi = new SpotifyWebApi({
1062 | clientId: clientId,
1063 | clientSecret: clientSecret
1064 | });
1065 |
1066 | // Retrieve an access token.
1067 | spotifyApi.clientCredentialsGrant().then(
1068 | function(data) {
1069 | console.log('The access token expires in ' + data.body['expires_in']);
1070 | console.log('The access token is ' + data.body['access_token']);
1071 |
1072 | // Save the access token so that it's used in future calls
1073 | spotifyApi.setAccessToken(data.body['access_token']);
1074 | },
1075 | function(err) {
1076 | console.log('Something went wrong when retrieving an access token', err);
1077 | }
1078 | );
1079 | ```
1080 |
1081 | #### Implicit Grant flow
1082 |
1083 | The Implicit Grant can be used to allow users to login to your completely client-side application. This method still requires a registered application, but won't expose your client secret.
1084 | This method of authentication won't return any refresh tokens, so you will need to fully reauthenticate the user everytime a token expires.
1085 |
1086 | ```javascript
1087 | var scopes = ['user-read-private', 'user-read-email'],
1088 | redirectUri = 'https://example.com/callback',
1089 | clientId = '5fe01282e44241328a84e7c5cc169165',
1090 | state = 'some-state-of-my-choice',
1091 | showDialog = true,
1092 | responseType = 'token';
1093 |
1094 | // Setting credentials can be done in the wrapper's constructor, or using the API object's setters.
1095 | var spotifyApi = new SpotifyWebApi({
1096 | redirectUri: redirectUri,
1097 | clientId: clientId
1098 | });
1099 |
1100 | // Create the authorization URL
1101 | var authorizeURL = spotifyApi.createAuthorizeURL(
1102 | scopes,
1103 | state,
1104 | showDialog,
1105 | responseType
1106 | );
1107 |
1108 | // https://accounts.spotify.com/authorize?client_id=5fe01282e44241328a84e7c5cc169165&response_type=token&redirect_uri=https://example.com/callback&scope=user-read-private%20user-read-email&state=some-state-of-my-choice&show_dialog=true
1109 | console.log(authorizeURL);
1110 | ```
1111 |
1112 | When the client returns, it will have a token we can directly pass to the library:
1113 |
1114 | ```javascript
1115 | // The code that's returned as a hash fragment query string parameter to the redirect URI
1116 | var code = 'MQCbtKe23z7YzzS44KzZzZgjQa621hgSzHN';
1117 | var credentials = {
1118 | clientId: 'someClientId',
1119 | clientSecret: 'someClientSecret',
1120 | //Either here
1121 | accessToken: code
1122 | };
1123 |
1124 | var spotifyApi = new SpotifyWebApi(credentials);
1125 |
1126 | //Or with a method
1127 | spotifyApi.setAccessToken(code);
1128 | ```
1129 |
1130 | #### Setting credentials
1131 |
1132 | Credentials are either set when constructing the API object or set after the object has been created using setters. They can be set all at once or one at a time.
1133 |
1134 | Using setters, getters and resetters.
1135 |
1136 | ```javascript
1137 | // Use setters to set all credentials one by one
1138 | var spotifyApi = new SpotifyWebApi();
1139 | spotifyApi.setAccessToken('myAccessToken');
1140 | spotifyApi.setRefreshToken('myRefreshToken');
1141 | spotifyApi.setRedirectURI('http://www.example.com/test-callback');
1142 | spotifyApi.setClientId('myOwnClientId');
1143 | spotifyApi.setClientSecret('someSuperSecretString');
1144 |
1145 | // Set all credentials at the same time
1146 | spotifyApi.setCredentials({
1147 | accessToken: 'myAccessToken',
1148 | refreshToken: 'myRefreshToken',
1149 | redirectUri: 'http://www.example.com/test-callback',
1150 | 'clientId ': 'myClientId',
1151 | clientSecret: 'myClientSecret'
1152 | });
1153 |
1154 | // Get the credentials one by one
1155 | console.log('The access token is ' + spotifyApi.getAccessToken());
1156 | console.log('The refresh token is ' + spotifyApi.getRefreshToken());
1157 | console.log('The redirectURI is ' + spotifyApi.getRedirectURI());
1158 | console.log('The client ID is ' + spotifyApi.getClientId());
1159 | console.log('The client secret is ' + spotifyApi.getClientSecret());
1160 |
1161 | // Get all credentials
1162 | console.log('The credentials are ' + spotifyApi.getCredentials());
1163 |
1164 | // Reset the credentials
1165 | spotifyApi.resetAccessToken();
1166 | spotifyApi.resetRefreshToken();
1167 | spotifyApi.resetRedirectURI();
1168 | spotifyApi.resetClientId();
1169 | spotifyApi.resetClientSecret();
1170 | spotifyApi.resetCode();
1171 |
1172 | // Reset all credentials at the same time
1173 | spotifyApi.resetCredentials();
1174 | ```
1175 |
1176 | Using the constructor.
1177 |
1178 | ```javascript
1179 | // Set necessary parts of the credentials on the constructor
1180 | var spotifyApi = new SpotifyWebApi({
1181 | clientId: 'myClientId',
1182 | clientSecret: 'myClientSecret'
1183 | });
1184 |
1185 | // Get an access token and 'save' it using a setter
1186 | spotifyApi.clientCredentialsGrant().then(
1187 | function(data) {
1188 | console.log('The access token is ' + data.body['access_token']);
1189 | spotifyApi.setAccessToken(data.body['access_token']);
1190 | },
1191 | function(err) {
1192 | console.log('Something went wrong!', err);
1193 | }
1194 | );
1195 | ```
1196 |
1197 | ```javascript
1198 | // Set the credentials when making the request
1199 | var spotifyApi = new SpotifyWebApi({
1200 | accessToken: 'njd9wng4d0ycwnn3g4d1jm30yig4d27iom5lg4d3'
1201 | });
1202 |
1203 | // Do search using the access token
1204 | spotifyApi.searchTracks('artist:Love').then(
1205 | function(data) {
1206 | console.log(data.body);
1207 | },
1208 | function(err) {
1209 | console.log('Something went wrong!', err);
1210 | }
1211 | );
1212 | ```
1213 |
1214 | ```javascript
1215 | // Set the credentials when making the request
1216 | var spotifyApi = new SpotifyWebApi({
1217 | accessToken: 'njd9wng4d0ycwnn3g4d1jm30yig4d27iom5lg4d3'
1218 | });
1219 |
1220 | // Get tracks in a playlist
1221 | api
1222 | .getPlaylistTracks('3ktAYNcRHpazJ9qecm3ptn', {
1223 | offset: 1,
1224 | limit: 5,
1225 | fields: 'items'
1226 | })
1227 | .then(
1228 | function(data) {
1229 | console.log('The playlist contains these tracks', data.body);
1230 | },
1231 | function(err) {
1232 | console.log('Something went wrong!', err);
1233 | }
1234 | );
1235 | ```
1236 |
1237 | ## Development
1238 |
1239 | See something you think can be improved? [Open an issue](https://github.com/thelinmichael/spotify-web-api-node/issues/new) or clone the project and send a pull request with your changes.
1240 |
1241 | ### Running tests
1242 |
1243 | You can run the unit tests executing `npm test` and get a test coverage report running `npm test -- --coverage`.
1244 |
--------------------------------------------------------------------------------
/__mocks__/superagent.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | //mock for superagent - __mocks__/superagent.js
4 |
5 | var mockDelay;
6 | var mockError;
7 | var mockResponse = {
8 | status() {
9 | return 200;
10 | },
11 | ok() {
12 | return true;
13 | },
14 | get: jest.fn(),
15 | toError: jest.fn()
16 | };
17 |
18 | var Request = {
19 | put() {
20 | return this;
21 | },
22 | del() {
23 | return this;
24 | },
25 | post() {
26 | return this;
27 | },
28 | get() {
29 | return this;
30 | },
31 | send() {
32 | return this;
33 | },
34 | query() {
35 | return this;
36 | },
37 | field() {
38 | return this;
39 | },
40 | set() {
41 | return this;
42 | },
43 | accept() {
44 | return this;
45 | },
46 | timeout() {
47 | return this;
48 | },
49 | end: jest.fn().mockImplementation(function(callback) {
50 | if (mockDelay) {
51 | this.delayTimer = setTimeout(callback, 0, mockError, mockResponse);
52 | return;
53 | }
54 |
55 | callback(mockError, mockResponse);
56 | }),
57 | //expose helper methods for tests to set
58 | __setMockDelay(boolValue) {
59 | mockDelay = boolValue;
60 | },
61 | __setMockResponse(mockRes) {
62 | mockResponse = mockRes;
63 | },
64 | __setMockError(mockErr) {
65 | mockError = mockErr;
66 | },
67 | __reset() {
68 | this.__setMockResponse({
69 | status() {
70 | return 200;
71 | },
72 | ok() {
73 | return true;
74 | }
75 | });
76 | this.__setMockError(null);
77 | this.__setMockDelay(false);
78 | }
79 | };
80 |
81 | module.exports = Request;
82 |
--------------------------------------------------------------------------------
/__tests__/authentication-request.js:
--------------------------------------------------------------------------------
1 | var AuthenticationRequest = require('../src/authentication-request');
2 |
3 | describe('Create Authentication Requests', () => {
4 | test('Should use default settings if none are supplied', () => {
5 | var request = AuthenticationRequest.builder().build();
6 |
7 | expect(request.getHost()).toBe('accounts.spotify.com');
8 | expect(request.getPort()).toBe(443);
9 | expect(request.getScheme()).toBe('https');
10 | expect(request.getHeaders()).toBeFalsy();
11 | expect(request.getPath()).toBeFalsy();
12 | expect(request.getQueryParameters()).toBeFalsy();
13 | expect(request.getBodyParameters()).toBeFalsy();
14 | });
15 |
16 | test('Can overwrite one of the default parameters', () => {
17 | var request = AuthenticationRequest.builder()
18 | .withHost('such.host.wow')
19 | .build();
20 |
21 | expect(request.getHost()).toBe('such.host.wow');
22 | expect(request.getPort()).toBe(443);
23 | expect(request.getScheme()).toBe('https');
24 | expect(request.getHeaders()).toBeFalsy();
25 | expect(request.getPath()).toBeFalsy();
26 | expect(request.getQueryParameters()).toBeFalsy();
27 | expect(request.getBodyParameters()).toBeFalsy();
28 | });
29 | });
30 |
--------------------------------------------------------------------------------
/__tests__/base-request.js:
--------------------------------------------------------------------------------
1 | var Request = require('../src/base-request');
2 |
3 | describe('Create Requests', () => {
4 | test('Should create host, port, and scheme', () => {
5 | var request = Request.builder()
6 | .withHost('such.api.wow')
7 | .withPort(1337)
8 | .withScheme('http')
9 | .build();
10 |
11 | expect(request.getHost()).toBe('such.api.wow');
12 | expect(request.getPort()).toBe(1337);
13 | expect(request.getScheme()).toBe('http');
14 | });
15 |
16 | test('Should add query parameters', () => {
17 | var request = Request.builder()
18 | .withHost('such.api.wow')
19 | .withPort(1337)
20 | .withScheme('http')
21 | .withQueryParameters({
22 | oneParameter: 1,
23 | anotherParameter: true,
24 | thirdParameter: 'hello'
25 | })
26 | .build();
27 |
28 | expect(request.getQueryParameters().oneParameter).toBe(1);
29 | expect(request.getQueryParameters().anotherParameter).toBe(true);
30 | expect(request.getQueryParameters().thirdParameter).toBe('hello');
31 | });
32 |
33 | test('Should add query parameters (multiple calls)', () => {
34 | var request = Request.builder()
35 | .withHost('such.api.wow')
36 | .withPort(1337)
37 | .withScheme('http')
38 | .withQueryParameters({
39 | oneParameter: 1,
40 | anotherParameter: true
41 | })
42 | .withQueryParameters({
43 | thirdParameter: 'hello'
44 | })
45 | .build();
46 |
47 | expect(request.getQueryParameters().oneParameter).toBe(1);
48 | expect(request.getQueryParameters().anotherParameter).toBe(true);
49 | expect(request.getQueryParameters().thirdParameter).toBe('hello');
50 | });
51 |
52 | test('Should add query parameters (combine calls)', () => {
53 | var request = Request.builder()
54 | .withHost('such.api.wow')
55 | .withPort(1337)
56 | .withScheme('http')
57 | .withQueryParameters(
58 | {
59 | oneParameter: 1,
60 | anotherParameter: true
61 | },
62 | {
63 | thirdParameter: 'hello'
64 | }
65 | )
66 | .build();
67 |
68 | expect(request.getQueryParameters().oneParameter).toBe(1);
69 | expect(request.getQueryParameters().anotherParameter).toBe(true);
70 | expect(request.getQueryParameters().thirdParameter).toBe('hello');
71 | });
72 |
73 | test('Should add body parameters', () => {
74 | var request = Request.builder()
75 | .withHost('such.api.wow')
76 | .withPort(1337)
77 | .withScheme('http')
78 | .withBodyParameters({
79 | one: 1,
80 | two: true,
81 | three: 'world'
82 | })
83 | .build();
84 |
85 | expect(request.getBodyParameters().one).toBe(1);
86 | expect(request.getBodyParameters().two).toBe(true);
87 | expect(request.getBodyParameters().three).toBe('world');
88 | });
89 |
90 | test('Should add array to body parameters', () => {
91 | var request = Request.builder()
92 | .withHost('such.api.wow')
93 | .withPort(1337)
94 | .withScheme('http')
95 | .withBodyParameters(['3VNWq8rTnQG6fM1eldSpZ0'])
96 | .build();
97 |
98 | expect(request.getBodyParameters()).toEqual(['3VNWq8rTnQG6fM1eldSpZ0']);
99 | });
100 |
101 | test('Should add header parameters', () => {
102 | var request = Request.builder()
103 | .withHost('such.api.wow')
104 | .withPort(1337)
105 | .withScheme('http')
106 | .withHeaders({
107 | Authorization: 'Basic WOOP',
108 | 'Content-Type': 'application/lol'
109 | })
110 | .build();
111 |
112 | expect(request.getHeaders().Authorization).toBe('Basic WOOP');
113 | expect(request.getHeaders()['Content-Type']).toBe('application/lol');
114 | });
115 |
116 | test('Should add path', () => {
117 | var request = Request.builder()
118 | .withHost('such.api.wow')
119 | .withPort(1337)
120 | .withPath('/v1/users/meriosweg')
121 | .build();
122 |
123 | expect(request.getPath()).toBe('/v1/users/meriosweg');
124 | });
125 |
126 | test('Should build URI', () => {
127 | var request = Request.builder()
128 | .withHost('such.api.wow')
129 | .withScheme('https')
130 | .withPort(1337)
131 | .withPath('/v1/users/meriosweg')
132 | .build();
133 |
134 | expect(request.getURI()).toBe(
135 | 'https://such.api.wow:1337/v1/users/meriosweg'
136 | );
137 | });
138 |
139 | test('Should construct empty query paramaters string', () => {
140 | var request = Request.builder()
141 | .withQueryParameters({})
142 | .build();
143 |
144 | expect(request.getQueryParameterString()).toBeFalsy();
145 | });
146 |
147 | test('Should construct query paramaters string for one parameter', () => {
148 | var request = Request.builder()
149 | .withQueryParameters({
150 | one: 1
151 | })
152 | .build();
153 |
154 | expect(request.getQueryParameterString()).toBe('?one=1');
155 | });
156 |
157 | test('Should construct query paramaters string for multiple parameters', () => {
158 | var request = Request.builder()
159 | .withQueryParameters({
160 | one: 1,
161 | two: true,
162 | three: 'world'
163 | })
164 | .build();
165 |
166 | expect(request.getQueryParameterString()).toBe(
167 | '?one=1&two=true&three=world'
168 | );
169 | });
170 |
171 | test('Should construct query paramaters string and exclude undefined values', () => {
172 | var request = Request.builder()
173 | .withQueryParameters({
174 | one: 1,
175 | two: undefined,
176 | three: 'world'
177 | })
178 | .build();
179 |
180 | expect(request.getQueryParameterString()).toBe('?one=1&three=world');
181 | });
182 | });
183 |
--------------------------------------------------------------------------------
/__tests__/http-manager.js:
--------------------------------------------------------------------------------
1 | var Request = require('../src/base-request'),
2 | superagent = require('superagent'),
3 | {
4 | TimeoutError,
5 | WebapiError,
6 | WebapiRegularError,
7 | WebapiAuthenticationError,
8 | WebapiPlayerError
9 | } = require('../src/response-error');
10 |
11 | var HttpManager = require('../src/http-manager');
12 | var request = Request.builder()
13 | .withHost('such.api.wow')
14 | .withPort(1337)
15 | .withScheme('http')
16 | .build();
17 |
18 | describe('Make requests', () => {
19 |
20 | afterEach(() => {
21 | superagent.__reset();
22 | jest.restoreAllMocks();
23 | });
24 |
25 | test('Should make a successful GET request', done => {
26 | superagent.__setMockResponse({
27 | statusCode: 200,
28 | headers: { 'Content-Type' : 'application/json' },
29 | body: 'some data'
30 | });
31 |
32 | HttpManager.get(request, function(error, result) {
33 | expect(result.body).toBe('some data');
34 | expect(result.statusCode).toBe(200);
35 | expect(result.headers['Content-Type']).toBe('application/json');
36 |
37 | done(error);
38 | });
39 | });
40 |
41 | test('Should process an error of unknown type', done => {
42 | superagent.__setMockError({
43 | response : {
44 | body: 'GET request error',
45 | headers : {},
46 | statusCode: 400
47 | }
48 | });
49 |
50 | HttpManager.get(request, function(error, result) {
51 | expect(error).toBeInstanceOf(WebapiError);
52 | expect(error.message).toBe('GET request error');
53 | done();
54 | });
55 | });
56 |
57 | test('Should process an error of regular type', done => {
58 | superagent.__setMockError({
59 | response : {
60 | body : {
61 | error: {
62 | status : 400,
63 | message : 'There is a problem in your request'
64 | },
65 | },
66 | headers : {},
67 | statusCode : 400
68 | }
69 | });
70 |
71 | HttpManager.get(request, function(error) {
72 | expect(error).toBeInstanceOf(WebapiRegularError);
73 | expect(error.message).toBe('An error occurred while communicating with Spotify\'s Web API.\nDetails: There is a problem in your request.');
74 | done();
75 | });
76 | });
77 |
78 | test('Should process an error of player type', done => {
79 | superagent.__setMockError({
80 | response: {
81 | body: {
82 | error : {
83 | message: 'Detailed Web API Error message',
84 | status: 400,
85 | reason: 'You messed up!'
86 | }
87 | },
88 | statusCode : 400,
89 | headers : []
90 | }
91 | });
92 |
93 | HttpManager.get(request, function(error) {
94 | expect(error).toBeInstanceOf(WebapiPlayerError);
95 | expect(error.message).toBe('An error occurred while communicating with Spotify\'s Web API.\nDetails: Detailed Web API Error message You messed up!.');
96 | expect(error.body.error.reason).toBe('You messed up!');
97 | expect(error.body.error.message).toBe('Detailed Web API Error message');
98 | done();
99 | });
100 | });
101 |
102 | test('should process error of authentication type', done => {
103 | superagent.__setMockError({
104 | response : {
105 | body : {
106 | error: 'invalid_client',
107 | error_description : 'Invalid client'
108 | },
109 | headers: { 'Content-Type' : 'application/json'},
110 | statusCode : 400
111 | }
112 | });
113 |
114 | HttpManager.get(request, function(error) {
115 | expect(error).toBeInstanceOf(WebapiAuthenticationError);
116 | expect(error.statusCode).toBe(400);
117 | expect(error.headers['Content-Type']).toBe('application/json');
118 | expect(error.message).toBe('An authentication error occurred while communicating with Spotify\'s Web API.\nDetails: invalid_client Invalid client.');
119 |
120 | done();
121 | });
122 |
123 | });
124 |
125 | test('should process error of authentication type with missing description', done => {
126 | superagent.__setMockError({
127 | response : {
128 | body : {
129 | error: 'invalid_client'
130 | },
131 | headers: { 'Content-Type' : 'application/json'},
132 | statusCode : 400
133 | }
134 | });
135 |
136 | HttpManager.get(request, function(error) {
137 | expect(error).toBeInstanceOf(WebapiAuthenticationError);
138 | expect(error.message).toBe('An authentication error occurred while communicating with Spotify\'s Web API.\nDetails: invalid_client.');
139 |
140 | done();
141 | });
142 |
143 | });
144 |
145 | test('Should get Retry Headers', done => {
146 | superagent.__setMockError({
147 | response: {
148 | body: {
149 | error : {
150 | message: 'Rate limit exceeded',
151 | status : 429
152 | }
153 | },
154 | statusCode : 429,
155 | headers : { 'Retry-After' : '5' }
156 | }
157 | });
158 |
159 | HttpManager.get(request, function(error) {
160 | expect(error).toBeInstanceOf(WebapiRegularError);
161 | expect(error.body.error.message).toBe('Rate limit exceeded');
162 | expect(error.headers['Retry-After']).toBe('5');
163 | expect(error.message).toBe('An error occurred while communicating with Spotify\'s Web API.\nDetails: Rate limit exceeded.')
164 | done();
165 | });
166 | });
167 |
168 | test('Should make a successful POST request', done => {
169 | superagent.__setMockResponse({
170 | status: 200,
171 | data: 'some data'
172 | });
173 |
174 | HttpManager.post(request, function(error) {
175 | done(error);
176 | });
177 | });
178 |
179 | test('Should make a successful PUT request', done => {
180 | superagent.__setMockResponse({
181 | status: 200,
182 | data: 'some data'
183 | });
184 |
185 | HttpManager.put(request, function(error) {
186 | done(error);
187 | });
188 | });
189 |
190 | test('Should make a successful DELETE request', done => {
191 | superagent.__setMockResponse({
192 | status: 200,
193 | data: 'some data'
194 | });
195 |
196 | HttpManager.del(request, function(error) {
197 | done(error);
198 | });
199 | });
200 |
201 | test('Should handle timeouts', done => {
202 | superagent.__setMockError({
203 | timeout: true
204 | });
205 |
206 | HttpManager.get(request, function(error) {
207 | expect(error).toBeInstanceOf(TimeoutError);
208 | done();
209 | });
210 | });
211 |
212 | test('Should handle arbitrary exceptions', done => {
213 | superagent.__setMockError(new Error('ops'));
214 |
215 | HttpManager.get(request, function(error) {
216 | expect(error).toBeInstanceOf(Error);
217 | done();
218 | });
219 | });
220 | });
221 |
222 |
--------------------------------------------------------------------------------
/__tests__/response-error.js:
--------------------------------------------------------------------------------
1 | const { TimeoutError, WebapiError, WebapiRegularError, WebapiAuthenticationError, WebapiPlayerError } = require("../src/response-error");
2 |
3 | describe('Test error classes', () => {
4 |
5 | test('Timeout', done => {
6 | let error = new TimeoutError();
7 |
8 | expect(error.name).toBe('TimeoutError');
9 | expect(error.message).toBe('A timeout occurred while communicating with Spotify\'s Web API.');
10 | done();
11 | });
12 |
13 | test('WebapiError', done => {
14 | const body = {
15 | success : false
16 | },
17 | headers = {
18 | 'Content-Type' : 'application/json',
19 | 'X-Experimental' : false
20 | },
21 | statusCode = 400,
22 | message = 'An unfortunate error occurred.';
23 |
24 | let error = new WebapiError(body, headers, statusCode, message);
25 |
26 | expect(error.name).toBe('WebapiError');
27 | expect(error.body).toBe(body);
28 | expect(error.headers).toBe(headers);
29 | expect(error.statusCode).toBe(statusCode);
30 | expect(error.message).toBe(message);
31 |
32 | done();
33 | });
34 |
35 | test('WebapiRegularError', done => {
36 | const body = {
37 | error : {
38 | message : 'Not found',
39 | status : 404
40 | }
41 | },
42 | headers = {
43 | 'Content-Type' : 'application/json',
44 | 'X-Experimental' : true
45 | },
46 | statusCode = 404,
47 | message = 'An error occurred while communicating with Spotify\'s Web API.\nDetails: Not found.';
48 |
49 | let error = new WebapiRegularError(body, headers, statusCode, message);
50 |
51 | expect(error.name).toBe('WebapiRegularError');
52 | expect(error.body).toBe(body);
53 | expect(error.headers).toBe(headers);
54 | expect(error.statusCode).toBe(statusCode);
55 | expect(error.message).toBe(message);
56 |
57 | done();
58 | });
59 |
60 | test('WebapiAuthenticationError', done => {
61 | const body = {
62 | error : 'invalid client id',
63 | error_description : 'Invalid Client ID'
64 | },
65 | headers = {
66 | 'Content-Type' : 'application/json'
67 | },
68 | statusCode = 400,
69 | message = 'An authentication error occurred while communicating with Spotify\'s Web API.\nDetails: invalid client id Invalid Client ID.';
70 |
71 | let error = new WebapiAuthenticationError(body, headers, statusCode, message);
72 |
73 | expect(error.name).toBe('WebapiAuthenticationError');
74 | expect(error.body).toBe(body);
75 | expect(error.headers).toBe(headers);
76 | expect(error.statusCode).toBe(statusCode);
77 | expect(error.message).toBe(message);
78 |
79 | done();
80 | });
81 |
82 | test('WebapiPlayerError', done => {
83 | const body = {
84 | error : {
85 | message : 'Not allowed to shuffle',
86 | status : 403,
87 | reason : 'Not premium'
88 | }
89 | },
90 | headers = {
91 | 'Content-Type' : 'application/json'
92 | },
93 | statusCode = 403,
94 | message = 'An error occurred while communicating with Spotify\'s Web API.\nDetails: Not allowed to shuffle Not premium.';
95 |
96 | let error = new WebapiPlayerError(body, headers, statusCode, message);
97 |
98 | expect(error.name).toBe('WebapiPlayerError');
99 | expect(error.body).toBe(body);
100 | expect(error.headers).toBe(headers);
101 | expect(error.statusCode).toBe(statusCode);
102 | expect(error.message).toBe(message);
103 |
104 | done();
105 | });
106 |
107 | });
--------------------------------------------------------------------------------
/__tests__/webapi-request.js:
--------------------------------------------------------------------------------
1 | var WebApiRequest = require('../src/webapi-request');
2 |
3 | describe('Create Web Api Requests', () => {
4 | test('Should use default settings if none are supplied', () => {
5 | var request = WebApiRequest.builder('token').build();
6 |
7 | expect(request.getHost()).toBe('api.spotify.com');
8 | expect(request.getPort()).toBe(443);
9 | expect(request.getScheme()).toBe('https');
10 | expect(request.getHeaders().Authorization).toBeTruthy();
11 | expect(request.getPath()).toBeFalsy();
12 | expect(request.getQueryParameters()).toBeFalsy();
13 | expect(request.getBodyParameters()).toBeFalsy();
14 | });
15 |
16 | test('Can overwrite one of the default parameters', () => {
17 | var request = WebApiRequest.builder('token')
18 | .withHost('such.host.wow')
19 | .build();
20 |
21 | expect(request.getHost()).toBe('such.host.wow');
22 | expect(request.getPort()).toBe(443);
23 | expect(request.getScheme()).toBe('https');
24 | expect(request.getHeaders().Authorization).toBeTruthy();
25 | expect(request.getPath()).toBeFalsy();
26 | expect(request.getQueryParameters()).toBeFalsy();
27 | expect(request.getBodyParameters()).toBeFalsy();
28 | });
29 | });
30 |
--------------------------------------------------------------------------------
/examples/access-token-refresh.js:
--------------------------------------------------------------------------------
1 | const SpotifyWebApi = require('../');
2 |
3 | /**
4 | * This example refreshes an access token. Refreshing access tokens is only possible access tokens received using the
5 | * Authorization Code flow, documented here: https://developer.spotify.com/spotify-web-api/authorization-guide/#authorization_code_flow
6 | */
7 |
8 | /* Retrieve an authorization code as documented here:
9 | * https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
10 | * or in the Authorization section of the README.
11 | *
12 | * Codes are given for a set of scopes. For this example, the scopes are user-read-private and user-read-email.
13 | * Scopes are documented here:
14 | * https://developer.spotify.com/documentation/general/guides/scopes/
15 | */
16 | const authorizationCode =
17 | '';
18 |
19 | /**
20 | * Get the credentials from Spotify's Dashboard page.
21 | * https://developer.spotify.com/dashboard/applications
22 | */
23 | const spotifyApi = new SpotifyWebApi({
24 | clientId: '',
25 | clientSecret: '',
26 | redirectUri: ''
27 | });
28 |
29 | // When our access token will expire
30 | let tokenExpirationEpoch;
31 |
32 | // First retrieve an access token
33 | spotifyApi.authorizationCodeGrant(authorizationCode).then(
34 | function(data) {
35 | // Set the access token and refresh token
36 | spotifyApi.setAccessToken(data.body['access_token']);
37 | spotifyApi.setRefreshToken(data.body['refresh_token']);
38 |
39 | // Save the amount of seconds until the access token expired
40 | tokenExpirationEpoch =
41 | new Date().getTime() / 1000 + data.body['expires_in'];
42 | console.log(
43 | 'Retrieved token. It expires in ' +
44 | Math.floor(tokenExpirationEpoch - new Date().getTime() / 1000) +
45 | ' seconds!'
46 | );
47 | },
48 | function(err) {
49 | console.log(
50 | 'Something went wrong when retrieving the access token!',
51 | err.message
52 | );
53 | }
54 | );
55 |
56 | // Continually print out the time left until the token expires..
57 | let numberOfTimesUpdated = 0;
58 |
59 | setInterval(function() {
60 | console.log(
61 | 'Time left: ' +
62 | Math.floor(tokenExpirationEpoch - new Date().getTime() / 1000) +
63 | ' seconds left!'
64 | );
65 |
66 | // OK, we need to refresh the token. Stop printing and refresh.
67 | if (++numberOfTimesUpdated > 5) {
68 | clearInterval(this);
69 |
70 | // Refresh token and print the new time to expiration.
71 | spotifyApi.refreshAccessToken().then(
72 | function(data) {
73 | tokenExpirationEpoch =
74 | new Date().getTime() / 1000 + data.body['expires_in'];
75 | console.log(
76 | 'Refreshed token. It now expires in ' +
77 | Math.floor(tokenExpirationEpoch - new Date().getTime() / 1000) +
78 | ' seconds!'
79 | );
80 | },
81 | function(err) {
82 | console.log('Could not refresh the token!', err.message);
83 | }
84 | );
85 | }
86 | }, 1000);
87 |
--------------------------------------------------------------------------------
/examples/access-token-using-client-credentials.js:
--------------------------------------------------------------------------------
1 | const SpotifyWebApi = require('../');
2 |
3 | /**
4 | * This example retrieves an access token using the Client Credentials Flow, documented at:
5 | * https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow
6 | */
7 |
8 | /**
9 | * Get the credentials from Spotify's Dashboard page.
10 | * https://developer.spotify.com/dashboard/applications
11 | */
12 | const spotifyApi = new SpotifyWebApi({
13 | clientId: '',
14 | clientSecret: ''
15 | });
16 |
17 | // Retrieve an access token
18 | spotifyApi.clientCredentialsGrant().then(
19 | function(data) {
20 | console.log('The access token expires in ' + data.body['expires_in']);
21 | console.log('The access token is ' + data.body['access_token']);
22 |
23 | // Save the access token so that it's used in future calls
24 | spotifyApi.setAccessToken(data.body['access_token']);
25 | },
26 | function(err) {
27 | console.log(
28 | 'Something went wrong when retrieving an access token',
29 | err.message
30 | );
31 | }
32 | );
33 |
--------------------------------------------------------------------------------
/examples/add-remove-replace-tracks-in-a-playlist.js:
--------------------------------------------------------------------------------
1 | const SpotifyWebApi = require('../');
2 |
3 | /**
4 | * This example demonstrates adding tracks, removing tracks, and replacing tracks in a playlist. At the time of writing this
5 | * documentation, this is the available playlist track modification feature in the Spotify Web API.
6 | *
7 | * Since authorization is required, this example retrieves an access token using the Authorization Code Grant flow,
8 | * documented here: https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
9 | *
10 | * Codes are given for a set of scopes. For this example, the scopes are playlist-modify-public.
11 | * Scopes are documented here:
12 | * https://developer.spotify.com/documentation/general/guides/scopes/
13 | */
14 |
15 | /* Obtain the `authorizationCode` below as described in the Authorization section of the README.
16 | */
17 | const authorizationCode =
18 | '';
19 |
20 | /**
21 | * Get the credentials from Spotify's Dashboard page.
22 | * https://developer.spotify.com/dashboard/applications
23 | */
24 | const spotifyApi = new SpotifyWebApi({
25 | clientId: '',
26 | clientSecret: '',
27 | redirectUri: ''
28 | });
29 |
30 | let playlistId;
31 |
32 | // First retrieve an access token
33 | spotifyApi
34 | .authorizationCodeGrant(authorizationCode)
35 | .then(function(data) {
36 | // Save the access token so that it's used in future requests
37 | spotifyApi.setAccessToken(data['access_token']);
38 |
39 | // Create a playlist
40 | return spotifyApi.createPlaylist(
41 | 'thelinmichael',
42 | 'My New Awesome Playlist'
43 | );
44 | })
45 | .then(function(data) {
46 | console.log('Ok. Playlist created!');
47 | playlistId = data.body['id'];
48 |
49 | // Add tracks to the playlist
50 | return spotifyApi.addTracksToPlaylist(playlistId, [
51 | 'spotify:track:4iV5W9uYEdYUVa79Axb7Rh',
52 | 'spotify:track:6tcfwoGcDjxnSc6etAkDRR',
53 | 'spotify:track:4iV5W9uYEdYUVa79Axb7Rh'
54 | ]);
55 | })
56 | .then(function(data) {
57 | console.log('Ok. Tracks added!');
58 |
59 | // Woops! Made a duplicate. Remove one of the duplicates from the playlist
60 | return spotifyApi.removeTracksFromPlaylist('thelinmichael', playlistId, [
61 | {
62 | uri: 'spotify:track:4iV5W9uYEdYUVa79Axb7Rh',
63 | positions: [0]
64 | }
65 | ]);
66 | })
67 | .then(function(data) {
68 | console.log('Ok. Tracks removed!');
69 |
70 | // Actually, lets just replace all tracks in the playlist with something completely different
71 | return spotifyApi.replaceTracksInPlaylist('thelinmichael', playlistId, [
72 | 'spotify:track:5Wd2bfQ7wc6GgSa32OmQU3',
73 | 'spotify:track:4r8lRYnoOGdEi6YyI5OC1o',
74 | 'spotify:track:4TZZvblv2yzLIBk2JwJ6Un',
75 | 'spotify:track:2IA4WEsWAYpV9eKkwR2UYv',
76 | 'spotify:track:6hDH3YWFdcUNQjubYztIsG'
77 | ]);
78 | })
79 | .then(function(data) {
80 | console.log('Ok. Tracks replaced!');
81 | })
82 | .catch(function(err) {
83 | console.log('Something went wrong:', err.message);
84 | });
85 |
--------------------------------------------------------------------------------
/examples/add-tracks-to-a-playlist.js:
--------------------------------------------------------------------------------
1 | const SpotifyWebApi = require('../');
2 |
3 | /**
4 | * This example demonstrates adding tracks to a specified position in a playlist.
5 | *
6 | * Since authorization is required, this example retrieves an access token using the Authorization Code Grant flow,
7 | * documented here: https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
8 | *
9 | * Codes are given for a set of scopes. For this example, the scopes are playlist-modify-public.
10 | * Scopes are documented here:
11 | * https://developer.spotify.com/documentation/general/guides/scopes/
12 | */
13 |
14 | /* Obtain the `authorizationCode` below as described in the Authorization section of the README.
15 | */
16 | const authorizationCode = '';
17 |
18 | /**
19 | * Get the credentials from Spotify's Dashboard page.
20 | * https://developer.spotify.com/dashboard/applications
21 | */
22 | const spotifyApi = new SpotifyWebApi({
23 | clientId: '',
24 | clientSecret: '',
25 | redirectUri: ''
26 | });
27 |
28 | // First retrieve an access token
29 | spotifyApi
30 | .authorizationCodeGrant(authorizationCode)
31 | .then(function(data) {
32 | spotifyApi.setAccessToken(data.body['access_token']);
33 | return spotifyApi.addTracksToPlaylist(
34 | '5ieJqeLJjjI8iJWaxeBLuK',
35 | [
36 | 'spotify:track:4iV5W9uYEdYUVa79Axb7Rh',
37 | 'spotify:track:1301WleyT98MSxVHPZCA6M'
38 | ],
39 | {
40 | position: 10
41 | }
42 | );
43 | })
44 | .then(function(data) {
45 | console.log('Added tracks to the playlist!');
46 | })
47 | .catch(function(err) {
48 | console.log('Something went wrong:', err.message);
49 | });
50 |
--------------------------------------------------------------------------------
/examples/client-credentials.js:
--------------------------------------------------------------------------------
1 | const { util } = require('prettier');
2 | var SpotifyWebApi = require('../');
3 |
4 | /**
5 | * This example uses the Client Credentials authorization flow.
6 | */
7 |
8 | /**
9 | * Get the credentials from Spotify's Dashboard page.
10 | * https://developer.spotify.com/dashboard/applications
11 | */
12 | const spotifyApi = new SpotifyWebApi({
13 | clientId: '',
14 | clientSecret: ''
15 | });
16 |
17 | // Retrieve an access token using your credentials
18 | spotifyApi.clientCredentialsGrant().
19 | then(function(result) {
20 | console.log('It worked! Your access token is: ' + result.body.access_token);
21 | }).catch(function(err) {
22 | console.log('If this is printed, it probably means that you used invalid ' +
23 | 'clientId and clientSecret values. Please check!');
24 | console.log('Hint: ');
25 | console.log(err);
26 | });
27 |
--------------------------------------------------------------------------------
/examples/get-info-about-current-user.js:
--------------------------------------------------------------------------------
1 | const SpotifyWebApi = require('../');
2 |
3 | /**
4 | * This example retrieves information about the 'current' user. The current user is the user that has
5 | * authorized the application to access its data.
6 | */
7 |
8 | /* Retrieve a code as documented here:
9 | * https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
10 | *
11 | * Codes are given for a set of scopes. For this example, the scopes are user-read-private and user-read-email.
12 | * Scopes are documented here:
13 | * https://developer.spotify.com/documentation/general/guides/scopes/
14 | */
15 | const authorizationCode =
16 | '';
17 |
18 | /* Get the credentials from Spotify's Dashboard page.
19 | * https://developer.spotify.com/dashboard/applications
20 | */
21 | const spotifyApi = new SpotifyWebApi({
22 | clientId: '',
23 | clientSecret: '',
24 | redirectUri: ''
25 | });
26 |
27 | // First retrieve an access token
28 | spotifyApi
29 | .authorizationCodeGrant(authorizationCode)
30 | .then(function(data) {
31 | console.log('Retrieved access token', data.body['access_token']);
32 |
33 | // Set the access token
34 | spotifyApi.setAccessToken(data.body['access_token']);
35 |
36 | // Use the access token to retrieve information about the user connected to it
37 | return spotifyApi.getMe();
38 | })
39 | .then(function(data) {
40 | // "Retrieved data for Faruk Sahin"
41 | console.log('Retrieved data for ' + data.body['display_name']);
42 |
43 | // "Email is farukemresahin@gmail.com"
44 | console.log('Email is ' + data.body.email);
45 |
46 | // "Image URL is http://media.giphy.com/media/Aab07O5PYOmQ/giphy.gif"
47 | console.log('Image URL is ' + data.body.images[0].url);
48 |
49 | // "This user has a premium account"
50 | console.log('This user has a ' + data.body.product + ' account');
51 | })
52 | .catch(function(err) {
53 | console.log('Something went wrong:', err.message);
54 | });
55 |
--------------------------------------------------------------------------------
/examples/get-related-artists.js:
--------------------------------------------------------------------------------
1 | var SpotifyWebApi = require('../');
2 |
3 | /*
4 | * This example shows how to get artists related to another artists. The endpoint is documented here:
5 | * https://developer.spotify.com/web-api/get-related-artists/
6 |
7 | * Please note that authorization is now required and so this example retrieves an access token using the Authorization Code Flow,
8 | * documented here: https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
9 | */
10 |
11 | var authorizationCode =
12 | 'AQAgjS78s64u1axMCBCRA0cViW_ZDDU0pbgENJ_-WpZr3cEO7V5O-JELcEPU6pGLPp08SfO3dnHmu6XJikKqrU8LX9W6J11NyoaetrXtZFW-Y58UGeV69tuyybcNUS2u6eyup1EgzbTEx4LqrP_eCHsc9xHJ0JUzEhi7xcqzQG70roE4WKM_YrlDZO-e7GDRMqunS9RMoSwF_ov-gOMpvy9OMb7O58nZoc3LSEdEwoZPCLU4N4TTJ-IF6YsQRhQkEOJK';
13 |
14 | /* Set the credentials given on Spotify's My Applications page.
15 | * https://developer.spotify.com/my-applications
16 | */
17 | var spotifyApi = new SpotifyWebApi({
18 | clientId: '',
19 | clientSecret: '',
20 | redirectUri: ''
21 | });
22 |
23 | var artistId = '0qeei9KQnptjwb8MgkqEoy';
24 |
25 | spotifyApi
26 | .authorizationCodeGrant(authorizationCode)
27 | .then(function(data) {
28 | console.log('Retrieved access token', data.body['access_token']);
29 |
30 | // Set the access token
31 | spotifyApi.setAccessToken(data.body['access_token']);
32 |
33 | // Use the access token to retrieve information about the user connected to it
34 | return spotifyApi.getArtistRelatedArtists(artistId);
35 | })
36 | .then(function(data) {
37 | if (data.body.artists.length) {
38 | // Print the number of similar artists
39 | console.log('I got ' + data.body.artists.length + ' similar artists!');
40 |
41 | console.log('The most similar one is ' + data.body.artists[0].name);
42 | } else {
43 | console.log("I didn't find any similar artists.. Sorry.");
44 | }
45 | },
46 | function(err) {
47 | console.log('Something went wrong:', err.message);
48 | }
49 | );
50 |
--------------------------------------------------------------------------------
/examples/get-top-tracks-for-artist.js:
--------------------------------------------------------------------------------
1 | const SpotifyWebApi = require('../');
2 |
3 | /**
4 | * This example retrieves the top tracks for an artist.
5 | * https://developer.spotify.com/documentation/web-api/reference/artists/get-artists-top-tracks/
6 | */
7 |
8 | /**
9 | * This endpoint doesn't require an access token, but it's beneficial to use one as it
10 | * gives the application a higher rate limit.
11 | *
12 | * Since it's not necessary to get an access token connected to a specific user, this example
13 | * uses the Client Credentials flow. This flow uses only the client ID and the client secret.
14 | * https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow
15 | */
16 | const spotifyApi = new SpotifyWebApi({
17 | clientId: '',
18 | clientSecret: ''
19 | });
20 |
21 | // Retrieve an access token
22 | spotifyApi
23 | .clientCredentialsGrant()
24 | .then(function(data) {
25 | // Set the access token on the API object so that it's used in all future requests
26 | spotifyApi.setAccessToken(data.body['access_token']);
27 |
28 | // Get the most popular tracks by David Bowie in Great Britain
29 | return spotifyApi.getArtistTopTracks('0oSGxfWSnnOXhD2fKuz2Gy', 'GB');
30 | })
31 | .then(function(data) {
32 | console.log('The most popular tracks for David Bowie is..');
33 | console.log('Drum roll..');
34 | console.log('...');
35 |
36 | /*
37 | * 1. Space Oddity - 2009 Digital Remaster (popularity is 51)
38 | * 2. Heroes - 1999 Digital Remaster (popularity is 33)
39 | * 3. Let's Dance - 1999 Digital Remaster (popularity is 20)
40 | * 4. ...
41 | */
42 | data.body.tracks.forEach(function(track, index) {
43 | console.log(
44 | index +
45 | 1 +
46 | '. ' +
47 | track.name +
48 | ' (popularity is ' +
49 | track.popularity +
50 | ')'
51 | );
52 | });
53 | })
54 | .catch(function(err) {
55 | console.log('Unfortunately, something has gone wrong.', err.message);
56 | });
57 |
--------------------------------------------------------------------------------
/examples/search-for-tracks.js:
--------------------------------------------------------------------------------
1 | const SpotifyWebApi = require('../');
2 |
3 | /*
4 | * This example shows how to search for a track. The endpoint is documented here:
5 | * https://developer.spotify.com/documentation/web-api/reference/search/
6 |
7 | * Since authorization is now required, this example retrieves an access token using the Authorization Code Grant flow,
8 | * documented here: https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
9 | *
10 | * Obtain the `authorizationCode` below as described in the Authorization section of the README.
11 | */
12 |
13 | const authorizationCode = '';
14 |
15 | /**
16 | * Get the credentials from Spotify's Dashboard page.
17 | * https://developer.spotify.com/dashboard/applications
18 | */
19 | const spotifyApi = new SpotifyWebApi({
20 | clientId: '',
21 | clientSecret: '',
22 | redirectUri: ''
23 | });
24 |
25 | spotifyApi
26 | .authorizationCodeGrant(authorizationCode)
27 | .then(function(data) {
28 | console.log('Retrieved access token', data.body['access_token']);
29 |
30 | // Set the access token
31 | spotifyApi.setAccessToken(data.body['access_token']);
32 |
33 | // Use the access token to retrieve information about the user connected to it
34 | return spotifyApi.searchTracks('Love');
35 | })
36 | .then(function(data) {
37 | // Print some information about the results
38 | console.log('I got ' + data.body.tracks.total + ' results!');
39 |
40 | // Go through the first page of results
41 | var firstPage = data.body.tracks.items;
42 | console.log('The tracks in the first page are (popularity in parentheses):');
43 |
44 | /*
45 | * 0: All of Me (97)
46 | * 1: My Love (91)
47 | * 2: I Love This Life (78)
48 | * ...
49 | */
50 | firstPage.forEach(function(track, index) {
51 | console.log(index + ': ' + track.name + ' (' + track.popularity + ')');
52 | });
53 | }).catch(function(err) {
54 | console.log('Something went wrong:', err.message);
55 | });
56 |
--------------------------------------------------------------------------------
/examples/tutorial/00-get-access-token.js:
--------------------------------------------------------------------------------
1 | /**
2 | * This example is using the Authorization Code flow.
3 | *
4 | * In root directory run
5 | *
6 | * npm install express
7 | *
8 | * then run with the followinng command. If you don't have a client_id and client_secret yet,
9 | * create an application on Create an application here: https://developer.spotify.com/my-applications to get them.
10 | * Make sure you whitelist the correct redirectUri in line 26.
11 | *
12 | * node access-token-server.js "" ""
13 | *
14 | * and visit in your Browser.
15 | */
16 | const SpotifyWebApi = require('../../');
17 | const express = require('../../node_modules/express');
18 |
19 | const scopes = [
20 | 'ugc-image-upload',
21 | 'user-read-playback-state',
22 | 'user-modify-playback-state',
23 | 'user-read-currently-playing',
24 | 'streaming',
25 | 'app-remote-control',
26 | 'user-read-email',
27 | 'user-read-private',
28 | 'playlist-read-collaborative',
29 | 'playlist-modify-public',
30 | 'playlist-read-private',
31 | 'playlist-modify-private',
32 | 'user-library-modify',
33 | 'user-library-read',
34 | 'user-top-read',
35 | 'user-read-playback-position',
36 | 'user-read-recently-played',
37 | 'user-follow-read',
38 | 'user-follow-modify'
39 | ];
40 |
41 | const spotifyApi = new SpotifyWebApi({
42 | redirectUri: 'http://localhost:8888/callback',
43 | clientId: process.argv.slice(2)[0],
44 | clientSecret: process.argv.slice(2)[1]
45 | });
46 |
47 | const app = express();
48 |
49 | app.get('/login', (req, res) => {
50 | res.redirect(spotifyApi.createAuthorizeURL(scopes));
51 | });
52 |
53 | app.get('/callback', (req, res) => {
54 | const error = req.query.error;
55 | const code = req.query.code;
56 | const state = req.query.state;
57 |
58 | if (error) {
59 | console.error('Callback Error:', error);
60 | res.send(`Callback Error: ${error}`);
61 | return;
62 | }
63 |
64 | spotifyApi
65 | .authorizationCodeGrant(code)
66 | .then(data => {
67 | const access_token = data.body['access_token'];
68 | const refresh_token = data.body['refresh_token'];
69 | const expires_in = data.body['expires_in'];
70 |
71 | spotifyApi.setAccessToken(access_token);
72 | spotifyApi.setRefreshToken(refresh_token);
73 |
74 | console.log('access_token:', access_token);
75 | console.log('refresh_token:', refresh_token);
76 |
77 | console.log(
78 | `Sucessfully retreived access token. Expires in ${expires_in} s.`
79 | );
80 | res.send('Success! You can now close the window.');
81 |
82 | setInterval(async () => {
83 | const data = await spotifyApi.refreshAccessToken();
84 | const access_token = data.body['access_token'];
85 |
86 | console.log('The access token has been refreshed!');
87 | console.log('access_token:', access_token);
88 | spotifyApi.setAccessToken(access_token);
89 | }, expires_in / 2 * 1000);
90 | })
91 | .catch(error => {
92 | console.error('Error getting Tokens:', error);
93 | res.send(`Error getting Tokens: ${error}`);
94 | });
95 | });
96 |
97 | app.listen(8888, () =>
98 | console.log(
99 | 'HTTP Server up. Now go to http://localhost:8888/login in your browser.'
100 | )
101 | );
102 |
--------------------------------------------------------------------------------
/examples/tutorial/01-basics/01-get-info-about-current-user.js:
--------------------------------------------------------------------------------
1 | const SpotifyWebApi = require('../../../');
2 |
3 | const spotifyApi = new SpotifyWebApi();
4 | spotifyApi.setAccessToken(process.env.SPOTIFY_ACCESS_TOKEN);
5 |
6 | (async () => {
7 | const me = await spotifyApi.getMe();
8 | console.log(me);
9 | })().catch(e => {
10 | console.error(e);
11 | });
12 |
--------------------------------------------------------------------------------
/examples/tutorial/README.md:
--------------------------------------------------------------------------------
1 | Execute all commands from the root folder of this repository.
2 |
3 | Start with
4 |
5 | git clone
6 | cd spotify-web-api-node
7 | npm install
8 | npm install express
9 | node examples/tutorial/00-get-access-token.js "" ""
10 |
11 | and visit in your browser to get an `access_token`.
12 | If you don't have a `client_id` and `client_secret` yet, create an application here: to get them. Make sure you whitelist the correct redirectUri when creating your application, which is `http://localhost:8888/callback`.
13 |
14 | After you got the `access_token`, call all other examples with this token in ENV variable `SPOTIFY_ACCESS_TOKEN`. The easiest way is to call:
15 |
16 | export SPOTIFY_ACCESS_TOKEN=""
17 | node examples/tutorial/01-basics/01-get-info-about-current-user.js
18 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "spotify-web-api-node",
3 | "version": "5.0.2",
4 | "homepage": "https://github.com/thelinmichael/spotify-web-api-node",
5 | "description": "A Node.js wrapper for Spotify's Web API",
6 | "main": "./src/server.js",
7 | "author": "Michael Thelin",
8 | "contributors": [
9 | {
10 | "name": "José M. Perez",
11 | "url": "https://github.com/JMPerez"
12 | }
13 | ],
14 | "license": "MIT",
15 | "repository": {
16 | "type": "git",
17 | "url": "https://github.com/thelinmichael/spotify-web-api-node.git"
18 | },
19 | "scripts": {
20 | "test": "jest",
21 | "travis": "npm test -- --coverage && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",
22 | "precommit": "lint-staged"
23 | },
24 | "jest": {
25 | "verbose": true,
26 | "testURL": "http://localhost/"
27 | },
28 | "lint-staged": {
29 | "*.{js,json,css,md}": [
30 | "prettier --single-quote --write",
31 | "git add"
32 | ]
33 | },
34 | "dependencies": {
35 | "superagent": "^6.1.0"
36 | },
37 | "devDependencies": {
38 | "coveralls": "^3.1.0",
39 | "husky": "^4.3.0",
40 | "jest": "^26.6.3",
41 | "lint-staged": "^10.4.0",
42 | "prettier": "^2.1.2",
43 | "sinon": "^9.0.3",
44 | "canvas": "^2.6.1",
45 | "bufferutil": "^4.0.1",
46 | "utf-8-validate": "^5.0.2",
47 | "jest-resolve": "^26.6.2",
48 | "minimist": "^1.2.5",
49 | "set-value": ">=2.0.1",
50 | "mixin-deep": ">=1.3.2",
51 | "ini": ">=1.3.6"
52 | },
53 | "keywords": [
54 | "spotify",
55 | "echonest",
56 | "music",
57 | "api",
58 | "wrapper",
59 | "client",
60 | "web api"
61 | ],
62 | "browser": {
63 | "./src/server.js": "./src/client.js"
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/authentication-request.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var Request = require('./base-request');
4 |
5 | var DEFAULT_HOST = 'accounts.spotify.com',
6 | DEFAULT_PORT = 443,
7 | DEFAULT_SCHEME = 'https';
8 |
9 | module.exports.builder = function() {
10 | return Request.builder()
11 | .withHost(DEFAULT_HOST)
12 | .withPort(DEFAULT_PORT)
13 | .withScheme(DEFAULT_SCHEME);
14 | };
15 |
--------------------------------------------------------------------------------
/src/base-request.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var Request = function(builder) {
4 | if (!builder) {
5 | throw new Error('No builder supplied to constructor');
6 | }
7 |
8 | this.host = builder.host;
9 | this.port = builder.port;
10 | this.scheme = builder.scheme;
11 | this.queryParameters = builder.queryParameters;
12 | this.bodyParameters = builder.bodyParameters;
13 | this.headers = builder.headers;
14 | this.path = builder.path;
15 | };
16 |
17 | Request.prototype._getter = function(key) {
18 | return function() {
19 | return this[key];
20 | };
21 | };
22 |
23 | Request.prototype.getHost = Request.prototype._getter('host');
24 |
25 | Request.prototype.getPort = Request.prototype._getter('port');
26 |
27 | Request.prototype.getScheme = Request.prototype._getter('scheme');
28 |
29 | Request.prototype.getPath = Request.prototype._getter('path');
30 |
31 | Request.prototype.getQueryParameters = Request.prototype._getter(
32 | 'queryParameters'
33 | );
34 |
35 | Request.prototype.getBodyParameters = Request.prototype._getter(
36 | 'bodyParameters'
37 | );
38 |
39 | Request.prototype.getHeaders = Request.prototype._getter('headers');
40 |
41 | Request.prototype.getURI = function() {
42 | if (!this.scheme || !this.host || !this.port) {
43 | throw new Error('Missing components necessary to construct URI');
44 | }
45 | var uri = this.scheme + '://' + this.host;
46 | if (
47 | (this.scheme === 'http' && this.port !== 80) ||
48 | (this.scheme === 'https' && this.port !== 443)
49 | ) {
50 | uri += ':' + this.port;
51 | }
52 | if (this.path) {
53 | uri += this.path;
54 | }
55 | return uri;
56 | };
57 |
58 | Request.prototype.getURL = function() {
59 | var uri = this.getURI();
60 | if (this.getQueryParameters()) {
61 | return uri + this.getQueryParameterString(this.getQueryParameters());
62 | } else {
63 | return uri;
64 | }
65 | };
66 |
67 | Request.prototype.getQueryParameterString = function() {
68 | var queryParameters = this.getQueryParameters();
69 | if (queryParameters) {
70 | return (
71 | '?' +
72 | Object.keys(queryParameters)
73 | .filter(function(key) {
74 | return queryParameters[key] !== undefined;
75 | })
76 | .map(function(key) {
77 | return key + '=' + queryParameters[key];
78 | })
79 | .join('&')
80 | );
81 | }
82 | };
83 |
84 | Request.prototype.execute = function(method, callback) {
85 | if (callback) {
86 | method(this, callback);
87 | return;
88 | }
89 | var _self = this;
90 |
91 | return new Promise(function(resolve, reject) {
92 | method(_self, function(error, result) {
93 | if (error) {
94 | reject(error);
95 | } else {
96 | resolve(result);
97 | }
98 | });
99 | });
100 | };
101 |
102 | var Builder = function() {};
103 |
104 | Builder.prototype._setter = function(key) {
105 | return function(value) {
106 | this[key] = value;
107 | return this;
108 | };
109 | };
110 |
111 | Builder.prototype.withHost = Builder.prototype._setter('host');
112 |
113 | Builder.prototype.withPort = Builder.prototype._setter('port');
114 |
115 | Builder.prototype.withScheme = Builder.prototype._setter('scheme');
116 |
117 | Builder.prototype.withPath = Builder.prototype._setter('path');
118 |
119 | Builder.prototype._assigner = function(key) {
120 | return function() {
121 | for (var i = 0; i < arguments.length; i++) {
122 | this[key] = this._assign(this[key], arguments[i]);
123 | }
124 |
125 | return this;
126 | };
127 | };
128 |
129 | Builder.prototype.withQueryParameters = Builder.prototype._assigner(
130 | 'queryParameters'
131 | );
132 |
133 | Builder.prototype.withBodyParameters = Builder.prototype._assigner(
134 | 'bodyParameters'
135 | );
136 |
137 | Builder.prototype.withHeaders = Builder.prototype._assigner('headers');
138 |
139 | Builder.prototype.withAuth = function(accessToken) {
140 | if (accessToken) {
141 | this.withHeaders({ Authorization: 'Bearer ' + accessToken });
142 | }
143 | return this;
144 | };
145 |
146 | Builder.prototype._assign = function(src, obj) {
147 | if (obj && Array.isArray(obj)) {
148 | return obj;
149 | }
150 | if (obj && typeof obj === 'string') {
151 | return obj;
152 | }
153 | if (obj && Object.keys(obj).length > 0) {
154 | return Object.assign(src || {}, obj);
155 | }
156 | return src;
157 | };
158 |
159 | Builder.prototype.build = function() {
160 | return new Request(this);
161 | };
162 |
163 | module.exports.builder = function() {
164 | return new Builder();
165 | };
166 |
--------------------------------------------------------------------------------
/src/client.js:
--------------------------------------------------------------------------------
1 | module.exports = require('./spotify-web-api');
2 |
--------------------------------------------------------------------------------
/src/http-manager.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var superagent = require('superagent'),
4 | { TimeoutError,
5 | WebapiError,
6 | WebapiRegularError,
7 | WebapiAuthenticationError,
8 | WebapiPlayerError
9 | } = require('./response-error');
10 |
11 | var HttpManager = {};
12 |
13 | /* Create superagent options from the base request */
14 | var _getParametersFromRequest = function(request) {
15 | var options = {};
16 |
17 | if (request.getQueryParameters()) {
18 | options.query = request.getQueryParameters();
19 | }
20 |
21 | if (request.getHeaders() && request.getHeaders()['Content-Type'] === 'application/json') {
22 | options.data = JSON.stringify(request.getBodyParameters());
23 | } else if (request.getBodyParameters()) {
24 | options.data = request.getBodyParameters();
25 | }
26 |
27 | if (request.getHeaders()) {
28 | options.headers = request.getHeaders();
29 | }
30 | return options;
31 | };
32 |
33 | var _toError = function(response) {
34 | if (typeof response.body === 'object' && response.body.error && typeof response.body.error === 'object' && response.body.error.reason) {
35 | return new WebapiPlayerError(response.body, response.headers, response.statusCode);
36 | }
37 |
38 | if (typeof response.body === 'object' && response.body.error && typeof response.body.error === 'object') {
39 | return new WebapiRegularError(response.body, response.headers, response.statusCode);
40 | }
41 |
42 | if (typeof response.body === 'object' && response.body.error && typeof response.body.error === 'string') {
43 | return new WebapiAuthenticationError(response.body, response.headers, response.statusCode);
44 | }
45 |
46 | /* Other type of error, or unhandled Web API error format */
47 | return new WebapiError(response.body, response.headers, response.statusCode, response.body);
48 | };
49 |
50 | /* Make the request to the Web API */
51 | HttpManager._makeRequest = function(method, options, uri, callback) {
52 | var req = method.bind(superagent)(uri);
53 |
54 | if (options.query) {
55 | req.query(options.query);
56 | }
57 |
58 | if (options.headers) {
59 | req.set(options.headers);
60 | }
61 |
62 | if (options.data) {
63 | req.send(options.data);
64 | }
65 |
66 | req.end(function(err, response) {
67 | if (err) {
68 | if (err.timeout) {
69 | return callback(new TimeoutError());
70 | } else if (err.response) {
71 | return callback(_toError(err.response));
72 | } else {
73 | return callback(err);
74 | }
75 | }
76 |
77 | return callback(null, {
78 | body: response.body,
79 | headers: response.headers,
80 | statusCode: response.statusCode
81 | });
82 | });
83 | };
84 |
85 | /**
86 | * Make a HTTP GET request.
87 | * @param {BaseRequest} The request.
88 | * @param {Function} The callback function.
89 | */
90 | HttpManager.get = function(request, callback) {
91 | var options = _getParametersFromRequest(request);
92 | var method = superagent.get;
93 |
94 | HttpManager._makeRequest(method, options, request.getURI(), callback);
95 | };
96 |
97 | /**
98 | * Make a HTTP POST request.
99 | * @param {BaseRequest} The request.
100 | * @param {Function} The callback function.
101 | */
102 | HttpManager.post = function(request, callback) {
103 | var options = _getParametersFromRequest(request);
104 | var method = superagent.post;
105 |
106 | HttpManager._makeRequest(method, options, request.getURI(), callback);
107 | };
108 |
109 | /**
110 | * Make a HTTP DELETE request.
111 | * @param {BaseRequest} The request.
112 | * @param {Function} The callback function.
113 | */
114 | HttpManager.del = function(request, callback) {
115 | var options = _getParametersFromRequest(request);
116 | var method = superagent.del;
117 |
118 | HttpManager._makeRequest(method, options, request.getURI(), callback);
119 | };
120 |
121 | /**
122 | * Make a HTTP PUT request.
123 | * @param {BaseRequest} The request.
124 | * @param {Function} The callback function.
125 | */
126 | HttpManager.put = function(request, callback) {
127 | var options = _getParametersFromRequest(request);
128 | var method = superagent.put;
129 |
130 | HttpManager._makeRequest(method, options, request.getURI(), callback);
131 | };
132 |
133 | module.exports = HttpManager;
--------------------------------------------------------------------------------
/src/response-error.js:
--------------------------------------------------------------------------------
1 | /* Timeout */
2 | class NamedError extends Error {
3 | get name() {
4 | return this.constructor.name;
5 | }
6 | }
7 |
8 | class TimeoutError extends NamedError {
9 | constructor() {
10 | const message = 'A timeout occurred while communicating with Spotify\'s Web API.';
11 | super(message);
12 | }
13 |
14 | }
15 |
16 | /* Web API Parent and fallback error */
17 | class WebapiError extends NamedError {
18 | constructor(body, headers, statusCode, message) {
19 | super(message);
20 | this.body = body;
21 | this.headers = headers;
22 | this.statusCode = statusCode;
23 | }
24 |
25 | }
26 |
27 | /**
28 | * Regular Error
29 | * { status : , message : }
30 | */
31 | class WebapiRegularError extends WebapiError {
32 | constructor(body, headers, statusCode) {
33 | const message = 'An error occurred while communicating with Spotify\'s Web API.\n' +
34 | 'Details: ' + body.error.message + '.';
35 |
36 | super(body, headers, statusCode, message);
37 | }
38 | }
39 |
40 | /**
41 | * Authentication Error
42 | * { error : , error_description : }
43 | */
44 | class WebapiAuthenticationError extends WebapiError {
45 | constructor(body, headers, statusCode) {
46 | const message = 'An authentication error occurred while communicating with Spotify\'s Web API.\n' +
47 | 'Details: ' + body.error + (body.error_description ? ' ' + body.error_description + '.' : '.');
48 |
49 | super(body, headers, statusCode, message);
50 | }
51 | }
52 |
53 | /**
54 | * Player Error
55 | * { status : , message : , reason : }
56 | */
57 | class WebapiPlayerError extends WebapiError {
58 | constructor(body, headers, statusCode) {
59 | const message = 'An error occurred while communicating with Spotify\'s Web API.\n' +
60 | 'Details: ' + body.error.message + (body.error.reason ? ' ' + body.error.reason + '.' : '.');
61 |
62 | super(body, headers, statusCode, message);
63 | }
64 | }
65 |
66 | module.exports = { WebapiError, TimeoutError, WebapiRegularError, WebapiAuthenticationError, WebapiPlayerError };
--------------------------------------------------------------------------------
/src/server-methods.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var AuthenticationRequest = require('./authentication-request');
4 | var HttpManager = require('./http-manager');
5 |
6 | module.exports = {
7 |
8 | /**
9 | * Retrieve a URL where the user can give the application permissions.
10 | * @param {string[]} scopes The scopes corresponding to the permissions the application needs.
11 | * @param {string} state A parameter that you can use to maintain a value between the request and the callback to redirect_uri.It is useful to prevent CSRF exploits.
12 | * @param {boolean} showDialog A parameter that you can use to force the user to approve the app on each login rather than being automatically redirected.
13 | * @param {string} responseType An optional parameter that you can use to specify the code response based on the authentication type - can be set to 'code' or 'token'. Default 'code' to ensure backwards compatability.
14 | * @returns {string} The URL where the user can give application permissions.
15 | */
16 | createAuthorizeURL: function(scopes, state, showDialog, responseType = 'code') {
17 | return AuthenticationRequest.builder()
18 | .withPath('/authorize')
19 | .withQueryParameters({
20 | client_id: this.getClientId(),
21 | response_type: responseType,
22 | redirect_uri: this.getRedirectURI(),
23 | scope: scopes.join('%20'),
24 | state: state,
25 | show_dialog: showDialog && !!showDialog
26 | })
27 | .build()
28 | .getURL();
29 | },
30 |
31 | /**
32 | * Request an access token using the Client Credentials flow.
33 | * Requires that client ID and client secret has been set previous to the call.
34 | * @param {requestCallback} [callback] Optional callback method to be called instead of the promise.
35 | * @returns {Promise|undefined} A promise that if successful, resolves into an object containing the access token,
36 | * token type and time to expiration. If rejected, it contains an error object. Not returned if a callback is given.
37 | */
38 | clientCredentialsGrant: function(callback) {
39 | return AuthenticationRequest.builder()
40 | .withPath('/api/token')
41 | .withBodyParameters({
42 | grant_type: 'client_credentials'
43 | })
44 | .withHeaders({
45 | Authorization:
46 | 'Basic ' +
47 | new Buffer(
48 | this.getClientId() + ':' + this.getClientSecret()
49 | ).toString('base64'),
50 | 'Content-Type' : 'application/x-www-form-urlencoded'
51 | })
52 | .build()
53 | .execute(HttpManager.post, callback);
54 | },
55 |
56 | /**
57 | * Request an access token using the Authorization Code flow.
58 | * Requires that client ID, client secret, and redirect URI has been set previous to the call.
59 | * @param {string} code The authorization code returned in the callback in the Authorization Code flow.
60 | * @param {requestCallback} [callback] Optional callback method to be called instead of the promise.
61 | * @returns {Promise|undefined} A promise that if successful, resolves into an object containing the access token,
62 | * refresh token, token type and time to expiration. If rejected, it contains an error object.
63 | * Not returned if a callback is given.
64 | */
65 | authorizationCodeGrant: function(code, callback) {
66 | return AuthenticationRequest.builder()
67 | .withPath('/api/token')
68 | .withBodyParameters({
69 | grant_type: 'authorization_code',
70 | redirect_uri: this.getRedirectURI(),
71 | code: code,
72 | client_id: this.getClientId(),
73 | client_secret: this.getClientSecret()
74 | })
75 | .withHeaders({ 'Content-Type' : 'application/x-www-form-urlencoded' })
76 | .build()
77 | .execute(HttpManager.post, callback);
78 | },
79 |
80 | /**
81 | * Refresh the access token given that it hasn't expired.
82 | * Requires that client ID, client secret and refresh token has been set previous to the call.
83 | * @param {requestCallback} [callback] Optional callback method to be called instead of the promise.
84 | * @returns {Promise|undefined} A promise that if successful, resolves to an object containing the
85 | * access token, time to expiration and token type. If rejected, it contains an error object.
86 | * Not returned if a callback is given.
87 | */
88 | refreshAccessToken: function(callback) {
89 | return AuthenticationRequest.builder()
90 | .withPath('/api/token')
91 | .withBodyParameters({
92 | grant_type: 'refresh_token',
93 | refresh_token: this.getRefreshToken()
94 | })
95 | .withHeaders({
96 | Authorization:
97 | 'Basic ' +
98 | new Buffer(
99 | this.getClientId() + ':' + this.getClientSecret()
100 | ).toString('base64'),
101 | 'Content-Type' : 'application/x-www-form-urlencoded'
102 | })
103 | .build()
104 | .execute(HttpManager.post, callback);
105 | }
106 | };
107 |
--------------------------------------------------------------------------------
/src/server.js:
--------------------------------------------------------------------------------
1 | var SpotifyWebApi = require('./spotify-web-api');
2 | var ServerMethods = require('./server-methods');
3 | SpotifyWebApi._addMethods(ServerMethods);
4 | module.exports = SpotifyWebApi;
5 |
--------------------------------------------------------------------------------
/src/webapi-request.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var Request = require('./base-request');
4 |
5 | var DEFAULT_HOST = 'api.spotify.com',
6 | DEFAULT_PORT = 443,
7 | DEFAULT_SCHEME = 'https';
8 |
9 | module.exports.builder = function(accessToken) {
10 | return Request.builder()
11 | .withHost(DEFAULT_HOST)
12 | .withPort(DEFAULT_PORT)
13 | .withScheme(DEFAULT_SCHEME)
14 | .withAuth(accessToken);
15 | };
16 |
--------------------------------------------------------------------------------