-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
519 lines (452 loc) · 14.8 KB
/
app.js
File metadata and controls
519 lines (452 loc) · 14.8 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const passport = require('passport');
const {User, Group} = require('./model/User');
const bcrypt = require('bcrypt');
const session = require('express-session');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger');
const SpotifyWebApi = require('spotify-web-api-node');
const app = express();
const cors = require('cors');
const spotifyApi = new SpotifyWebApi({
clientId: process.env.SPOTIFY_CLIENT_ID,
clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
redirectUri: 'http://localhost:3000/auth/spotify/callback'
});
mongoose.connect('mongodb://localhost:27017/SpotyAPI', {useNewUrlParser: true, useUnifiedTopology: true});
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: false
}));
require('./passport');
app.use(cors({
origin: 'http://localhost:3000'
}));
app.use(function (req, res, next) {
res.setHeader("Content-Security-Policy", "default-src 'none'; connect-src 'self'; script-src 'self'; font-src 'self' http://localhost:3000; style-src 'self' http://fonts.googleapis.com;");
return next();
});
app.use(passport.initialize());
app.use(passport.session());
app.use(express.json());
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.use(router);
// Routes
app.get('/', (req, res) => {
res.send('YSpotyAPI is running');
});
// TODO: Add routes for user registration, login, group management, etc.
require('dotenv').config();
// registration
router.post('/register', async (req, res) => {
const {username, password} = req.body;
console.log('Received request to register user:', username);
// Check if the username and password are provided
if (!username || !password) {
console.log('Username or password not provided');
return res.status(400).send('Username and password are required');
}
// if user already exists
const existingUser = await User.findOne({username});
if (existingUser) {
console.log('User already exists:', username);
return res.status(400).send('User already exists');
}
// password hash
const hashedPassword = await bcrypt.hash(password, 10);
console.log('Password hashed successfully');
// new user
const createUser = async (username, password, spotifyId) => {
try {
// Vérifier si l'utilisateur existe déjà
const existingUser = await User.findOne({username: username});
if (existingUser) {
throw new Error('Username already exists');
}
// Hacher le mot de passe
const hashedPassword = await bcrypt.hash(password, 10);
// Créer un nouvel utilisateur
const newUser = new User({
username: username,
password: hashedPassword,
spotifyId: spotifyId
});
// Enregistrer le nouvel utilisateur
await newUser.save();
return newUser;
} catch (error) {
throw new Error('Error creating user: ' + error.message);
}
};
});
app.post('/register', async (req, res) => {
try {
const {username, password, spotifyId} = req.body;
const newUser = await createUser(username, password, spotifyId);
console.log('User saved successfully:', username);
res.status(201).send('User registered successfully');
} catch (error) {
console.error('Error registering user:', error);
res.status(500).send('Error registering user');
}
});
app.get('/auth/spotify', passport.authenticate('spotify', {
scope: ['user-read-email', 'user-read-private'],
showDialog: true
}));
app.get('/auth/spotify/callback',
passport.authenticate('spotify', {failureRedirect: '/login'}),
function (req, res) {
res.redirect('/');
});
app.post('/login', (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (err) {
return res.status(500).send('An error occurred: ' + err);
}
if (!user) {
return res.status(400).send('Invalid login data: ' + info.message);
}
req.logIn(user, function (err) {
if (err) {
return res.status(500).send('An error occurred: ' + err);
}
return res.send('User logged in');
});
})(req, res, next);
});
app.listen(3000, () => {
console.log('YSpotyAPI is running on port 3000');
console.log(process.env.SPOTIFY_CLIENT_ID);
console.log(process.env.SPOTIFY_CLIENT_SECRET);
});
module.exports = router;
app.use(function (req, res, next) {
res.setHeader("Content-Security-Policy", "default-src 'none'; font-src 'self' http://localhost:3000; style-src 'self' http://fonts.googleapis.com;");
return next();
});
app.get('/auth/spotify', passport.authenticate('spotify', {
scope: ['user-read-email', 'user-read-private'],
showDialog: true
}));
app.get('/auth/spotify/callback',
passport.authenticate('spotify', {failureRedirect: '/login'}),
function (req, res) {
res.redirect('/');
});
app.post('/login', (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (err) {
return res.status(500).send('An error occurred: ' + err);
}
if (!user) {
return res.status(400).send('Invalid login data: ' + info.message);
}
req.logIn(user, function (err) {
if (err) {
return res.status(500).send('An error occurred: ' + err);
}
return res.send('User logged in');
});
})(req, res, next);
});
// Join a group
router.post('/joinGroup', async (req, res) => {
const {groupName} = req.body;
const currentUser = req.user;
if (!groupName) {
return res.status(400).send('Group name is required');
}
let group = await Group.findOne({name: groupName});
if (!group) {
group = new Group({name: groupName, chief: currentUser._id});
} else {
if (currentUser.group) {
const oldGroup = await Group.findById(currentUser.group);
oldGroup.users.pull(currentUser._id);
if (oldGroup.chief.equals(currentUser._id)) {
if (oldGroup.users.length > 0) {
oldGroup.chief = oldGroup.users[0];
} else {
await Group.findByIdAndDelete(oldGroup._id);
}
}
await oldGroup.save();
}
group.users.push(currentUser._id);
}
currentUser.group = group._id;
await currentUser.save();
await group.save();
res.send('User joined the group successfully');
});
// CONSULT GROUPS
// Fetch all groups
router.get('/groups', async (req, res) => {
const groups = await Group.find().populate('users', 'username');
const groupsInfo = groups.map(group => ({
groupName: group.name,
numberOfUsers: group.users.length
}));
res.json(groupsInfo);
});
// Fetch all users in a specific group
router.get('/groupUsers/:groupId', async (req, res) => {
const {groupId} = req.params;
const group = await Group.findById(groupId).populate('users', 'username');
if (!group) {
return res.status(404).send('Group not found');
}
const usersInfo = group.users.map(user => ({
username: user.username,
isChief: user._id.equals(group.chief),
spotifyUsername: user.profile ? user.profile.username : null,
currentTrack: user.profile ? user.profile.currentTrack : null,
activeDeviceName: user.profile ? user.profile.activeDeviceName : null
}));
res.json(usersInfo);
});
// Leaving group
router.post('/leaveGroup', async (req, res) => {
const currentUser = req.user;
if (!currentUser.group) {
return res.status(400).send('User is not in a group');
}
const group = await Group.findById(currentUser.group);
group.users.pull(currentUser._id);
if (group.chief.equals(currentUser._id)) {
if (group.users.length > 0) {
group.chief = group.users[0];
} else {
await Group.findByIdAndDelete(group._id);
}
}
await group.save();
currentUser.group = null;
await currentUser.save();
res.send('User left the group successfully');
});
// Synchronization
router.post('/syncPlayback', async (req, res) => {
const currentUser = req.user;
if (!currentUser.group || !currentUser.group.chief.equals(currentUser._id)) {
return res.status(400).send('User is not the chief of a group');
}
spotifyApi.setAccessToken(currentUser.accessToken);
const playback = await spotifyApi.getMyCurrentPlaybackState();
const trackUri = playback.body.item.uri;
const positionMs = playback.body.progress_ms;
const group = await Group.findById(currentUser.group).populate('users');
for (const user of group.users) {
if (!user.equals(currentUser)) {
spotifyApi.setAccessToken(user.accessToken);
await spotifyApi.play({uris: [trackUri], position_ms: positionMs});
}
}
res.send('Playback synchronized successfully');
});
// Playlist
router.post('/createPlaylist', async (req, res) => {
const currentUser = req.user;
const {targetUser} = req.body;
const target = await User.findById(targetUser);
if (!target || !target.group.equals(currentUser.group)) {
return res.status(400).send('Target user is not in the same group');
}
spotifyApi.setAccessToken(target.accessToken);
const topTracks = await spotifyApi.getMyTopTracks({limit: 10});
const trackUris = topTracks.body.items.map(track => track.uri);
spotifyApi.setAccessToken(currentUser.accessToken);
const playlist = await spotifyApi.createPlaylist(currentUser.spotifyId, 'Top 10 Tracks', {public: false});
await spotifyApi.addTracksToPlaylist(playlist.body.id, trackUris);
res.send('Playlist created successfully');
});
// Analyse des Titres Likés d'un utilisateur pour déduire sa personnalité
app.get('/user/personality', async (req, res) => {
try {
const userId = req.query.userId; // Supposons que l'ID de l'utilisateur soit passé en paramètre de requête
// Récupérer les Titres Likés de l'utilisateur à partir de la base de données
const likedTracks = await LikedTrack.find({ userId: userId });
if (likedTracks.length === 0) {
res.status(404).send('Aucun titre liké trouvé pour cet utilisateur');
return;
}
// Analyser les Titres Likés pour déduire la personnalité de l'utilisateur
const danceAttraction = calculateDanceAttraction(likedTracks);
const averageTempo = calculateAverageTempo(likedTracks);
const vocalPreference = calculateVocalPreference(likedTracks);
const mood = calculateMood(likedTracks);
// Générer le portrait de personnalité de l'utilisateur
const userPersonality = {
danceAttraction: danceAttraction,
averageTempo: averageTempo,
vocalPreference: vocalPreference,
mood: mood
};
res.status(200).json(userPersonality);
} catch (error) {
console.error('Erreur lors de la récupération de la personnalité de l\'utilisateur:', error);
res.status(500).send('Erreur lors de la récupération de la personnalité de l\'utilisateur');
}
});
/**
* @swagger
* components:
* schemas:
* User:
* type: object
* required:
* - username
* - password
* properties:
* username:
* type: string
* password:
* type: string
*
*/
/**
* @swagger
* /register:
* post:
* summary: Register a new user
* consumes:
* - application/json
* parameters:
* - in: body
* name: user
* description: The user to create.
* schema:
* $ref: '#/components/schemas/User'
* responses:
* 200:
* description: User registered successfully
* 400:
* description: Username is already taken or username and password are required
*/
/**
* @swagger
* /login:
* post:
* summary: Log in a user
* consumes:
* - application/json
* parameters:
* - in: body
* name: user
* description: The user to log in.
* schema:
* type: object
* required:
* - username
* - password
* properties:
* username:
* type: string
* password:
* type: string
* responses:
* 200:
* description: User logged in
* 400:
* description: Invalid login data
*/
/**
* @swagger
* /joinGroup:
* post:
* summary: Join a group
* consumes:
* - application/json
* parameters:
* - in: body
* name: group
* description: The group to join.
* schema:
* type: object
* required:
* - groupName
* properties:
* groupName:
* type: string
* responses:
* 200:
* description: User joined the group successfully
* 400:
* description: Group name is required
*/
/**
* @swagger
* /groups:
* get:
* summary: Fetch all groups
* responses:
* 200:
* description: List of all groups
*/
/**
* @swagger
* /groupUsers/{groupId}:
* get:
* summary: Fetch all users in a specific group
* parameters:
* - in: path
* name: groupId
* required: true
* schema:
* type: string
* responses:
* 200:
* description: List of all users in the group
* 404:
* description: Group not found
*/
/**
* @swagger
* /leaveGroup:
* post:
* summary: Leave a group
* responses:
* 200:
* description: User left the group successfully
* 400:
* description: User is not in a group
*/
/**
* @swagger
* /syncPlayback:
* post:
* summary: Synchronize playback
* responses:
* 200:
* description: Playback synchronized successfully
* 400:
* description: User is not the chief of a group
*/
/**
* @swagger
* /createPlaylist:
* post:
* summary: Create a playlist
* consumes:
* - application/json
* parameters:
* - in: body
* name: targetUser
* description: The target user to create a playlist for.
* schema:
* type: object
* required:
* - targetUser
* properties:
* targetUser:
* type: string
* responses:
* 200:
* description: Playlist created successfully
* 400:
* description: Target user is not in the same group
*/