-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·310 lines (245 loc) · 9.63 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
#!/usr/bin/env node
import chalk from "chalk";
import inquirer from "inquirer";
import gradient from "gradient-string";
import chalkAnimation from "chalk-animation";
import nconf from "nconf";
import SpotifyWebApi from "spotify-web-api-node"
import open from "open";
import { createSpinner } from "nanospinner";
import path from "path";
import os from "os";
import spotifyMacClient from "spotify-node-applescript";
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const { Command } = require('commander');
const program = new Command();
// setup nconf for storing and retrieving keys
const CONFIG_PATH = path.join(os.homedir(),'/.spotify-cli-config.json');
nconf.env().file(CONFIG_PATH);
let spotifyApi = null;
let SPOTIFY_CLIENT_ID = nconf.get("SPOTIFY_CLIENT_ID");
let SPOTIFY_CLIENT_SECRET = nconf.get("SPOTIFY_CLIENT_SECRET");
const sleep = (ms) => { return new Promise(resolve => setTimeout(resolve, ms)) };
const setKeys = async () => {
const setKeysTitle = chalkAnimation.rainbow("It's time to set your Spotify keys! \n");
await sleep(2000);
setKeysTitle.stop();
const websitePrompt = await inquirer.prompt({
name: "sendToWebsite",
type: "confirm",
message: "Do you want to go to the Spotify developer website get an api key?",
default: true
});
if (websitePrompt.sendToWebsite) {
const spinner = createSpinner('Opening Spotify developer website...').start();
await sleep(2000);
await open("https://developer.spotify.com/dashboard/applications");
spinner.success();
}
const clientIdPrompt = await inquirer.prompt({
name: "clientId",
type: "input",
message: "What is your Spotify client ID? 🎫",
default: SPOTIFY_CLIENT_ID
});
SPOTIFY_CLIENT_ID = clientIdPrompt.clientId;
nconf.set("SPOTIFY_CLIENT_ID", SPOTIFY_CLIENT_ID);
nconf.save();
const clientSecretPrompt = await inquirer.prompt({
name: "clientSecret",
type: "input",
message: "What is your Spotify client secret? 🔑",
default: SPOTIFY_CLIENT_SECRET
});
SPOTIFY_CLIENT_SECRET = clientSecretPrompt.clientSecret;
nconf.set("SPOTIFY_CLIENT_SECRET", SPOTIFY_CLIENT_SECRET);
nconf.save();
};
const initSpotifyApi = async () => {
if (SPOTIFY_CLIENT_ID == undefined || SPOTIFY_CLIENT_SECRET == undefined) {
await setKeys();
}
return new SpotifyWebApi({
clientId: SPOTIFY_CLIENT_ID,
clientSecret: SPOTIFY_CLIENT_SECRET,
});
};
const resetConfig = async () => {
SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET = undefined;
initSpotifyApi();
};
const setAccessToken = async (spotifyApi) => {
let credentialResponse = await spotifyApi.clientCredentialsGrant();
// console.log(credentialResponse.body['access_token']);
spotifyApi.setAccessToken(credentialResponse.body['access_token']);
}
const play = async (type,name) => {
const playSpinner = createSpinner('Playing...');
// if no name is provided, play the current track and exit
if (!name) {
playSpinner.start();
await sleep(100);
await spotifyMacClient.play();
playSpinner.success();
return;
}
let searchResult = null;
let searchListings = null;
const searchSpinner = createSpinner(`${gradient.rainbow(`Searching for ${name}...`)}`).start();
switch (type) {
case "track":
searchResult = await spotifyApi.searchTracks(name);
searchListings = searchResult.body.tracks.items;
break;
case "artist":
searchResult = await spotifyApi.searchArtists(name);
searchListings = searchResult.body.artists.items;
break;
case "playlist":
searchResult = await spotifyApi.searchPlaylists(name);
searchListings = searchResult.body.playlists.items;
break;
default:
searchResult = await spotifyApi.searchTracks(name);
searchListings = searchResult.body.tracks.items;
break;
}
if (searchListings.length > 1) {
searchSpinner.success();
// make array of top 5 search results
const trackNames = searchListings.map(track => track.name).slice(0,6);
// show search results and ask user to select one
const selectedTrack = await inquirer.prompt({
name: "track",
type: "list",
message: `Which ${type} do you want to play?`,
choices: trackNames
});
let selectedIndex = (trackNames.indexOf(selectedTrack.track));
let result = searchListings[selectedIndex];
playSpinner.update({text: `Playing ${result.name} ${result.artists ? `by ${result.artists[0].name}` : ""}`});
playSpinner.start();
await spotifyMacClient.playTrack(result.uri)
playSpinner.success();
} else if (searchListings.length == 1) {
searchSpinner.success();
let result = searchListings[0];
playSpinner.update({text: `Playing ${result.name} ${result.artists ? `by ${result.artists[0].name}` : ""}`});
playSpinner.start();
await spotifyMacClient.playTrack(result.uri)
playSpinner.success();
} else {
searchSpinner.error();
console.log(chalk.red("Result not found!"));
}
};
const pause = async () => {
const pauseSpinner = createSpinner('Pausing...').start();
await sleep(100);
await spotifyMacClient.pause();
pauseSpinner.success();
};
const next = async () => {
const nextSpinner = createSpinner('Next...').start();
await sleep(100);
await spotifyMacClient.next();
nextSpinner.success();
};
const previous = async () => {
const previousSpinner = createSpinner('Previous...').start();
await sleep(100);
await spotifyMacClient.previous();
previousSpinner.success();
};
const volumeUp = async () => {
const volumeUpSpinner = createSpinner('Volume up...').start();
await sleep(100);
await spotifyMacClient.volumeUp();
volumeUpSpinner.success();
};
const volumeDown = async () => {
const volumeDownSpinner = createSpinner('Volume down...').start();
await sleep(100);
await spotifyMacClient.volumeDown();
volumeDownSpinner.success();
};
const setVolume = async (volume) => {
const setVolumeSpinner = createSpinner(`Setting ${gradient.atlas(`volume`)} to ${chalk.cyan( `${volume}`)}`).start();
await sleep(100);
await spotifyMacClient.setVolume(volume);
setVolumeSpinner.success();
};
const getStatus = async () => {
let status;
let trackLength;
let trackPosition;
await spotifyMacClient.getTrack(async (err, track) => {
await spotifyMacClient.getState(async (err, state) => {
// capitalize state.state
state.state = state.state.charAt(0).toUpperCase() + state.state.slice(1);
status = chalkAnimation.neon(`${state.state + ": " + track.name + " by " + track.artist} from ${track.album}`, 1.8);
// convert progress from seconds to ms
state.position *= 1000;
await sleep(1000);
let progresBar = chalkAnimation.rainbow(generateProgressBar(state.position, track.duration), 0.5);
await sleep(1000);
progresBar.stop()
});
});
}
const about = async () => {
console.log(chalk.blue(`Yeah so this CLI was developed by this random kid called ${chalk.cyan(`@trevorkw7`)}`));
await sleep(1000);
console.log(chalk.blue(`It's pretty cool, right?`));
await sleep(1000);
console.log(chalk.blue(`If you have any questions, feel free to get in touch through the GitHub repo`));
await sleep(1000);
const githubPrompt = await inquirer.prompt({
name: "sendToGithub",
type: "confirm",
message: "Speaking of GitHub, wanna check it out 👀?",
default: true
});
if (githubPrompt.sendToGithub) {
const spinner = createSpinner('Opening GitHub...').start();
await sleep(2000);
await open("https://github.com/trevorkw7/Spotify-CLI");
spinner.success();
} else {
console.log ("Ok, maybe next time!");
}
};
const msToMinAndSec = (ms) => {
var minutes = Math.floor(ms / 60000);
var seconds = ((ms % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}
const generateProgressBar = (progress, length) => {
const barLength = 30;
let leftTicks = (progress / length) * barLength;
let rightTicks = barLength - leftTicks;
let progressBar = `${(msToMinAndSec(progress))} [${'='.repeat(leftTicks)}⚪️${'-'.repeat(rightTicks)}] ${msToMinAndSec(length)}`;
return progressBar;
}
// init spotify api
spotifyApi = await initSpotifyApi();
// set an access token
await setAccessToken(spotifyApi);
await spotifyMacClient.unmuteVolume();
// map commands to functions;
const playCommand = program.command('play [type] [name]')
playCommand.description('play current song / play a specific [track] or [artist] or [playlist]');
playCommand.action(async (type, name) => {play(type, name)});
program.command('pause').action((async () => {pause()}));
program.command('next').action((async () => {next()}));
program.command('prev').action((async () => {previous()}));
program.command('volumeUp').action((async () => {volumeUp()}));
program.command('volumeDown').action((async () => {volumeDown()}));
program.command('volume')
.argument('<volume>')
.action((volume) => {setVolume(volume)});
program.command('configure').action(async () => {resetConfig()});
program.command('status').action(async () => {getStatus()});
program.command('about').action(async () => {about()});
program.parse(process.argv);