├── .gitignore ├── README.md ├── lib └── index.js └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | .AppleDouble 2 | node_modules 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #Simple-Lastfm 2 | 3 | A simple nodejs library to interface with the last.fm API 4 | 5 | ## Installation 6 | npm install simple-lastfm 7 | 8 | ## Examples 9 | 10 | First, you'll need to get an API key from last.fm: [http://www.last.fm/api/account](http://www.last.fm/api/account). 11 | 12 | Once you have your API key and API secret, you'll need to generate a session key, after which you can then start to scrobble: 13 | 14 | ```js 15 | var Lastfm = require('simple-lastfm'); 16 | 17 | var lastfm = new Lastfm({ 18 | api_key: 'xxx', 19 | api_secret: 'xxx', 20 | username: 'xxx', 21 | password: 'xxx', 22 | authToken: 'xxx' // Optional, you can use this instead of password, where authToken = md5(username + md5(password)) 23 | }); 24 | 25 | lastfm.getSessionKey(function(result) { 26 | console.log("session key = " + result.session_key); 27 | if(result.success) { 28 | lastfm.scrobbleNowPlayingTrack({ 29 | artist: 'Ratatat', 30 | track: 'Seventeen Years', 31 | callback: function(result) { 32 | console.log("in callback, finished: ", result); 33 | } 34 | }); 35 | lastfm.scrobbleTrack({ 36 | artist: 'Bonobo', 37 | track: 'Black Sands', 38 | callback: function(result) { 39 | console.log("in callback, finished: ", result); 40 | } 41 | }); 42 | lastfm.loveTrack({ 43 | artist: 'Electrelane', 44 | track: 'Suitcase', 45 | callback: function(result) { 46 | console.log("in callback, finished: ", result); 47 | } 48 | }); 49 | lastfm.unloveTrack({ 50 | artist: 'something crap', 51 | track: 'no thanks', 52 | callback: function(result) { 53 | console.log("in callback, finished: ", result); 54 | } 55 | }); 56 | } else { 57 | console.log("Error: " + result.error); 58 | } 59 | }); 60 | ``` 61 | 62 | #Documentation 63 | 64 | ### init ( options ) 65 | options must be an object with the following required keys: 66 | 67 | * `api_key` 68 | * `api_secret` 69 | * `username` 70 | * `password` 71 | 72 | Optional parameters: 73 | 74 | * `session_key` 75 | * `debug` 76 | 77 | I recommend you save the session key and reuse it when possible. Debug should be true or false. By default it is false. Set it to true to have some console commands outputted. 78 | 79 | ### getSessionKey ( callback ) 80 | callback: A function which receives a single object. On success, this object looks like: 81 | 82 | ```js 83 | { 84 | success: true, 85 | session_key: 'xxx' 86 | } 87 | ``` 88 | 89 | On failure: 90 | 91 | ```js 92 | { 93 | success: false, 94 | error: 'A text description of the error from last.fm' 95 | } 96 | ``` 97 | 98 | Note:Right now 99 | When a session key is successfully received, it automatically gets saved into the lastfm instance (in the above code, you could access it as lastfm.session_key) 100 | 101 | ### addTrackTags ( options) 102 | Require parameters: 103 | 104 | * `artist` 105 | * `track` 106 | * `tags`: A comma delimited list of user supplied tags to apply to this track. Accepts a maximum of 10 tags. 107 | 108 | Optional parameters: 109 | 110 | * `callback`: A function which receives a single object, of the form { success: true|false[, error: 'text description of the error']}. 111 | 112 | ### scrobbleTrack ( options ) 113 | Required parameters: 114 | 115 | * `artist` 116 | * `track` 117 | 118 | Optional parameters: 119 | 120 | * `callback`: A function which receives a single object, of the form { success: true|false[, error: 'text description of the error']}. 121 | * `timestamp`: The timestamp for this scrobble. If omitted, uses the current date/time. Use number of seconds (NOT milliseconds!) since the UNIX epoch. 122 | 123 | ### loveTrack (options) 124 | Required parameters: 125 | 126 | * `artist` 127 | * `track` 128 | 129 | Optional parameters: 130 | 131 | * `callback`: A function which receives a single object, of the form { success: true|false[, error: 'text description of the error']}. 132 | 133 | ### unloveTrack (options) 134 | Required parameters: 135 | 136 | * `artist` 137 | * `track` 138 | 139 | Optional parameters: 140 | 141 | * `callback`: A function which receives a single object, of the form { success: true|false[, error: 'text description of the error']}. 142 | 143 | ### getArtistInfo (options) 144 | Required parameters: 145 | 146 | * `artist` 147 | 148 | Optional parameters: 149 | 150 | * `callback`: A function which receives a single object, of the form { success: true|false[, artistInfo: {}, error: 'text description of the error']}. 151 | 152 | ### getSimilarArtists (options) 153 | Required parameters: 154 | 155 | * `artist` 156 | 157 | Optional parameters: 158 | 159 | * `limit`: The number of results to fetch per page. Defaults to 50. 160 | * `autocorrect`: [0, 1] Transform misspelled artist names into correct artist names, returning the correct version instead. The corrected artist name will be returned in the response. 161 | * `mbid`: The musicbrainz id for the artist. 162 | * `callback`: A function which receives a single object, of the form { success: true|false[, tags: {}, error: 'text description of the error']}. 163 | 164 | ### getTags (options) 165 | Required parameters: 166 | 167 | * `artist` 168 | 169 | Optional parameters: 170 | 171 | * `track` 172 | * `callback`: A function which receives a single object, of the form { success: true|false[, tags: {}, error: 'text description of the error']}. 173 | 174 | ### getTopArtists (options) 175 | Required parameters: 176 | 177 | * `user` 178 | 179 | Optional parameters: 180 | 181 | * `period`: overall | 7day | 1month | 3month | 6month | 12month - The time period over which to retrieve top artists for. 182 | * `limit`: The number of results to fetch per page. Defaults to 50. 183 | * `page`: The page number to fetch. Defaults to first page. 184 | * `callback`: A function which receives a single object, of the form { success: true|false[, tags: {}, error: 'text description of the error']}. 185 | 186 | ### getTrackInfo (options) 187 | Required parameters: 188 | 189 | * `artist` 190 | * `track` 191 | 192 | Optional parameters: 193 | 194 | * `callback`: A function which receives a single object, of the form { success: true|false[, trackInfo: {}, error: 'text description of the error']}. 195 | 196 | ### getPlays (options) 197 | Required parameters: 198 | 199 | * `artist` 200 | 201 | Optional parameters: 202 | 203 | * `track`: The name of the track. If ommitted, method will return number of artist plays. 204 | * `callback`: A function which receives a single object, of the form { success: true|false[, plays: #, error: 'text description of the error']}. 205 | 206 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | var http = require('http'); 2 | var crypto = require('crypto'); 3 | var xml2js = require('xml2js'); 4 | var querystring = require('querystring'); 5 | 6 | var Lastfm = function(options) { 7 | options = options || {}; 8 | var api_key; 9 | var api_secret; 10 | var username; 11 | var password; 12 | var authToken; 13 | var session_key; 14 | 15 | var self = this; 16 | var _isTheMethodCaller = false; 17 | 18 | this.debug = options.debug || false; 19 | 20 | this.api_key = options.api_key; 21 | if(options.api_secret != undefined && options.api_secret != '') 22 | this.api_secret = options.api_secret; 23 | if(options.username != undefined && options.username != '') 24 | this.username = options.username; 25 | if(options.password != undefined && options.password != '') 26 | this.password = options.password; 27 | if(options.session_key != undefined && options.session_key != '') 28 | this.session_key = options.session_key; 29 | if(options.authToken != undefined && options.authToken != '') 30 | this.authToken = options.authToken; 31 | 32 | // Privileged method - available to public methods but not to the instance itself. 33 | self._getInfo = function(opt) { 34 | if(!self._isTheMethodCaller) throw new Error('Security exception.'); 35 | try { 36 | if(opt.artist == undefined || opt.artist == '' && typeof opt.callback == 'function') { 37 | opt.callback({ 38 | '@': {status: 'error'}, 39 | error: {'#': 'Artist not specified.'} 40 | }); 41 | } else { 42 | http.get({ 43 | host: 'ws.audioscrobbler.com', 44 | port: 80, 45 | path: '/2.0/?method=' + (opt.track != undefined && opt.track != '' ? 'track' : 'artist') + '.getinfo&api_key=' + this.api_key + '&autocorrect=1&username=' + this.username + '&artist=' + encodeURIComponent(opt.artist) + (opt.track == undefined || opt.track == '' ? '' : '&track=' + encodeURIComponent(opt.track)) 46 | }, function(res) { 47 | var body = ''; 48 | res.on('data', function(chunk) { 49 | body += chunk; 50 | }); 51 | res.on('end', function() { 52 | var parser = new xml2js.Parser(xml2js.defaults["0.1"]); 53 | parser.parseString(body, function(err, result) { 54 | if (typeof opt.callback == 'function') { 55 | opt.callback(result); 56 | } 57 | }); 58 | }); 59 | }); 60 | } 61 | } catch(e) { 62 | if(this.debug) 63 | console.log("Exception getting track info: ", e); 64 | } 65 | }; 66 | }; 67 | 68 | // Left for backwards compatibility 69 | Lastfm.prototype.init = function(options) { 70 | this.api_key = options.api_key; 71 | if(options.api_secret != undefined && options.api_secret != '') 72 | this.api_secret = options.api_secret; 73 | if(options.username != undefined && options.username != '') 74 | this.username = options.username; 75 | if(options.password != undefined && options.password != '') 76 | this.password = options.password; 77 | if(options.session_key != undefined && options.session_key != '') 78 | this.session_key = options.session_key; 79 | }; 80 | 81 | Lastfm.prototype.getSessionKey = function(callback) { 82 | var authToken = this.authToken ? this.authToken : md5(this.username + md5(this.password)); 83 | var sig = 'api_key' + this.api_key + 'authToken' + authToken + 'methodauth.getMobileSessionusername' + this.username + this.api_secret; 84 | var api_sig = md5(sig); 85 | var lastfmObj = this; 86 | http.get({ 87 | host: 'ws.audioscrobbler.com', 88 | port: 80, 89 | path: '/2.0/?method=auth.getMobileSession&' + 90 | 'username=' + this.username + '&' + 91 | 'authToken=' + authToken + '&' + 92 | 'api_key=' + this.api_key + '&' + 93 | 'api_sig=' + api_sig 94 | }, function(res) { 95 | var body = ''; 96 | res.on('data', function(chunk) { 97 | body += chunk; 98 | }); 99 | res.on('end', function() { 100 | try { 101 | var parser = new xml2js.Parser(xml2js.defaults["0.1"]); 102 | parser.parseString(body, function(err, result) { 103 | var ret = { 104 | success: result['@'].status == 'ok' 105 | }; 106 | if(ret.success) { 107 | ret.session_key = result.session.key; 108 | lastfmObj.session_key = result.session.key; 109 | } else 110 | ret.error = result.error['#']; 111 | if(typeof callback == 'function') { 112 | callback(ret); 113 | } 114 | }); 115 | } catch(e) { 116 | if(lastfmObj.debug) 117 | console.log("Exception: ", e); 118 | } 119 | }); 120 | }); 121 | }; 122 | 123 | Lastfm.prototype.scrobbleTrack = function(opt) { 124 | var options = Object.assign(opt || {}, {method: 'track.scrobble'}); 125 | this.doScrobble(options); 126 | }; 127 | 128 | Lastfm.prototype.loveTrack = function(opt) { 129 | var options = Object.assign(opt || {}, {method: 'track.love'}); 130 | this.doScrobble(options); 131 | }; 132 | 133 | Lastfm.prototype.unloveTrack = function(opt) { 134 | var options = Object.assign(opt || {}, {method: 'track.unlove'}); 135 | this.doScrobble(options); 136 | }; 137 | 138 | Lastfm.prototype.scrobbleNowPlayingTrack = function(opt) { 139 | var options = Object.assign(opt || {}, {method: 'track.updateNowPlaying'}); 140 | this.doScrobble(options); 141 | }; 142 | 143 | Lastfm.prototype.addTrackTags = function(opt) { 144 | var options = Object.assign(opt || {}, {method: 'track.addTags'}); 145 | this.doScrobble(options); 146 | }; 147 | 148 | Lastfm.prototype.doScrobble = function(options) { 149 | if(this.debug) 150 | console.log("Starting scrobbleTrack: ", options); 151 | options = options || {}; 152 | if((this.api_secret == undefined || this.api_secret == '') && typeof options.callback == 'function') { 153 | options.callback({ 154 | success: false, 155 | error: 'API Secret not specified.' 156 | }); 157 | } 158 | if((this.username == undefined || this.username == '') && typeof options.callback == 'function') { 159 | options.callback({ 160 | success: false, 161 | error: 'Username not specified.' 162 | }); 163 | } 164 | if(((this.password == undefined || this.password == '') && !this.authToken) && typeof options.callback == 'function') { 165 | options.callback({ 166 | success: false, 167 | error: 'Password not specified.' 168 | }); 169 | } 170 | 171 | options.timestamp = options.timestamp != undefined ? Math.floor(options.timestamp) : Math.floor(now() / 1000); 172 | 173 | if(this.debug) 174 | console.log("Using session key: " + this.session_key + "\n\n"); 175 | var authToken = this.authToken ? this.authToken : md5(this.username + md5(this.password)); 176 | var sig = 'api_key' + this.api_key + 'artist' + options.artist + 'method' + options.method + 'sk' + this.session_key + (options.tags != null ? 'tags' + options.tags : '') + 'timestamp' + options.timestamp + 'track' + options.track + this.api_secret; 177 | var api_sig = md5(sig); 178 | 179 | var post_obj = { 180 | api_key: this.api_key, 181 | method: options.method, 182 | sk: this.session_key, 183 | api_sig: api_sig, 184 | timestamp: options.timestamp, 185 | artist: options.artist, 186 | track: options.track 187 | }; 188 | 189 | if(options.tags != null) 190 | post_obj.tags = options.tags; 191 | var post_data = querystring.stringify(post_obj); 192 | 193 | // console.log("post_data: ", post_data); 194 | 195 | var post_options = { 196 | host: 'ws.audioscrobbler.com', 197 | port: '80', 198 | path: '/2.0/', 199 | method: 'POST', 200 | headers: { 201 | 'Content-Type': 'application/x-www-form-urlencoded', 202 | 'Content-Length': post_data.length 203 | } 204 | }; 205 | 206 | var post_req = http.request(post_options, function(res) { 207 | res.setEncoding('utf8'); 208 | res.on('data', function(chunk) { 209 | // console.log('Response: ' + chunk); 210 | var parser = new xml2js.Parser(xml2js.defaults["0.1"]); 211 | parser.parseString(chunk, function(err, result) { 212 | try { 213 | if (result['@'].status == 'ok') { 214 | // console.log("Track scrobbled (" + options.method + " )"); 215 | if(typeof options.callback == 'function') { 216 | options.callback({ 217 | success: true 218 | }); 219 | } 220 | } else { 221 | if(typeof options.callback == 'function') { 222 | options.callback({ 223 | success: false, 224 | error: result.error['#'] 225 | }); 226 | } 227 | } 228 | } catch(e) { 229 | if(this.debug) 230 | console.log("Exception parsing scrobble result: ", e); 231 | } 232 | }); 233 | }); 234 | }); 235 | post_req.write(post_data); 236 | post_req.end(); 237 | }; 238 | 239 | Lastfm.prototype.getTrackInfo = function(opt) { 240 | opt = opt || {}; 241 | if(opt.artist == undefined || opt.artist == '' && typeof opt.callback == 'function') { 242 | opt.callback({ 243 | success: false, 244 | error: 'Artist not specified.' 245 | }); 246 | } else if(opt.track == undefined || opt.track == '' && typeof opt.callback == 'function') { 247 | opt.callback({ 248 | success: false, 249 | error: 'Track not specified.' 250 | }); 251 | } else if(typeof opt.callback == 'function') { 252 | var the_callback = opt.callback; 253 | this._isTheMethodCaller = true; 254 | this._getInfo(Object.assign(opt, { 255 | callback: function(result) { 256 | this._isTheMethodCaller = false; 257 | if(result['@'].status == 'ok') { 258 | the_callback({ 259 | success: true, 260 | trackInfo: result.track 261 | }); 262 | } else { 263 | the_callback({ 264 | success: false, 265 | error: result.error['#'] 266 | }); 267 | } 268 | } 269 | })); 270 | } 271 | }; 272 | 273 | Lastfm.prototype.getArtistInfo = function(opt) { 274 | opt = opt || {}; 275 | opt.track = ''; 276 | if(opt.artist == undefined || opt.artist == '' && typeof opt.callback == 'function') { 277 | opt.callback({ 278 | success: false, 279 | error: 'Artist not specified.' 280 | }); 281 | } else if(typeof opt.callback == 'function') { 282 | var the_callback = opt.callback; 283 | this._isTheMethodCaller = true; 284 | this._getInfo(Object.assign(opt, { 285 | callback: function(result) { 286 | this._isTheMethodCaller = false; 287 | if(result['@'].status == 'ok') { 288 | the_callback({ 289 | success: true, 290 | artistInfo: result.artist 291 | }); 292 | } else { 293 | the_callback({ 294 | success: false, 295 | error: result.error['#'] 296 | }); 297 | } 298 | } 299 | })); 300 | } 301 | }; 302 | 303 | Lastfm.prototype.getTags = function(opt) { 304 | var the_callback = opt.callback; 305 | this._isTheMethodCaller = true; 306 | this._getInfo(Object.assign(opt, { 307 | callback: function(result) { 308 | this._isTheMethodCaller = false; 309 | // console.log("result: ", result); 310 | if(typeof the_callback == 'function') { 311 | if(result['@'].status == 'ok') { 312 | var tags = opt.track != undefined && opt.track != '' ? result.track.toptags.tag : result.artist.tags.tag; 313 | if(typeof tags == 'object' && !tags.length) 314 | tags = [tags]; 315 | var args = { 316 | success: true, 317 | tags: tags || [], 318 | artist: opt.track != undefined && opt.track != '' ? result.track.artist.name : result.artist.name 319 | }; 320 | if(opt.track != undefined && opt.track != '') 321 | args.track = result.track.name; 322 | the_callback(args); 323 | } else { 324 | the_callback({ 325 | success: false, 326 | error: result.error['#'] 327 | }); 328 | } 329 | } 330 | } 331 | })); 332 | }; 333 | 334 | Lastfm.prototype.getPlays = function(opt) { 335 | var the_callback = opt.callback; 336 | this._isTheMethodCaller = true; 337 | this._getInfo(Object.assign(opt, { 338 | callback: function(result) { 339 | this._isTheMethodCaller = false; 340 | if(typeof the_callback == 'function') { 341 | if(result['@'].status == 'ok') { 342 | var ret = { 343 | success: true, 344 | plays: opt.track != undefined && opt.track != '' ? result.track.userplaycount : result.artist.stats.userplaycount, 345 | artist: opt.track != undefined && opt.track != '' ? result.track.artist.name : result.artist.name 346 | }; 347 | if(ret.plays == undefined) 348 | ret.plays = 0; 349 | if(opt.track != undefined && opt.track != '') 350 | ret.track = result.track.name; 351 | the_callback(ret); 352 | } else { 353 | the_callback({ 354 | success: false, 355 | error: result.error['#'] 356 | }); 357 | } 358 | } 359 | } 360 | })); 361 | }; 362 | 363 | Lastfm.prototype.getTracks = function(opt) { 364 | // var the_callback = opt.callback; 365 | var page = opt.page ? opt.page : 1; 366 | http.get({ 367 | host: 'ws.audioscrobbler.com', 368 | port: 80, 369 | path: '/2.0/?method=user.getartisttracks&page=' + page + '&api_key=' + this.api_key + '&autocorrect=1&user=' + this.username + '&artist=' + encodeURIComponent(opt.artist) 370 | }, function(res) { 371 | var body = ''; 372 | res.on('data', function(chunk) { 373 | body += chunk; 374 | }); 375 | res.on('end', function() { 376 | var parser = new xml2js.Parser(xml2js.defaults["0.1"]); 377 | parser.parseString(body, function(err, result) { 378 | if (typeof opt.callback == 'function') { 379 | opt.callback(result); 380 | } 381 | }); 382 | }); 383 | }); 384 | }; 385 | 386 | Lastfm.prototype.getAllTracks = function(opt) { 387 | var lastfm = this; 388 | var the_callback = opt.callback; 389 | var tracks = []; 390 | opt.callback = function(result) { 391 | if(result['@'].status == 'failed') { 392 | the_callback({ 393 | success: false, 394 | reason: result.error['#'] 395 | }); 396 | } else { 397 | var numPages = result.artisttracks['@'].totalPages; 398 | for(var i=0;i", 10 | "main": "lib/index.js", 11 | "directories": { 12 | "lib": "lib" 13 | }, 14 | "engines": { 15 | "node": ">= 4.8.3" 16 | }, 17 | "dependencies" : { 18 | "crypto": ">= 0.0.3", 19 | "xml2js": ">= 0.1.13", 20 | "querystring": ">= 0.1.0" 21 | }, 22 | "devDependencies": {}, 23 | "optionalDependencies": {} 24 | } 25 | --------------------------------------------------------------------------------