-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
225 lines (203 loc) · 6.33 KB
/
app.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
require("dotenv").config(); // configure access to our .env
var express = require("express"); // Express web server framework
var cors = require("cors");
var cookieParser = require("cookie-parser");
var SpotifyWebApi = require("spotify-web-api-node");
var bodyParser = require("body-parser");
var ejs = require("ejs");
var favicon = require('serve-favicon');
var path = require('path');
const client_id = process.env.CLIENT_ID;
const client_secret = process.env.CLIENT_SECRET;
const redirect_uri = "http://localhost:8888/callback";
const scope = ["user-read-private", "user-read-email", "user-top-read", "playlist-modify-private"];
const stateKey = "spotify_auth_state";
const PORT = 8888;
var app = express();
app
.use(express.static(__dirname + "/public"))
.use(cors())
.use(cookieParser())
.use(
bodyParser.urlencoded({
extended: true,
}))
.use(favicon(path.join(__dirname, 'public', 'images/favicon.ico')))
.use('/public/images', express.static(__dirname + '/public/images'));
app.set("view engine", "ejs");
app.get("/", function (req, res) {
res.render("home");
});
app.get("/categories", function (req, res) {
var categories = [
{
title: "Pain Relief",
number: 1,
},
{
title: "Managing Depression",
number: 2,
},
{
title: "Promoting Wellness",
number: 3,
},
{
title: "Improving Memory",
number: 4,
},
{
title: "Sleep",
number: 5,
},
{
title: "Stress Management",
number: 6,
},
];
res.render("categories", {
categories: categories
});
});
app.get("/playlist", async (req, res) => {
// Tested stuff that works
var userId = await getUserId(); // returns userId, string
console.log(`UserID: ${userId}`);
// var topTracks = await findTopTracks();
// console.log("Found user's top tracks");
// console.log(topTracks);
// console.log(typeof(topTracks));
var topTracks = ['5iFwAOB2TFkPJk8sMlxP8g', '5z8qQvLYEehH19vNOoFAPb'];
var genres = [
'indie pop', 'indie poptimism', 'easy listening'
];
var genTracks = await findTracks(topTracks, genres);
var genTracksURIs = genTracks[0];
var tracks = genTracks[1];
console.log(tracks);
console.log(`Generated recommended tracks`);
//////////////////////////////////////////////////////////////////////
// var newPlaylist = await generatePlaylist(userId, 'Pain Relief', 'Here is a therapeutic pain relief playlist');
// console.log(newPlaylist);
// var playlistId = '1dmCfhZzi5q4EGdqJGp4sl';
// addToPlaylist(userId, playlistId, genTracksURIs);
res.render("playlist", {
tracks: tracks
});
});
// Instantiate Spotify Web API
var spotifyApi = new SpotifyWebApi({
clientId: client_id,
clientSecret: client_secret,
redirectUri: redirect_uri,
});
// Authentication
app.get("/login", function (req, res) {
var state = generateRandomString(16);
res.cookie(stateKey, state);
var authorizationURL = spotifyApi.createAuthorizeURL(scope, state);
res.redirect(authorizationURL);
});
app.get("/callback", async (req, res) => {
var code = req.query.code || null;
if (code == null) {
console.log("code isi null");
}
try {
var data = await spotifyApi.authorizationCodeGrant(code);
var access_token = data.body["access_token"];
console.log('Authenticated');
} catch (err) {
console.log("something went wrong :PP");
}
spotifyApi.setAccessToken(access_token);
res.redirect("/categories");
});
// Find user's top tracks, return a list of song IDs
async function findTopTracks() {
try {
var topTracksInfo = await spotifyApi.getMyTopTracks({ time_range: 'long_term', limit:10, offset:0 });
var topTracks = topTracksInfo.body['items'];
var topTracksIds = [];
for (let i = 0; i < 10; i++) {
try {
topTracksIds.push(topTracks[i].id);
} catch (err) {
console.log('something went wrong with adding top tracks to list :PP');
console.log(err);
}
}
return topTracksIds;
}
catch (err) {
console.log("something went wrong with getting top tracks :PP");
console.log(err);
}
}
// Find song recommendations
async function findTracks(topTracks, genres) {
try {
var tracksInfo = await spotifyApi.getRecommendations({ // idea !! seed artists but also customize other factors
seed_tracks: topTracks, // list of song IDs
seed_genres: genres, // list of genre names
limit: 10
});
var genTracks = tracksInfo.body['tracks'];
var genTracksURIs = [], genTracksInfo = [];
for (let i = 0; i < 10; i++) {
try {
genTracksURIs.push(genTracks[i].uri);
genTracksInfo.push({ title: genTracks[i].name, artists: genTracks[i].artists[0].name, duration: millisToMinutesAndSeconds(genTracks[i].duration_ms)});
} catch (err) {
console.log('there was an error in adding trackURI or info :P');
}
}
return [genTracksURIs, genTracksInfo];
} catch (err) {
console.log("something went wrong with finding tracks for the playlist :PP");
}
}
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}
// Create a new playlist
async function generatePlaylist(userId, title, description) {
try {
console.log('creating new playlist');
var newPlaylist = await spotifyApi.createPlaylist(userId, title, { public: false });
return newPlaylist;
}
catch (err) {
console.log("something went wrong with creating the playlist :PP");
}
}
async function addToPlaylist(userId, playlistId, tracks) {
try {
await spotifyApi.addTracksToPlaylist(userId, playlistId, tracks);
console.log('Added tracks to playlist');
} catch (err) {
console.log("something went wrong with adding songs to the playlist :PP");
}
}
// Helper functions
var generateRandomString = function (length) {
var text = "";
var possible =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};
async function getUserId() {
try {
var data = await spotifyApi.getMe();
return data.body['id'];
} catch (err) {
console.log("something went wrong with fetching user data :PP");
}
}
console.log(`Listening on ${PORT}`);
app.listen(PORT);