Skip to content

Commit 846d69a

Browse files
committed
commits
1 parent dc92f16 commit 846d69a

File tree

4 files changed

+107
-97
lines changed

4 files changed

+107
-97
lines changed

controllers/authController.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ const spotifyService = require('../services/spotifyService');
22
const spotifyApi = require('../utils/spotifyApi');
33

44
const login = (req, res) => {
5-
const authUrl = spotifyService.getAuthUrl();
5+
const scopes = ['user-library-read', 'playlist-modify-private', 'playlist-modify-public'];
6+
const authUrl = spotifyService.getAuthUrl(scopes);
67
res.redirect(authUrl);
78
};
89

@@ -16,13 +17,13 @@ const callback = async (req, res) => {
1617
spotifyApi.setRefreshToken(refresh_token);
1718

1819
res.cookie('spotify_access_token', access_token, { httpOnly: true });
19-
res.redirect('https://main.d1n7z7zw3v28b1.amplifyapp.com/home');
20+
res.redirect('http://localhost:5173/home');
2021
} catch (error) {
21-
res.redirect('https://main.d1n7z7zw3v28b1.amplifyapp.com/login?error=auth_failed');
22+
res.redirect('http://localhost:5173/login?error=auth_failed');
2223
}
2324
};
2425

2526
module.exports = {
2627
login,
2728
callback,
28-
};
29+
};

controllers/playlistController.js

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,23 @@
1+
const SpotifyWebApi = require('spotify-web-api-node');
12
const spotifyService = require('../services/spotifyService');
23

4+
const createSpotifyApiInstance = (accessToken) => {
5+
const spotifyApi = new SpotifyWebApi({
6+
clientId: '5e3eef3570b74a37af3438268b820e32',
7+
clientSecret: 'ecda63e51490449d9c94b26f9fd9571a',
8+
redirectUri: 'http://localhost:4000/auth/callback',
9+
accessToken: accessToken
10+
});
11+
return spotifyApi;
12+
};
13+
314
const getPlaylists = async (req, res) => {
415
try {
16+
const accessToken = req.cookies.spotify_access_token;
17+
const spotifyApi = createSpotifyApiInstance(accessToken);
18+
519
const { offset = 0, limit = 20 } = req.query;
6-
const playlists = await spotifyService.getUserPlaylists(parseInt(offset), parseInt(limit));
20+
const playlists = await spotifyService.getUserPlaylists(parseInt(offset), spotifyApi);
721
res.json(playlists);
822
} catch (error) {
923
res.status(500).json({ error: error.message });
@@ -12,7 +26,10 @@ const getPlaylists = async (req, res) => {
1226

1327
const getLikedSongs = async (req, res) => {
1428
try {
15-
const likedSongs = await spotifyService.getLikedSongs();
29+
const accessToken = req.cookies.spotify_access_token;
30+
const spotifyApi = createSpotifyApiInstance(accessToken);
31+
32+
const likedSongs = await spotifyService.getLikedSongs(spotifyApi);
1633
res.json(likedSongs);
1734
} catch (error) {
1835
console.error('Error in getLikedSongs controller:', error);
@@ -24,9 +41,12 @@ const getLikedSongs = async (req, res) => {
2441

2542
const getPlaylistSongs = async (req, res) => {
2643
try {
44+
const accessToken = req.cookies.spotify_access_token;
45+
const spotifyApi = createSpotifyApiInstance(accessToken);
46+
2747
const { playlistId } = req.params;
28-
const playlist = await spotifyService.getPlaylist(playlistId);
29-
const tracks = await spotifyService.getPlaylistTracks(playlistId);
48+
const playlist = await spotifyService.getPlaylist(playlistId, spotifyApi);
49+
const tracks = await spotifyService.getPlaylistTracks(playlistId, spotifyApi);
3050

3151
res.json({
3252
playlist: playlist,
@@ -39,9 +59,12 @@ const getPlaylistSongs = async (req, res) => {
3959

4060
const createPlaylist = async (req, res) => {
4161
try {
62+
const accessToken = req.cookies.spotify_access_token;
63+
const spotifyApi = createSpotifyApiInstance(accessToken);
64+
4265
const { seedTrackId } = req.body;
4366
const userId = req.query.userId;
44-
const playlistId = await spotifyService.createPlaylistFromSeedTrack(userId, seedTrackId);
67+
const playlistId = await spotifyService.createPlaylistFromSeedTrack(userId, seedTrackId, spotifyApi);
4568
res.json({ message: 'Playlist created successfully', playlistId });
4669
} catch (error) {
4770
res.status(500).json({ error: error.message });
@@ -53,4 +76,4 @@ module.exports = {
5376
getLikedSongs,
5477
getPlaylistSongs,
5578
createPlaylist,
56-
};
79+
};

services/spotifyService.js

Lines changed: 72 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -2,81 +2,67 @@ const spotifyApi = require('../utils/spotifyApi');
22

33
const path = require('path');
44
const playlistImages = [
5-
path.join(__dirname, '../images/1.jpg'),
6-
path.join(__dirname, '../images/2.jpg'),
7-
path.join(__dirname, '../images/3.jpg'),
8-
path.join(__dirname, '../images/4.jpg')
5+
path.join(__dirname, '../images/1.jpg'),
6+
path.join(__dirname, '../images/2.jpg'),
7+
path.join(__dirname, '../images/3.jpg'),
8+
path.join(__dirname, '../images/4.jpg')
99
];
1010

11-
1211
const convertImageToBase64 = async (imagePath) => {
13-
const fs = require('fs').promises;
14-
const buffer = await fs.readFile(imagePath);
15-
return buffer.toString('base64');
12+
const fs = require('fs').promises;
13+
const buffer = await fs.readFile(imagePath);
14+
return buffer.toString('base64');
1615
};
1716

18-
19-
const getAuthUrl = () => {
20-
const scopes = ['user-library-read', 'playlist-modify-private', 'playlist-modify-public'];
21-
return spotifyApi.createAuthorizeURL(scopes, 'state-key');
17+
const getAuthUrl = (scopes) => {
18+
return spotifyApi.createAuthorizeURL(scopes, 'state');
2219
};
2320

2421
const setAccessToken = (accessToken) => {
25-
spotifyApi.setAccessToken(accessToken);
22+
spotifyApi.setAccessToken(accessToken);
2623
};
2724

28-
const getUserPlaylists = async (offset = 0) => {
29-
const playlistResponse = await spotifyApi.getUserPlaylists({ offset });
30-
31-
const likedSongsResponse = await spotifyApi.getMySavedTracks();
32-
33-
return {
34-
playlists: playlistResponse.body,
35-
likedSongs: likedSongsResponse.body
36-
};
25+
const getUserPlaylists = async (offset = 0, spotifyApi) => {
26+
const playlistResponse = await spotifyApi.getUserPlaylists({ offset });
27+
28+
const likedSongsResponse = await spotifyApi.getMySavedTracks();
29+
30+
return {
31+
playlists: playlistResponse.body,
32+
likedSongs: likedSongsResponse.body
33+
};
3734
};
3835

39-
const getLikedSongs = async () => {
40-
try {
41-
const response = await spotifyApi.getMySavedTracks({
42-
limit: 50,
43-
offset: 0
44-
});
45-
return response.body;
46-
} catch (error) {
47-
console.error('Error fetching liked songs:', error);
48-
if (error.statusCode) {
49-
throw new Error(`Spotify API error: ${error.statusCode} - ${error.message}`);
50-
}
51-
throw error;
52-
}
36+
const getLikedSongs = async (spotifyApi) => {
37+
try {
38+
const response = await spotifyApi.getMySavedTracks({
39+
limit: 50,
40+
offset: 0
41+
});
42+
return response.body;
43+
} catch (error) {
44+
console.error('Error fetching liked songs:', error);
45+
if (error.statusCode) {
46+
throw new Error(`Spotify API error: ${error.statusCode} - ${error.message}`);
47+
}
48+
throw error;
49+
}
5350
};
5451

55-
56-
const getPlaylist = async (playlistId) => {
57-
const response = await spotifyApi.getPlaylist(playlistId);
58-
return response.body;
52+
const getPlaylist = async (playlistId, spotifyApi) => {
53+
const response = await spotifyApi.getPlaylist(playlistId);
54+
return response.body;
5955
};
6056

61-
const getPlaylistTracks = async (playlistId) => {
62-
const response = await spotifyApi.getPlaylistTracks(playlistId);
63-
return response.body;
57+
const getPlaylistTracks = async (playlistId, spotifyApi) => {
58+
const response = await spotifyApi.getPlaylistTracks(playlistId);
59+
return response.body;
6460
};
6561

66-
const getTrackRecommendations = async (seedTrackId) => {
67-
const seedTrackFeatures = await spotifyApi.getAudioFeaturesForTrack(seedTrackId);
68-
62+
const getTrackRecommendations = async (seedTrackId, spotifyApi) => {
6963
const response = await spotifyApi.getRecommendations({
70-
seed_tracks: [seedTrackId],
64+
seed_tracks: [seedTrackId],
7165
limit: 100,
72-
target_instrumentalness: seedTrackFeatures.body.instrumentalness,
73-
target_acousticness: seedTrackFeatures.body.acousticness,
74-
min_instrumentalness: Math.max(0, seedTrackFeatures.body.instrumentalness - 0.2),
75-
max_instrumentalness: Math.min(1, seedTrackFeatures.body.instrumentalness + 0.2),
76-
target_key: seedTrackFeatures.body.key,
77-
target_mode: seedTrackFeatures.body.mode,
78-
target_time_signature: seedTrackFeatures.body.time_signature,
79-
min_popularity: 20,
8066
});
8167

8268
const tracks = response.body.tracks;
@@ -90,7 +76,7 @@ const getTrackRecommendations = async (seedTrackId) => {
9076
selectedTracks.push(track);
9177
totalDurationMs += track.duration_ms;
9278
}
93-
79+
9480
if (totalDurationMs >= TARGET_DURATION_MS - MARGIN_MS) {
9581
break;
9682
}
@@ -99,45 +85,45 @@ const getTrackRecommendations = async (seedTrackId) => {
9985
return selectedTracks;
10086
};
10187

102-
const createPlaylist = async (userId, name, description, trackUris) => {
103-
const playlistResponse = await spotifyApi.createPlaylist(userId, {
104-
name,
105-
description,
106-
});
88+
const createPlaylist = async (userId, name, description, trackUris, spotifyApi) => {
89+
const playlistResponse = await spotifyApi.createPlaylist(userId, {
90+
name,
91+
description,
92+
});
10793

108-
const playlistId = playlistResponse.body.id;
109-
await spotifyApi.addTracksToPlaylist(playlistId, trackUris);
94+
const playlistId = playlistResponse.body.id;
95+
await spotifyApi.addTracksToPlaylist(playlistId, trackUris);
11096

111-
const randomImageIndex = Math.floor(Math.random() * playlistImages.length);
112-
const imagePath = playlistImages[randomImageIndex];
113-
114-
const imageData = await convertImageToBase64(imagePath);
115-
await spotifyApi.uploadCustomPlaylistCoverImage(playlistId, imageData);
97+
const randomImageIndex = Math.floor(Math.random() * playlistImages.length);
98+
const imagePath = playlistImages[randomImageIndex];
99+
100+
const imageData = await convertImageToBase64(imagePath);
101+
await spotifyApi.uploadCustomPlaylistCoverImage(playlistId, imageData);
116102

117-
return playlistId;
103+
return playlistId;
118104
};
119105

120-
const createPlaylistFromSeedTrack = async (userId, seedTrackId) => {
121-
const seedTrack = await spotifyApi.getTrack(seedTrackId);
122-
const seedTrackName = seedTrack.body.name;
106+
const createPlaylistFromSeedTrack = async (userId, seedTrackId, spotifyApi) => {
107+
const seedTrack = await spotifyApi.getTrack(seedTrackId);
108+
const seedTrackName = seedTrack.body.name;
123109

124-
const recommendations = await getTrackRecommendations(seedTrackId);
125-
const trackUris = recommendations.map(track => track.uri);
110+
const recommendations = await getTrackRecommendations(seedTrackId, spotifyApi);
111+
const trackUris = recommendations.map(track => track.uri);
126112

127-
const playlistName = 'Groovz';
128-
const description = `Similar songs to ${seedTrackName}`;
113+
const playlistName = 'Groovz';
114+
const description = `Similar songs to ${seedTrackName}`;
129115

130-
const playlistId = await createPlaylist(userId, playlistName, description, trackUris);
131-
return playlistId;
116+
const playlistId = await createPlaylist(userId, playlistName, description, trackUris, spotifyApi);
117+
return playlistId;
132118
};
133119

134120
module.exports = {
135-
getAuthUrl,
136-
setAccessToken,
137-
getUserPlaylists,
138-
getLikedSongs,
139-
getPlaylist,
140-
getPlaylistTracks,
141-
getTrackRecommendations,
142-
createPlaylistFromSeedTrack,
121+
getAuthUrl,
122+
setAccessToken,
123+
getUserPlaylists,
124+
getLikedSongs,
125+
getPlaylist,
126+
getPlaylistTracks,
127+
getTrackRecommendations,
128+
createPlaylistFromSeedTrack,
143129
};

utils/spotifyApi.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ const SpotifyWebApi = require('spotify-web-api-node');
33
const spotifyApi = new SpotifyWebApi({
44
clientId: '5e3eef3570b74a37af3438268b820e32',
55
clientSecret: 'ecda63e51490449d9c94b26f9fd9571a',
6-
redirectUri: 'https://groovz-backend-js.onrender.com/auth/callback',
6+
redirectUri: 'http://localhost:4000/auth/callback',
77
});
88

99
module.exports = spotifyApi;

0 commit comments

Comments
 (0)