Last active
March 9, 2016 21:44
-
-
Save himynameisdave/931530e170d8d1a050c3 to your computer and use it in GitHub Desktop.
Microservice to fetch data about the last song I played from last.fm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module.exports = function lastPlay(hook) { | |
| var req = require("request-promise"); | |
| var url = "http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=himynameisdave9&api_key="+hook.env.lastsong_lastfm_key+"&format=json"; | |
| var stringify = function(data) { | |
| return JSON.stringify(data, true, 2); | |
| }; | |
| var blackList = ["Hello Internet", "This American Life", "Myke Hurley and CGP Grey"]; // items that we don't want showing up | |
| var isValidArtist = function (artist) { | |
| var validity = blackList.filter(function(dontAdd){ | |
| return artist.toLowerCase().indexOf(dontAdd.toLowerCase()) >= 0; | |
| }); | |
| return validity.length === 0; | |
| }; | |
| req(url) | |
| .then(function(data){ | |
| var lastPlayed = JSON.parse(data).recenttracks.track.filter(function(track, i){ | |
| if ( track.artist["#text"] ){ | |
| return isValidArtist(track.artist["#text"]) | |
| } | |
| return false; | |
| })[0];// there is normally an array bc each track may have different "versions"... we're always gonna use the first one in the array though, hence [0] | |
| hook.res.end(stringify({ | |
| name: lastPlayed.name || "Unknown Track", | |
| artist: lastPlayed.artist["#text"] || "Unknown Artist", | |
| album: lastPlayed.album["#text"] || "Unknown Album", | |
| url: lastPlayed.url || "http://www.last.fm/user/himynameisdave9", | |
| image: lastPlayed.image.slice(-1).pop()["#text"] || "http://i.imgur.com/OYU5axd.png", | |
| nowplaying: lastPlayed["@attr"] ? true : false | |
| }) | |
| ); | |
| }) | |
| .catch(function(e){ | |
| hook.res.end(stringify({ | |
| message: "Error fetching lastfm data!", | |
| error: e | |
| })) | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment