-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
65 lines (57 loc) · 2.02 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
const SpotifyWebApi = require('spotify-web-api-node');
const express = require('express');
const {downloadSong, setupSlsk} = require('./downloadSong');
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const SLSK_USER = process.env.SLSK_USER;
const SLSK_PASS = process.env.SLSK_PASS;
const REDIRECT_HOST = process.env.REDIRECT_HOST;
const REDIRECT_URI = `http://${REDIRECT_HOST}:3005/auth`;
const playlistId = process.argv.slice(2)[0];
const app = express();
const spotifyApi = new SpotifyWebApi({
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET,
redirectUri: REDIRECT_URI
});
const downloadSongs = async (songs) => {
const asyncArray = songs.map((songName) => () => downloadSong(songName));
try {
await Promise.all(asyncArray.map(elem => elem()));
} catch (error) {
console.log("download failed: ", error);
}
}
const getPlaylistSongs = async () => {
const playlistName = await spotifyApi.getPlaylist(playlistId);
const playlist = await spotifyApi.getPlaylistTracks(playlistId);
const songs = [];
for (track of playlist.body.items) {
songs.push(track.track.artists[0].name + " " + track.track.name)
}
console.log(playlistName)
console.log(`Playlist found: $ We will try and download: `);
console.log(songs);
downloadSongs(songs);
}
const setAccessToken = async (code) => {
try {
const data = await spotifyApi.authorizationCodeGrant(code);
spotifyApi.setAccessToken(data.body['access_token']);
spotifyApi.setRefreshToken(data.body['refresh_token']);
console.log("Authenticated!");
getPlaylistSongs();
} catch (err) {
console.log("authorization failed: ", err);
}
}
app.get("/auth", (req, res, next) => {
setAccessToken(req.query.code);
res.send("You have been authenticated and can close this tab!");
})
app.listen(3005, async () => {
console.log("listening on port 3005");
const authorizeURL = spotifyApi.createAuthorizeURL([], "state");
await setupSlsk(SLSK_USER, SLSK_PASS);
console.log("Please click this link: ", authorizeURL);
})