Commit b99545ba authored by Deac Karns's avatar Deac Karns
Browse files

add executable back in

parent a44cf411
#!/usr/bin/env node
const colors = require('colors');
const Table = require('cli-table');
const fs = require('fs');
const program = require('commander');
const home = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
const inquirer = require('inquirer');
const request = require('request');
const querystring = require('querystring');
const readlineLib = require('readline');
const opn = require('opn');
const SpotifyWebApi = require('spotify-web-api-node');
let spotifyApi = new SpotifyWebApi();
const readline = readlineLib.createInterface({
input: process.stdin,
output: process.stdout
});
program
.version('0.0.1')
.option('-a, --add', 'Add current track to default playlist', 0)
.option('-s, --settings', 'Display the current configuration', 0)
.option('-c, --current', 'Display the current playing track', 0)
.option('-p, --playlist', 'Display the default playlist', 0)
.parse(process.argv);
console.reset = function () {
return process.stdout.write('\033c');
}
var redirect_uri = 'http://spotiko.karnsonline.com'
const loadConfig = function(){
return JSON.parse(fs.readFileSync(home+'/.spotiko', 'utf8')) || {};
}
const writeToConfig = function(configObj) {
let mergedConfig = Object.assign(config, configObj);
fs.writeFileSync(home+'/.spotiko', JSON.stringify(mergedConfig, null, 4), { flag: 'w' }, function (err) {
if (err) throw err;
});
}
if (!fs.existsSync(home+'/.spotiko')) {
config = {
client_id:null,
client_secret:null
};
writeToConfig({});
}
var config = loadConfig();
const promptForAuthorizationCode = function() {
return new Promise((resolve) => {
readline.question(colors.cyan('\nPaste the provided authentication code here:\n\n'), (answer) => {
readline.close();
resolve(answer)
})
});
}
const promptForInput = function(prompt) {
return new Promise((resolve) => {
readline.question(colors.cyan('\n'+prompt+'\n\n'), (answer) => {
readline.close();
resolve(answer)
})
});
}
const refreshAccessToken = function() {
let options = {
url: 'https://accounts.spotify.com/api/token',
form: {
grant_type: "refresh_token",
refresh_token: config.refresh_token
},
headers: {
'Authorization': 'Basic ' + (new Buffer.from(config.client_id + ':' + config.client_secret).toString('base64'))
},
json: true
}
return new Promise(function(resolve) {
request.post(options, function(error, response, body) {
if (!error && response.statusCode === 200) {
writeToConfig(
{
access_token:body.access_token
}
);
}
resolve(body.access_token);
});
})
}
const displayAuthorizeUrl = function() {
// your application requests authorization
let scope = 'user-read-private user-read-currently-playing playlist-read-private playlist-modify-private playlist-modify-public playlist-read-collaborative';
let authorizeUrl = 'https://accounts.spotify.com/authorize?' +
querystring.stringify({
response_type: 'code',
client_id: config.client_id,
scope: scope,
redirect_uri: redirect_uri,
state: 'spotiko-attempt-authentication'
});
opn(authorizeUrl)
return new Promise(function(resolve){
console.log(colors.cyan('\nGo to the following address in your browser (if it doesnt open automatically):\n'))
console.log(colors.yellow(authorizeUrl));
resolve(true);
})
}
const exchangeAuthorizationCodeForTokens = function(code) {
let options = {
url: 'https://accounts.spotify.com/api/token',
form: {
grant_type: "authorization_code",
code: code,
redirect_uri: redirect_uri
},
headers: {
'Authorization': 'Basic ' + (new Buffer.from(config.client_id + ':' + config.client_secret).toString('base64'))
},
json: true
}
return new Promise(function(resolve, reject) {
request.post(options, function(error, response, body) {
if (!error && response.statusCode === 200) {
writeToConfig(
{
access_token:body.access_token,
refresh_token:body.refresh_token
}
);
resolve(true);
}
});
});
}
const addTrackToPlaylist = function(track,playlist) {
trackString = querystring.stringify({
uris: track.track_uri,
});
let options = {
url: ' https://api.spotify.com/v1/playlists/'+playlist.id+'/tracks?'+trackString,
auth: {
'bearer': config.access_token
},
json: true
}
return new Promise(function(resolve, reject) {
request.post(options, function(error, response, body) {
if (!error && response.statusCode >= 200 && response.statusCode < 300) {
resolve(true);
}
});
});
}
const getCurrentTrack = function() {
let options = {
url: 'https://api.spotify.com/v1/me/player/currently-playing',
auth: {
'bearer': config.access_token
},
json: true
}
return new Promise(function(resolve, reject) {
request.get(options, function(error, response, body){
resolve({
album_name: body.item.album.name,
album_artist: body.item.album.artists.map( (artist) => artist.name).toString(),
track_name: body.item.name,
track_id: body.item.id,
track_url: body.item.external_urls.spotify,
track_uri: body.item.uri,
});
})
})
}
const getDefinedPlaylist = function() {
let options = {
url: 'https://api.spotify.com/v1/me/playlists',
auth: {
'bearer': config.access_token
}
}
return new Promise(function(resolve, reject) {
request(options, function(error, response, body){
let playlists = JSON.parse(body)
let use = playlists.items.filter(function(playlist) {
return (playlist.name == 'Bi Weekly Build')
})
playlist = use.shift()
resolve(playlist);
})
})
}
if(!config.client_id){
promptForInput('Enter your client id:')
.then((client_id) => {
writeToConfig(
{
client_id: client_id
}
);
})
}
if(!config.client_secret){
promptForInput('Enter your client secret:')
.then((client_secret) => {
writeToConfig(
{
client_secret: client_secret
}
);
})
}
if(!config.access_token){
console.reset()
displayAuthorizeUrl()
.then( () => {
promptForAuthorizationCode()
.then( (code) => {
writeToConfig({authorization_code:code});
return code;
})
.then( (code) => {
exchangeAuthorizationCodeForTokens(code)
.then(() => process.exit());
})
});
}
if(program.add){
refreshAccessToken()
.then( () => {
getCurrentTrack()
.then( (track) => {
console.log(colors.cyan('\n[Track]'))
console.log(colors.magenta(' Artist: ')+track.album_artist);
console.log(colors.magenta(' Album: ')+track.album_name);
console.log(colors.magenta(' Name: ')+track.track_name);
console.log(colors.magenta(' ID: ')+track.track_id);
console.log(colors.magenta(' URI: ')+track.track_uri);
console.log(colors.magenta(' URL: ')+track.track_url);
return track
})
.then( (track) => {
return getDefinedPlaylist()
.then( (playlist) => {
console.log(colors.cyan('\n[Playlist]'))
console.log(colors.magenta(' Name: ')+playlist.name)
console.log(colors.magenta(' ID: ')+playlist.id)
return playlist
}).then( (playlist) => {
return addTrackToPlaylist(track, playlist)
})
.finally( () => {
console.log('\nTrack added to playlist\n');
process.exit()
})
})
})
}
else if(program.current){
refreshAccessToken()
.then( () => {
return getCurrentTrack()
.then( (track) => {
console.log(colors.cyan('\n[Track]'))
console.log(colors.magenta(' Artist: ')+track.album_artist);
console.log(colors.magenta(' Album: ')+track.album_name);
console.log(colors.magenta(' Name: ')+track.track_name);
console.log(colors.magenta(' ID: ')+track.track_id);
console.log(colors.magenta(' URI: ')+track.track_uri);
console.log(colors.magenta(' URL: ')+track.track_url);
})
})
.finally( () => process.exit())
}
else if(program.playlist){
refreshAccessToken()
.then( () => {
return getDefinedPlaylist()
.then( (playlist) => {
console.log(colors.cyan('\n[Playlist]'))
console.log(colors.magenta(' Name: ')+playlist.name)
console.log(colors.magenta(' ID: ')+playlist.id)
})
})
.finally( () => process.exit())
}
else if(program.settings){
console.log(config)
}
else {
program.help();
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment