Skip to content

Instantly share code, notes, and snippets.

@voloshink
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save voloshink/da94c92cff610775d42a to your computer and use it in GitHub Desktop.

Select an option

Save voloshink/da94c92cff610775d42a to your computer and use it in GitHub Desktop.
// Based on http://cgbystrom.com/articles/deconstructing-spotifys-builtin-http-server/
var request = require('request');
var spotify = function(){
this.port = 4371;
this.nowPlaying = {};
this.getOauth();
}
spotify.prototype.getOauth = function() {
var _self = this;
this.csrf_token = null;
request('http://open.spotify.com/token', function(err, resp, body) {
if (err) throw err;
_self.oauth_token = JSON.parse(body).t;
_self.getCsrf();
})
}
spotify.prototype.getCsrf = function() {
var _self = this;
this.get('/simplecsrf/token.json', function(body) {
_self.csrf_token = body.token;
_self.watchForSongChange();
})
}
spotify.prototype.get = function(url, callback) {
var options = {
//Only accepts request coming from the spotify domains
headers: {
Origin: 'https://open.spotify.com',
Referer: 'https://embed.spotify.com/?uri=spotify:track:5Zp4SWOpbuOdnsxLqwgutt'
},
qs: {
oauth: this.oauth_token
},
rejectUnauthorized: false,// #YOLO
url: 'https://' + this.generateRandomString() + '.spotilocal.com:' + this.port + url //getting around the domain connection limit
}
if (this.csrf_token) options.qs.csrf = this.csrf_token;
request(options, function(err, resp, body){
if (err) throw err;
callback(JSON.parse(body));
})
}
spotify.prototype.getSongInfo = function() {
var _self = this;
this.get('/remote/status.json', function(body) {
var song = body.track.track_resource.name;
var artist = body.track.artist_resource.name;
var nowPlaying = {artist:artist,song:song};
_self.changeSong(nowPlaying);
})
};
spotify.prototype.changeSong = function(nowPlaying) {
if (this.nowPlaying != null && nowPlaying.song !== this.nowPlaying.song) {
this.nowPlaying = nowPlaying;
console.log(nowPlaying);
}
}
spotify.prototype.watchForSongChange = function() {
var _self = this;
setInterval(function() {
_self.getSongInfo();
}, 3000);
}
spotify.prototype.generateRandomString = function() {
var charset = "abcdefghijklmnopqrstuvwxyz";
var arr = [];
for (var i = 0; i < 10; i++) {
arr.push(charset.charAt(Math.floor(Math.random() * charset.length)));
}
return arr.join('');
}
var spot = new spotify;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment