-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
395 lines (342 loc) · 13.6 KB
/
server.js
File metadata and controls
395 lines (342 loc) · 13.6 KB
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
const express = require('express');
const app = express();
const path = require('path');
const cookieParser = require('cookie-parser');
const compression = require('compression');
const helmet = require("helmet");
const csv = require('csv-parser');
const fs = require('fs');
const { default: axios } = require('axios');
require('dotenv').config();
app.set('views', path.join(__dirname,'views'));
app.set('view engine', 'hbs');
app.use(express.static('public'))
.use(cookieParser())
.use(express.urlencoded({extended: true}))
.use(express.json())
.use(compression())
.use(helmet({
contentSecurityPolicy: {
useDefaults: true,
directives: {
"img-src": ["'self'", "https://i.scdn.co/image/", "https://storage.googleapis.com/daneee.com/no_img.jpg"],
"media-src": ["'self'", "https://p.scdn.co/mp3-preview/"]
}
}
}));
const PORT = 1116;
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const REDIRECT_URI = process.env.REDIRECT_URI || 'http://localhost:' + PORT + '/callback';
const STATE_KEY = 'spotify_auth_state';
const LIMIT = 50;
const EMBED_DIM = 50;
const NO_IMG = "https://storage.googleapis.com/daneee.com/no_img.jpg";
const genreMap = new Map();
let genreEmbeds, horoEmbeds;
app.listen(process.env.PORT || PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/hey.html');
});
app.get('/login', (req, res) => {
fs.createReadStream('genres.csv')
.pipe(csv())
.on('data', data => {
genreMap.set(data.genre, [data.url, csvTrim(data.opp_genres), JSON.parse(data.opp_weights), csvTrim(data.opp_urls)]);
})
.on('end', () => console.log('genres loaded'));
genreEmbeds = new Map(Object.entries(JSON.parse(fs.readFileSync('genre_embeddings.json'))));
horoEmbeds = new Map(Object.entries(JSON.parse(fs.readFileSync('horoscope_embeddings.json'))));
console.log("embeddings loaded");
const state = generateRandomString(16);
res.cookie(STATE_KEY, state);
res.redirect('https://accounts.spotify.com/authorize?' + new URLSearchParams({
response_type: 'code',
client_id: CLIENT_ID,
scope: 'user-top-read',
redirect_uri: REDIRECT_URI,
state: state
}).toString());
});
app.get('/callback', (req, res) => {
const code = req.query.code || null;
const state = req.query.state || null;
const storedState = req.cookies ? req.cookies[STATE_KEY] : null;
if (state === null || state !== storedState) {
return res.redirect('/#error=state_mismatch');
}
res.clearCookie(STATE_KEY);
// Gets user token
axios.post('https://accounts.spotify.com/api/token',
new URLSearchParams({
code: code,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code'
}).toString(), {
headers: {
'content-type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + Buffer.from(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64')
}
}
).then(body => {
if (body.status !== 200) {
console.log('invalid token');
return res.redirect('/#error=invalid_token');
}
const access_token = body.data.access_token;
const params = new URLSearchParams({'limit': LIMIT, time_range: 'long_term'}).toString();
const userHeaders = {
headers: {
'Authorization': 'Bearer ' + access_token,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
// Gets user's top artists and tracks
Promise.all([axios.get('https://api.spotify.com/v1/me/top/tracks?' + params, userHeaders),
axios.get('https://api.spotify.com/v1/me/top/artists?' + params, userHeaders)]).then(userData => {
if (userData[0].data.items.length == 0) {
return res.sendFile(__dirname + '/nodata.html');
}
const tracks = userData[0].data.items;
const artists = userData[1].data.items;
const numOfTracks = tracks.length;
const numOfArtists = artists.length;
const genreWeights = new Map(); // Genre weightage
const artistGenres = new Map(); // Genres associated with each artist
const trackData = []
const artistData = [];
let totalPopularity = 0;
let minPopTrack = 101;
let minPopTrackId;
let minPopArtist = 101;
let minPopArtistId;
// Assigns weightage to genres of top artists
for (let i = 0; i < numOfArtists; i++) {
const artist = artists[i];
if (artist.popularity < minPopArtist) {
minPopArtist = artist.popularity;
minPopArtistId = artist;
}
if (i < 5) {
artistData.push({'img': getArtistImage(artist), 'artist': artist.name});
}
artistGenres.set(artist.id, artist.genres);
for (const genre of artist.genres) {
if (genreWeights.has(genre)) {
genreWeights.set(genre, genreWeights.get(genre) + Math.log(numOfArtists - i));
} else {
genreWeights.set(genre, Math.log(numOfArtists - i));
}
}
}
// Assigns weightage to artists of top tracks
for (let i = 0; i < numOfTracks; i++) {
const track = tracks[i];
let numTrackArtists = 0;
totalPopularity += track.popularity;
// Gets album covers of the user's top 5 tracks
if (i < 5) {
trackData.push({'img': getAlbumImage(track), 'title': track.name, 'artist': track.artists.length > 0 ? track.artists[0].name : 'Unknown'});
}
// Gets user's least popular favourite track
if (track.popularity < minPopTrack) {
minPopTrack = track.popularity;
minPopTrackId = track;
}
// Gets number of track artists in artistGenres
for (const artist of track.artists) {
if (artistGenres.has(artist.id)) {
numTrackArtists++;
}
}
for (const artist of track.artists) {
if (artistGenres.has(artist.id)) {
for (const genre of artistGenres.get(artist.id)) {
if (genreWeights.has(genre)) {
genreWeights.set(genre, genreWeights.get(genre) + Math.log((numOfTracks - i) / numTrackArtists));
} else {
genreWeights.set(genre, Math.log((numOfTracks - i) / numTrackArtists));
}
}
}
}
}
// Get top 5 genres from genreWeights
const topGenreData = [];
const topGenres = Array.from(genreWeights.entries()).sort((a, b) => b[1] - a[1]);
for (const genre of topGenres.slice(0, 5)) {
if (genreMap.has(genre[0])) {
topGenreData.push({ "genre": genre[0], "url": 'https://p.scdn.co/mp3-preview/' + genreMap.get(genre[0])[0] });
}
}
// Get user's horoscope
const horoscope = getHoroscope(topGenres.slice(0, 10));
// Assigns weightage to their corresponding genres
const opps = new Map();
// Assigns weightage to dissimilar genres
for (const [key, value] of genreWeights.entries()) {
// Skips genre if it cannot possibly be the most loved/hated
if (genreMap.has(key)) {
const genreData = genreMap.get(key);
for (i = 0; i < genreData[1].length; i++) {
const genre = genreData[1][i];
if (opps.has(genre)) {
const oppItem = opps.get(genre);
oppItem.weight += genreData[2][i] * value;
} else {
opps.set(genre, {
genre: genre,
weight: genreData[2][i] * value,
url: 'https://p.scdn.co/mp3-preview/' + genreData[3][i]
});
}
}
}
}
return res.render('yours', {
songs: trackData,
artists: artistData,
loves: topGenreData,
hates: Array.from(opps.values()).sort((a, b) => b.weight - a.weight).slice(0, 5),
score: totalPopularity / numOfTracks,
desc: getBasic(totalPopularity / numOfTracks),
horoemoji: getHoroEmoji(horoscope),
horoscope: horoscope,
trackUrl: getAlbumImage(minPopTrackId),
trackTitle: Object.hasOwn(minPopTrackId, 'name') ? minPopTrackId.name : 'Unknown',
trackArtist: Object.hasOwn(minPopTrackId, 'artists') ? minPopTrackId.artists[0].name : 'Unknown',
artistUrl: getArtistImage(minPopArtistId),
artistName: Object.hasOwn(minPopArtistId, 'name') ? minPopArtistId.name : 'Unknown'
});
}).catch(err => {
console.log('error from getting user\'s top tracks and artists');
console.log(err.message);
res.sendFile(__dirname + '/error.html');
});
}).catch(err => {
console.log('error from getting authorization code');
console.log(err.message);
res.sendFile(__dirname + '/hey.html');
});
});
// Generates a random 16 character string for cookies
const generateRandomString = function(length) {
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let text = '';
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};
// Returns an array of genres given its string representation from the csv file
// Used in place of JSON.parse() as parse() does not play well with certain characters found in the genres
const csvTrim = genreString => {
const arr = genreString.slice(1,-1).split(',');
for (i = 0; i < arr.length; i++) {
arr[i] = arr[i].trim().slice(1,-1);
}
return arr;
}
const getHoroscope = genreWeights => {
let totalGenreEmbed = new Array(EMBED_DIM);
for (let i = 0; i < EMBED_DIM; ++i) totalGenreEmbed[i] = 0;
for (const [key, value] of genreWeights) {
// console.log(key + ": " + value);
if (genreEmbeds.has(key)) {
for (let i = 0; i < EMBED_DIM; i++) {
totalGenreEmbed[i] += genreEmbeds.get(key)[i] // * value; // value is the weight of the genre
}
}
}
let max = -1;
let horo = "";
for (const [key, value] of horoEmbeds.entries()) {
similarity = cosineSimilarity(totalGenreEmbed, value)
// console.log(key + ": " + similarity);
if (similarity > max) {
max = similarity
horo = key
}
}
return horo;
}
const cosineSimilarity = (arr1, arr2) => {
let dotProduct = 0;
let magnitude1 = 0;
let magnitude2 = 0;
for (let i = 0; i < arr1.length; i++) {
dotProduct += arr1[i] * arr2[i];
magnitude1 += arr1[i] ** 2;
magnitude2 += arr2[i] ** 2;
}
return dotProduct / (Math.sqrt(magnitude1) * Math.sqrt(magnitude2));
};
const getAlbumImage = track => {
if (track != null && Object.hasOwn(track, 'album') && Object.hasOwn(track.album, 'images') && track.album.images.length > 0) {
if (track.album.images.length > 1) {
return track.album.images[1].url;
} else {
return track.album.images[0].url;
}
} else {
return NO_IMG;
}
}
const getArtistImage = artist => {
if (artist != null && Object.hasOwn(artist, 'images') && artist.images.length > 0) {
if (artist.images.length == 1) {
return artist.images[0].url;
} else {
return artist.images[1].url;
}
} else {
return NO_IMG;
}
}
const getHoroEmoji = sign => {
switch (sign) {
case 'Aries':
return '♈';
case 'Taurus':
return '♉';
case 'Gemini':
return '♊';
case 'Cancer':
return '♋';
case 'Leo':
return '♌';
case 'Virgo':
return '♍';
case 'Libra':
return '♎';
case 'Scorpio':
return '♏';
case 'Sagittarius':
return '♐';
case 'Capricorn':
return '♑';
case 'Aquarius':
return '♒';
case 'Pisces':
return '♓';
default:
return '';
}
}
// Gets the user's basic description based on their average song popularity
const getBasic = score => {
if (score >= 80) {
return "Swiftie 💁♀️💅✨";
} else if (score >= 60) {
return "Pretty ✨b a s i c✨";
} else if (score >= 40) {
return "About Average";
} else if (score >= 20) {
return "Indie Kid";
} else {
return "Apologies for interrupting your grindset";
}
}