-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
415 lines (346 loc) · 13.1 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
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
const SpotifyWebApi = require('spotify-web-api-node');
const path = require('path');
const express = require('express');
const consolidate = require('consolidate');
const session = require('express-session');
const { UnauthorizedError, NotFoundError } = require('./expressError');
const User = require('./models/user');
const Festival = require('./models/festival');
const Artist = require('./models/artist');
const { shuffleArray } = require('./helpers/playlist');
require('dotenv').config();
const ec2Url = 'https://www.festy.live';
const authCallbackPath = '/auth/spotify/callback';
const scopes = [
'playlist-modify-public',
],
showDialog = true,
responseType = 'token';
const app = express();
app.engine('html', consolidate.nunjucks);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({ secret: process.env.SECRET_KEY, resave: false, saveUninitialized: true, cookie: { secure: false } }));
var masterSpotifyApi = new SpotifyWebApi({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
redirectUri: ec2Url + authCallbackPath,
});
/**
* Middleware to capture the redirect URL.
*/
app.use((req, res, next) => {
// Exclude auth routes from redirect capture
if (!req.path.startsWith('/auth')) {
// Attempt to capture the redirect URL
const redirectTo = req.query.redirectTo || req.get('Referer') || '/';
req.session.redirectTo = redirectTo;
}
next();
});
/**
* Middleware to add flash messages to the response locals.
*/
app.use((req, res, next) => {
if (req.session.flashMessage) {
res.locals.flashMessage = req.session.flashMessage;
delete req.session.flashMessage;
}
next();
});
/** GET /
* Render the home page.
*/
app.get('/', async (req, res) => {
const currUser = req.session.currUser;
if (currUser) {
res.render('index.html', { user: currUser });
}
else {
res.render('index.html');
}
});
/** GET /login
* Redirect to the Spotify login page.
*/
app.get('/login', (req, res) => {
res.redirect(masterSpotifyApi.createAuthorizeURL(scopes));
});
/** GET /auth/spotify/callback
* Exchange the code for an access token and redirect to the redirectURL.
* If an error occurs, the response should have a 500 status code and an error message.
*/
app.get(authCallbackPath, async (req, res) => {
try {
const { body } = await masterSpotifyApi.authorizationCodeGrant(req.query.code);
req.session.spotifyTokens = {
accessToken: body['access_token'],
refreshToken: body['refresh_token'],
expiresIn: body['expires_in']
};
const expires_in = body['expires_in'];
const spotifyApi = initializeSpotifyApi(req.session);
setInterval(async () => {
const data = await spotifyApi.refreshAccessToken();
const access_token = data.body['access_token'];
spotifyApi.setAccessToken(access_token);
}, expires_in / 2 * 1000);
//TODO: ADD something to keep this from refreshing so often
const user = await spotifyApi.getMe();
req.session.currUser = user.body;
const spotifyUserId = user.body.id;
const userExists = await User.checkUserExists(spotifyUserId);
if (!userExists) {
const displayName = user.body.display_name;
await User.createUser(spotifyUserId, displayName);
}
userDBId = await User.getUserId(spotifyUserId);
req.session.currUser.dbid = userDBId.id;
const redirectUrl = req.session.redirectTo || '/';
res.redirect(redirectUrl);
}
catch (err) {
console.log('Error logging in:', err);
res.status(500).send('Internal Server Error');
}
});
/** GET /logout
* Log out the current user.
* The response should redirect to the home page.
*/
app.get('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
console.error('Error destroying session:', err);
}
res.redirect('/');
});
});
/** GET /profile
* Retrieve the current user's profile.
* The response should be a JSON object with the user data.
*/
app.get('/profile', ensureLoggedIn, async (req, res) => {
const currUser = req.session.currUser;
res.render('profile.html', { user: currUser });
});
/* GET /playlists
* Retrieve all playlists for the current user.
* The response should be a JSON object with the playlist data.
*/
app.get('/playlists', ensureLoggedIn, async (req, res) => {
const currUser = req.session.currUser;
const spotifyApi = initializeSpotifyApi(req.session);
const playlists = await User.getPlaylists(currUser.dbid);
for (let playlist of playlists) {
playlist.url = `https://open.spotify.com/playlist/${playlist.playlist_spotify_id}`;
if (playlist.created_at < Date.now() - 86400000) {
try {
await spotifyApi.getPlaylist(playlist.playlist_spotify_id);
User.updatePlaylistCreatedAt(playlist.id, Date.now());
}
catch {
await User.deletePlaylist(playlist.id);
playlists.splice(playlists.indexOf(playlist), 1);
continue;
}
}
}
res.render('playlists.html', { playlists: playlists, user: currUser });
});
/**POST /playlists
* Delete a playlist from the database and delete the playlist from spotify.
* The request body should contain the spotify id and the playlist id.
* The response should be a JSON object with a message.
*/
app.post('/playlists', async (req, res) => {
currUser = req.session.currUser;
const spotifyApi = initializeSpotifyApi(req.session);
const playlistId = req.body.playlistId;
const spotifyId = req.body.spotifyId;
await User.deletePlaylist(playlistId, currUser.dbid);
try {
await spotifyApi.unfollowPlaylist(spotifyId);
} catch (error) {
console.error('Error unfollowing playlist:', error);
}
res.json({ message: 'Playlist deleted' });
});
/** GET /festivals
* Retrieve all festivals.
* The response should be a JSON object with the festival data.
* If an error occurs, the response should have a 500 status code and an error message.
*/
app.get('/festivals', async (req, res) => {
try {
const festivals = await Festival.getByDate();
const currUser = req.session.currUser;
for (let festival of festivals) {
festival.date = festival.date.toISOString().split('T')[0];
}
// Render the 'festivals.html' template with the retrieved festival data and user data
res.render('festivals.html', { festivals, user: currUser });
} catch (err) {
// Handle any errors here, such as database query errors
console.error(err);
res.status(500).send('Internal Server Error');
}
});
/** GET /festivals/:id
* Retrieve the festival with the given ID.
* The response should be a JSON object with the festival data.
* If an error occurs, the response should have a 500 status code and an error message.
*/
app.get('/festivals/:id', async (req, res) => {
try {
// Retrieve the festival ID from the request parameters
const festivalId = req.params.id;
// Call the getFestivalWithActs function to retrieve the festival data
const festival = await Festival.getFestivalWithActs(festivalId);
//format date
festival.date = festival.date.toISOString().split('T')[0];
// Retrieve the current user from the session if needed
const currUser = req.session.currUser;
// Render the 'festival.html' template with the retrieved festival data and user data
res.render('festival.html', { festival, user: currUser });
} catch (err) {
// Handle any errors here, such as database query errors
console.error(err);
res.status(500).send('Internal Server Error');
}
});
/** POST /festivals/:id
* Create a new playlist for the festival with the given ID.
* The request body should contain a festivla name, an array of artist IDs and an array of track counts.
*
* The playlist should be created and the tracks added to it.
* The response should be a JSON object with a message and the playlist ID.
* If an error occurs, the response should have a 500 status code and an error message.
*/
app.post('/festivals/:user', async (req, res) => {
try {
const spotifyApi = initializeSpotifyApi(req.session);
const currUser = req.session.currUser;
const artistIds = req.body.artistIds;
const trackCounts = req.body.trackCounts;
const festivalName = req.body.festivalName;
// Combine artist IDs and track counts into an array of objects
const artistTrackData = artistIds.map((id, index) => {
return { id: id, count: parseInt(trackCounts[index], 10) };
});
// Define a function to fetch top tracks for an artist
const fetchTopTracks = async (artistSpotifyId, count) => {
//TODO: chack if tracks need to be updated
//If need to be updated then update with API call
//otherwise get from database
const topTracks = await Artist.getTracks(artistSpotifyId);
if (topTracks.length === 0) {
const topTracksResponse = await spotifyApi.getArtistTopTracks(artistSpotifyId, 'US');
for (let track of topTracksResponse.body.tracks) {
await Artist.addTrack(artistSpotifyId, track.id);
}
let topTracks = shuffleArray(topTracksResponse.body.tracks);
topTracks = topTracks.slice(0, count);
return topTracks.map(track => `spotify:track:${track.id}`);
}
for (let track of topTracks) {
if (Date.now() - track.date_added > 604800000) { //check if track is older than 7 days
await Artist.deleteTracks(artistSpotifyId);
const topTracksResponse = await spotifyApi.getArtistTopTracks(artistSpotifyId, 'US');
for (let track of topTracksResponse.body.tracks) {
await Artist.addTrack(artistSpotifyId, track.id);
}
let topTracks = shuffleArray(topTracksResponse.body.tracks);
topTracks = topTracks.slice(0, count);
return topTracks.map(track => `spotify:track:${track.id}`);
}
}
let requestedTracks = shuffleArray(topTracks);
requestedTracks = requestedTracks.slice(0, count); // Get the first 'count' tracks
return requestedTracks.map(track => `spotify:track:${track.track_spotify_id}`); // Extract track IDs
};
let allTrackUris = [];
// Fetch tracks for each artist and accumulate their URIs
for (let i = 0; i < artistTrackData.length; i++) {
const artistSpotifyId = artistTrackData[i].id;
const trackCount = artistTrackData[i].count;
const topTrackUris = await fetchTopTracks(artistSpotifyId, trackCount);
allTrackUris = allTrackUris.concat(topTrackUris);
}
// Create a new playlist
const playlistResponse = await spotifyApi.createPlaylist(`${festivalName} Playlist`, { 'description': 'Made with Festy', 'public': true });
const playlistId = playlistResponse.body.id;
// Function to add tracks to playlist in batches of 100
const addTracksInBatches = async (trackUris, playlistId) => {
for (let i = 0; i < trackUris.length; i += 100) {
const batch = trackUris.slice(i, i + 100);
await spotifyApi.addTracksToPlaylist(playlistId, batch);
}
};
// Add tracks to the playlist in batches
await addTracksInBatches(allTrackUris, playlistId);
await User.addPlaylist(currUser.dbid, playlistId, `${festivalName} Playlist`);
res.json({ message: 'Playlist created and tracks added!', playlistId: playlistId });
} catch (err) {
console.error(err);
res.status(500).send('Internal Server Error');
}
}
);
app.get('/feed', async (req, res) => {
const currUser = req.session.currUser;
res.render('feed.html', { user: currUser });
});
/** Middleware to use when they must be logged in.
*
* If not, raises Unauthorized.
*/
function ensureLoggedIn(req, res, next) {
if (!req.session.currUser) {
req.session.flashMessage = {
message: 'You must be logged in.',
color: 'red'
};
return res.redirect('/');
}
next();
}
/**
* Initializes a SpotifyWebApi instance with credentials and tokens from the session.
* @param {Object} session - The HTTP session object.
* @returns {SpotifyWebApi} An instance of SpotifyWebApi or null if tokens are not available.
*/
function initializeSpotifyApi(session) {
// Check if the session has stored Spotify tokens
if (session && session.spotifyTokens) {
const spotifyApi = new SpotifyWebApi({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
redirectUri: ec2Url + authCallbackPath,
});
// Set the access and refresh tokens for the Spotify API instance
spotifyApi.setAccessToken(session.spotifyTokens.accessToken);
spotifyApi.setRefreshToken(session.spotifyTokens.refreshToken);
return spotifyApi;
} else {
console.log("Spotify tokens are not available in the session.");
return null;
}
}
/** Handle 404 errors -- this matches everything */
app.use(function (req, res, next) {
throw new NotFoundError();
});
/** Generic error handler; anything unhandled goes here. */
app.use(function (err, req, res, next) {
if (process.env.NODE_ENV !== "test") console.error(err.stack);
const status = err.status || 500;
const message = err.message;
return res.status(status).json({
error: { message, status },
});
});
module.exports = app;